qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
listlengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
|---|---|---|---|---|---|
2,400,605
|
I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications
so I'm considering PHP, Python or ruby, I prefer python because it's better syntax than other( I feel it closer to Delphi), also I want to deploy the application to shared hosting, specially Linux.
so as Delphi developer, what do you choose to develop web application?
|
2010/03/08
|
[
"https://Stackoverflow.com/questions/2400605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235131/"
] |
Why should an answer be different if the question was asked by a Delphi programmer, than a programmer from any other platform? Any decent language should be fun to learn, regardless of the tool you are using right now.
That said, I myself walked a way from Borland Pascal and Delphi (quite some time ago), over PHP and ASP.NET (using C#). Right now I am working almost exclusively on Ruby (and occasionally Rails) and I am perfectly happy with it. But, then again, it's matter of personal preference: I really enjoy Ruby's pure object-orientation and functional capabilities, as well as dynamical nature of a scripting language. So, it's all up to you and your personal preferences.
Although, one thing I can surely recommend is to stick with one of the major web-players, for pragmatic reasons: PHP, Python, Ruby, ASP.NET or possibly Java. I'm sorry to say that, but I don't think Pascaloid languages have any future anymore.
|
Actually, the answer probably is ASP.NET using C#. You'll see (ex-)Borland engineering syntax that looks quite familiar coming from Delphi. To deploy on Linux have a look at the [Mono project](http://www.mono-project.com/Main_Page).
|
2,400,605
|
I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications
so I'm considering PHP, Python or ruby, I prefer python because it's better syntax than other( I feel it closer to Delphi), also I want to deploy the application to shared hosting, specially Linux.
so as Delphi developer, what do you choose to develop web application?
|
2010/03/08
|
[
"https://Stackoverflow.com/questions/2400605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235131/"
] |
Only good answer - C# ;) Seriously ;)
Why? Anders Hejlsberg. He made it. It is the direct continuation of his work that started with Turbo Pascal and went over to Delphi... then Microsoft hired him and he moved from Pascal to C (core langauge) and made C#.
Read it up on <http://en.wikipedia.org/wiki/Anders_Hejlsberg>
If you come from Delphi, you will love it ;)
|
I have done a fairly large (4-5 FTE) project based on webhub (www.href.com). I can certainly advise this if it is a webapp for internal use.
|
2,400,605
|
I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications
so I'm considering PHP, Python or ruby, I prefer python because it's better syntax than other( I feel it closer to Delphi), also I want to deploy the application to shared hosting, specially Linux.
so as Delphi developer, what do you choose to develop web application?
|
2010/03/08
|
[
"https://Stackoverflow.com/questions/2400605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235131/"
] |
Try Morfik <http://www.morfik.com/>
P.S.
It looked promising a few years ago, but after I digged it deeper I must admit that it's quite limited web development environment for a very basic web development.
|
Only good answer - C# ;) Seriously ;)
Why? Anders Hejlsberg. He made it. It is the direct continuation of his work that started with Turbo Pascal and went over to Delphi... then Microsoft hired him and he moved from Pascal to C (core langauge) and made C#.
Read it up on <http://en.wikipedia.org/wiki/Anders_Hejlsberg>
If you come from Delphi, you will love it ;)
|
2,400,605
|
I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications
so I'm considering PHP, Python or ruby, I prefer python because it's better syntax than other( I feel it closer to Delphi), also I want to deploy the application to shared hosting, specially Linux.
so as Delphi developer, what do you choose to develop web application?
|
2010/03/08
|
[
"https://Stackoverflow.com/questions/2400605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235131/"
] |
I agree about Intraweb, but Delphi itself is still a good language to build websites with. You could start a CGI application or an ISAPI-extesion. You could also check out <http://xxm.sf.net> , it's an open-source project I started that offers a few extra's:
* You can mix HTML and Delphi code into the same files (much like PHP)
* These files get auto-compiled to a Delphi project so you can see the results by refreshing the web-browser (much like PHP)
* You can load the library with a number of 'handlers':
+ there's a IInternetProtocol implementation to use with InternetExplorer directly (really handy for development
+ there's an ISAPI extension that loads the library (and auto-updates is, really handy for updates on live-environments)
+ there's a stand-alone HTTP executable or NT-Service
+ there's even a FireFox plugin and Apache module in the making.
|
I'm a long-time Delphi developer myself and had to do some web work recently, I decided to use ASP.Net with [Delphi Prism](http://www.embarcadero.com/products/delphi-prism) and found myself right at home since I didn't have to learn a new language, just a new framework.
|
2,400,605
|
I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications
so I'm considering PHP, Python or ruby, I prefer python because it's better syntax than other( I feel it closer to Delphi), also I want to deploy the application to shared hosting, specially Linux.
so as Delphi developer, what do you choose to develop web application?
|
2010/03/08
|
[
"https://Stackoverflow.com/questions/2400605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235131/"
] |
If you feel like stretching your muscles, you could try out [Seaside](http://www.seaside.st/).
Seaside's a Smalltalk framework (so working with it will feel pretty much like working with Ruby) that lets you write your website just like you'd build a desktop application. You can split your code up into components that you can assemble much like you'd work with TComponents (programmatically, at least).
|
Actually, the answer probably is ASP.NET using C#. You'll see (ex-)Borland engineering syntax that looks quite familiar coming from Delphi. To deploy on Linux have a look at the [Mono project](http://www.mono-project.com/Main_Page).
|
2,400,605
|
I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications
so I'm considering PHP, Python or ruby, I prefer python because it's better syntax than other( I feel it closer to Delphi), also I want to deploy the application to shared hosting, specially Linux.
so as Delphi developer, what do you choose to develop web application?
|
2010/03/08
|
[
"https://Stackoverflow.com/questions/2400605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235131/"
] |
PHP is a pretty simple answer.
One reason is there is both Delphi4PHP (the rather cryptic IDE licensed by Embarcadero which in my estimation is really only for Web Apps (not for doing whole site)s) and PHP4Delphi (the pretty awesome Delphi Component that lets you compile your Delphi code to PHP Extensions).
|
Actually, the answer probably is ASP.NET using C#. You'll see (ex-)Borland engineering syntax that looks quite familiar coming from Delphi. To deploy on Linux have a look at the [Mono project](http://www.mono-project.com/Main_Page).
|
2,400,605
|
I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications
so I'm considering PHP, Python or ruby, I prefer python because it's better syntax than other( I feel it closer to Delphi), also I want to deploy the application to shared hosting, specially Linux.
so as Delphi developer, what do you choose to develop web application?
|
2010/03/08
|
[
"https://Stackoverflow.com/questions/2400605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235131/"
] |
I agree about Intraweb, but Delphi itself is still a good language to build websites with. You could start a CGI application or an ISAPI-extesion. You could also check out <http://xxm.sf.net> , it's an open-source project I started that offers a few extra's:
* You can mix HTML and Delphi code into the same files (much like PHP)
* These files get auto-compiled to a Delphi project so you can see the results by refreshing the web-browser (much like PHP)
* You can load the library with a number of 'handlers':
+ there's a IInternetProtocol implementation to use with InternetExplorer directly (really handy for development
+ there's an ISAPI extension that loads the library (and auto-updates is, really handy for updates on live-environments)
+ there's a stand-alone HTTP executable or NT-Service
+ there's even a FireFox plugin and Apache module in the making.
|
PHP is a pretty simple answer.
One reason is there is both Delphi4PHP (the rather cryptic IDE licensed by Embarcadero which in my estimation is really only for Web Apps (not for doing whole site)s) and PHP4Delphi (the pretty awesome Delphi Component that lets you compile your Delphi code to PHP Extensions).
|
2,400,605
|
I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications
so I'm considering PHP, Python or ruby, I prefer python because it's better syntax than other( I feel it closer to Delphi), also I want to deploy the application to shared hosting, specially Linux.
so as Delphi developer, what do you choose to develop web application?
|
2010/03/08
|
[
"https://Stackoverflow.com/questions/2400605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235131/"
] |
If you feel like stretching your muscles, you could try out [Seaside](http://www.seaside.st/).
Seaside's a Smalltalk framework (so working with it will feel pretty much like working with Ruby) that lets you write your website just like you'd build a desktop application. You can split your code up into components that you can assemble much like you'd work with TComponents (programmatically, at least).
|
I'm a long-time Delphi developer myself and had to do some web work recently, I decided to use ASP.Net with [Delphi Prism](http://www.embarcadero.com/products/delphi-prism) and found myself right at home since I didn't have to learn a new language, just a new framework.
|
31,682,981
|
I am a newbie in Django un I want to write a Test for Django Web-poll application (<https://docs.djangoproject.com/en/1.8/intro/tutorial01/>)
but I got this error:
```
devuser@localhost:~/Django-apps/poolApp$ django-admin shell --plain --no-startup
Traceback (most recent call last):
File "/usr/local/bin/django-admin", line 9, in <module>
load_entry_point('Django==1.8.3', 'console_scripts', 'django-admin')()
File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/core/management/base.py", line 405, in run_from_argv
connections.close_all()
File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/db/utils.py", line 258, in close_all
for alias in self:
File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/db/utils.py", line 252, in __iter__
return iter(self.databases)
File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/utils/functional.py", line 60, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/db/utils.py", line 151, in databases
self._databases = settings.DATABASES
File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/conf/__init__.py", line 48, in __getattr__
self._setup(name)
File "/usr/local/lib/python2.7/dist-packages/Django-1.8.3-py2.7.egg/django/conf/__init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
```
I would like to know what is the best approach to do it:
define the environment variable DJANGO\_SETTINGS\_MODULE or call settings.configure()
|
2015/07/28
|
[
"https://Stackoverflow.com/questions/31682981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4450024/"
] |
Use `manage.py`, not `django-admin`.
|
What does work is using
```
django-admin shell --plain --no-startup --pythonpath "." --settings "myproject.settings"
```
while you are in the root of your django app.
However `manage.py shell` (or the amazing `shell_plus` from django\_extensions <https://github.com/django-extensions/django-extensions>) is recommended instead
|
46,034,924
|
When I try to run python manage.py runserver I get this error:
```
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/user/lokvi/lokvi_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/Users/user/lokvi/lokvi_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 307, in execute
settings.INSTALLED_APPS
File "/Users/user/lokvi/lokvi_env/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__
self._setup(name)
File "/Users/user/lokvi/lokvi_env/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup
self._wrapped = Settings(settings_module)
File "/Users/user/lokvi/lokvi_env/lib/python2.7/site-packages/django/conf/__init__.py", line 110, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named settings
```
I have python 2.7 in my virtualenv. I noticed strange thing at the last lines of my stack trace, the line before the last line has path that goes like that: `/lokvi_env/lib/python2.7` etc
But the last line goes like that `System/Library/Frameworks` etc, so it seems like path has changed from virtualenv to system. Is it ok?
|
2017/09/04
|
[
"https://Stackoverflow.com/questions/46034924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3565829/"
] |
You need to import `settings` module
```
from django.conf import settings
```
|
Oh, It was not the python path specific question, sorry. I just needed `__init__.py` in settings module inside of my project, since there were no settings it tried to find it in python lib itself and couldn't, I believe.
|
2,134,941
|
For a package of mine, I have a README.rst file that is read into the setup.py's long description like so:
```
readme = open('README.rst', 'r')
README_TEXT = readme.read()
readme.close()
setup(
...
long_description = README_TEXT,
....
)
```
This way that I can have the README file show up on my [github page](http://github.com/jasonbaker/envbuilder) every time I commit and on the [pypi page](http://pypi.python.org/pypi/envbuilder/) every time I `python setup.py register`. There's only one problem. I'd like the github page to say something like "This document reflects a pre-release version of envbuilder. For the most recent release, see pypi."
I could just put those lines in README.rst and delete them before I `python setup.py register`, but I know that there's going to be a time that I forget to remove the sentences before I push to pypi.
I'm trying to think of the best way to automate this so I don't have to worry about it. Anyone have any ideas? Is there any setuptools/distutils magic I can do?
|
2010/01/25
|
[
"https://Stackoverflow.com/questions/2134941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
Another option is to side-step the issue completely by adding a paragraph that works in both environments: "The latest unstable code is on github. The latest stable kits are on pypi."
After all, why assume that pypi people don't want to be pointed to github? This would be more helpful to both audiences, and simplifies your setup.py.
|
You could always do this:
```
GITHUB_ALERT = 'This document reflects a pre-release version...'
readme = open('README.rst', 'r')
README_TEXT = readme.read().replace(GITHUB_ALERT, '')
readme.close()
setup(
...
long_description = README_TEXT,
....
)
```
But then you'd have to keep that `GITHUB_ALERT` string in sync with the actual wording of the `README`. Using a regular expression instead (to, say, match a line beginning with *Note for Github Users:* or something) might give you a little more flexibility.
|
2,134,941
|
For a package of mine, I have a README.rst file that is read into the setup.py's long description like so:
```
readme = open('README.rst', 'r')
README_TEXT = readme.read()
readme.close()
setup(
...
long_description = README_TEXT,
....
)
```
This way that I can have the README file show up on my [github page](http://github.com/jasonbaker/envbuilder) every time I commit and on the [pypi page](http://pypi.python.org/pypi/envbuilder/) every time I `python setup.py register`. There's only one problem. I'd like the github page to say something like "This document reflects a pre-release version of envbuilder. For the most recent release, see pypi."
I could just put those lines in README.rst and delete them before I `python setup.py register`, but I know that there's going to be a time that I forget to remove the sentences before I push to pypi.
I'm trying to think of the best way to automate this so I don't have to worry about it. Anyone have any ideas? Is there any setuptools/distutils magic I can do?
|
2010/01/25
|
[
"https://Stackoverflow.com/questions/2134941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
You can just use a ReST comment with some text like "split here", and then split on that in your setup.py. Ian Bicking does that in virtualenv with [index.txt](http://bitbucket.org/ianb/virtualenv/src/77d301cdbf8c/docs/index.txt) and [setup.py](http://bitbucket.org/ianb/virtualenv/src/tip/setup.py).
|
You could always do this:
```
GITHUB_ALERT = 'This document reflects a pre-release version...'
readme = open('README.rst', 'r')
README_TEXT = readme.read().replace(GITHUB_ALERT, '')
readme.close()
setup(
...
long_description = README_TEXT,
....
)
```
But then you'd have to keep that `GITHUB_ALERT` string in sync with the actual wording of the `README`. Using a regular expression instead (to, say, match a line beginning with *Note for Github Users:* or something) might give you a little more flexibility.
|
2,134,941
|
For a package of mine, I have a README.rst file that is read into the setup.py's long description like so:
```
readme = open('README.rst', 'r')
README_TEXT = readme.read()
readme.close()
setup(
...
long_description = README_TEXT,
....
)
```
This way that I can have the README file show up on my [github page](http://github.com/jasonbaker/envbuilder) every time I commit and on the [pypi page](http://pypi.python.org/pypi/envbuilder/) every time I `python setup.py register`. There's only one problem. I'd like the github page to say something like "This document reflects a pre-release version of envbuilder. For the most recent release, see pypi."
I could just put those lines in README.rst and delete them before I `python setup.py register`, but I know that there's going to be a time that I forget to remove the sentences before I push to pypi.
I'm trying to think of the best way to automate this so I don't have to worry about it. Anyone have any ideas? Is there any setuptools/distutils magic I can do?
|
2010/01/25
|
[
"https://Stackoverflow.com/questions/2134941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
You can just use a ReST comment with some text like "split here", and then split on that in your setup.py. Ian Bicking does that in virtualenv with [index.txt](http://bitbucket.org/ianb/virtualenv/src/77d301cdbf8c/docs/index.txt) and [setup.py](http://bitbucket.org/ianb/virtualenv/src/tip/setup.py).
|
Another option is to side-step the issue completely by adding a paragraph that works in both environments: "The latest unstable code is on github. The latest stable kits are on pypi."
After all, why assume that pypi people don't want to be pointed to github? This would be more helpful to both audiences, and simplifies your setup.py.
|
64,375,499
|
```
def save_weights(self, filename = "./" + str(timestamp) + "-tfsave"):
### save model weights
saver = tf.train.Saver()
saver.save(self.sess, filename)
print("saved to:",filename)
```
---
UnknownError Traceback (most recent call last)
~\Anaconda3\envs\tf\lib\site-packages\tensorflow\_core\python\client\session.py in \_do\_call(self, fn, \*args)
1364 try:
-> 1365 return fn(\*args)
1366 except errors.OpError as e:
~\Anaconda3\envs\tf\lib\site-packages\tensorflow\_core\python\client\session.py in \_run\_fn(feed\_dict, fetch\_list, target\_list, options, run\_metadata)
1349 return self.\_call\_tf\_sessionrun(options, feed\_dict, fetch\_list,
-> 1350 target\_list, run\_metadata)
1351
~\Anaconda3\envs\tf\lib\site-packages\tensorflow\_core\python\client\session.py in \_call\_tf\_sessionrun(self, options, feed\_dict, fetch\_list, target\_list, run\_metadata)
1442 fetch\_list, target\_list,
-> 1443 run\_metadata)
1444
UnknownError: Failed to rename: ./2020-10-15\_18:28-tfsave.data-00000-of-00001.tempstate9752799594239982307 to: ./2020-10-15\_18:28-tfsave.data-00000-of-00001 : The parameter is incorrect.
; Unknown error
[[{{node save/SaveV2}}]]
|
2020/10/15
|
[
"https://Stackoverflow.com/questions/64375499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12137831/"
] |
You can achieve this without javascript by using a [media-query](https://www.w3schools.com/css/css_rwd_mediaqueries.asp):
```css
#show-nav {
display: none;
background-color: red;
}
/* if screen width is smaller than 720px, #show-nav will be a block */
@media only screen and (max-width: 720px) {
#show-nav {
display: block;
}
}
```
```html
<nav id="show-nav">
Navbar
</nav>
```
|
You could use only css to do so.
DEMO (make it full page)
------------------------
```css
body{
margin: 0;
}
nav{
width: 100vw;
background:yellow;
}
@media only screen and (min-width: 720px){
nav{
background:red;
}
}
```
```html
<nav>
<ul>
<li>Welcome</li>
</ul>
</nav
```
|
64,375,499
|
```
def save_weights(self, filename = "./" + str(timestamp) + "-tfsave"):
### save model weights
saver = tf.train.Saver()
saver.save(self.sess, filename)
print("saved to:",filename)
```
---
UnknownError Traceback (most recent call last)
~\Anaconda3\envs\tf\lib\site-packages\tensorflow\_core\python\client\session.py in \_do\_call(self, fn, \*args)
1364 try:
-> 1365 return fn(\*args)
1366 except errors.OpError as e:
~\Anaconda3\envs\tf\lib\site-packages\tensorflow\_core\python\client\session.py in \_run\_fn(feed\_dict, fetch\_list, target\_list, options, run\_metadata)
1349 return self.\_call\_tf\_sessionrun(options, feed\_dict, fetch\_list,
-> 1350 target\_list, run\_metadata)
1351
~\Anaconda3\envs\tf\lib\site-packages\tensorflow\_core\python\client\session.py in \_call\_tf\_sessionrun(self, options, feed\_dict, fetch\_list, target\_list, run\_metadata)
1442 fetch\_list, target\_list,
-> 1443 run\_metadata)
1444
UnknownError: Failed to rename: ./2020-10-15\_18:28-tfsave.data-00000-of-00001.tempstate9752799594239982307 to: ./2020-10-15\_18:28-tfsave.data-00000-of-00001 : The parameter is incorrect.
; Unknown error
[[{{node save/SaveV2}}]]
|
2020/10/15
|
[
"https://Stackoverflow.com/questions/64375499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12137831/"
] |
You can achieve this without javascript by using a [media-query](https://www.w3schools.com/css/css_rwd_mediaqueries.asp):
```css
#show-nav {
display: none;
background-color: red;
}
/* if screen width is smaller than 720px, #show-nav will be a block */
@media only screen and (max-width: 720px) {
#show-nav {
display: block;
}
}
```
```html
<nav id="show-nav">
Navbar
</nav>
```
|
```
@media only screen and (max-width: 720px) {
#show-nav {
display: block;
}
}
```
|
50,539,199
|
So I am trying to find a way to "merge" a dependency list which is in the form of a dictionary in python, and I haven't been able to come up with a solution. So imagine a graph along the lines of this: (all of the lines are downward pointing arrows in this directed graph)
```
1 2 4
\ / / \
3 5 8
\ / \ \
6 7 9
```
this graph would produce a dependency dictionary that looks like this:
```
{3:[1,2], 5:[4], 6:[3,5], 7:[5], 8:[4], 9:[8], 1:[], 2:[], 4:[]}
```
such that keys are nodes in the graph, and their values are the nodes they are dependent on.
I am trying to convert this into a total ancestry list in terms of a tree, so that each node is a key, and its value is a list of ALL nodes that lead to it, not just it's immediate parents. The resulting dictionary would be:
```
{3:[1,2], 5:[4], 6:[3, 5, 1, 2, 4], 7:[5, 4], 8:[4], 9:[8, 4], 1:[], 2:[], 3:[]}
```
Any suggestions on how to solve this? I have been banging my head into it for a while, tried a recursive solution that I haven't been able to get working.
|
2018/05/26
|
[
"https://Stackoverflow.com/questions/50539199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9849681/"
] |
You can use a chained `dict comprehension` with `list comprehension` for up to two nodes.
```
>>> {k: v + [item for i in v for item in d.get(i, [])] for k,v in d.items()}
{3: [1, 2],
5: [4],
6: [3, 5, 1, 2, 4],
7: [5, 4],
8: [4],
9: [8, 4],
1: [],
2: [],
4: []}
```
---
For unlimited depth, you can use a recursive approach
```
def get_ant(node, d):
if node:
return d.get(node,[]) + [item for x in d.get(node, []) for item in get_ant(x, d) ]
return []
```
Then,
```
>>> get_ant(6, d)
[3, 5, 1, 2, 10, 4]
```
To get all cases:
```
>>> {k: get_ant(k, d) for k in d.keys()}
{3: [1, 2, 10],
5: [4],
6: [3, 5, 1, 2, 10, 4],
7: [5, 4],
8: [4],
9: [8, 4],
1: [10],
2: [],
4: []}
```
|
Here's a really simple way to do it.
```
In [22]: a
Out[22]: {1: [], 2: [], 3: [1, 2], 4: [], 5: [4], 6: [3, 5], 7: [5], 8: [4], 9: [8]}
In [23]: final = {}
In [24]: for key in a:
...: nodes = set()
...:
...: for val in a[key]:
...: nodes.add(val)
...: if val in a:
...: nodes.update(set(a[val]))
...:
...: final[key] = list(nodes)
In [25]: final
Out[25]:
{1: [],
2: [],
3: [1, 2],
4: [],
5: [4],
6: [3, 1, 2, 5, 4],
7: [5, 4],
8: [4],
9: [8, 4]}
```
|
24,635,064
|
Here is my problem with urllib in python 3.
I wrote a piece of code which works well in Python 2.7 and is using urllib2. It goes to the page on Internet (which requires authorization) and grabs me the info from that page.
The real problem for me is that I can't make my code working in python 3.4 because there is no urllib2, and urllib works differently; even after few hours of googling and reading I got nothing. So if somebody can help me to solve this, I'd really appreciate that help.
Here is my code:
```
request = urllib2.Request('http://mysite/admin/index.cgi?index=127')
base64string = base64.encodestring('%s:%s' % ('login', 'password')).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
resulttext = result.read()
```
|
2014/07/08
|
[
"https://Stackoverflow.com/questions/24635064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816874/"
] |
Thankfully to you guys I finally figured out the way it works.
Here is my code:
```
request = urllib.request.Request('http://mysite/admin/index.cgi?index=127')
base64string = base64.b64encode(bytes('%s:%s' % ('login', 'password'),'ascii'))
request.add_header("Authorization", "Basic %s" % base64string.decode('utf-8'))
result = urllib.request.urlopen(request)
resulttext = result.read()
```
After all, there is one more difference with urllib: the `resulttext` variable in my case had the type of `<bytes>` instead of `<str>`, so to do something with text inside it I had to decode it:
```
text = resulttext.decode(encoding='utf-8',errors='ignore')
```
|
What about [urllib.request](https://docs.python.org/dev/library/urllib.request.html) ? It seems it has everything you need.
```
import base64
import urllib.request
request = urllib.request.Request('http://mysite/admin/index.cgi?index=127')
base64string = bytes('%s:%s' % ('login', 'password'), 'ascii')
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib.request.urlopen(request)
resulttext = result.read()
```
|
24,635,064
|
Here is my problem with urllib in python 3.
I wrote a piece of code which works well in Python 2.7 and is using urllib2. It goes to the page on Internet (which requires authorization) and grabs me the info from that page.
The real problem for me is that I can't make my code working in python 3.4 because there is no urllib2, and urllib works differently; even after few hours of googling and reading I got nothing. So if somebody can help me to solve this, I'd really appreciate that help.
Here is my code:
```
request = urllib2.Request('http://mysite/admin/index.cgi?index=127')
base64string = base64.encodestring('%s:%s' % ('login', 'password')).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
resulttext = result.read()
```
|
2014/07/08
|
[
"https://Stackoverflow.com/questions/24635064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816874/"
] |
What about [urllib.request](https://docs.python.org/dev/library/urllib.request.html) ? It seems it has everything you need.
```
import base64
import urllib.request
request = urllib.request.Request('http://mysite/admin/index.cgi?index=127')
base64string = bytes('%s:%s' % ('login', 'password'), 'ascii')
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib.request.urlopen(request)
resulttext = result.read()
```
|
An alternative using [OpenerDirector](https://docs.python.org/3.9/library/urllib.request.html#urllib.request.OpenerDirector) that installs the auth headers for all future urllib requests
```py
login_pass = base64.b64encode(f'{login}:{password}'.encode()).decode()
opener = urllib.request.build_opener()
opener.addheaders = [('Authorization', f'Basic {login_pass}')]
urllib.request.install_opener(opener)
response = urllib.request.urlopen(API_URL)
print(response.read().decode())
```
A further example using [HTTPBasicAuthHandler](https://docs.python.org/3.9/library/urllib.request.html#urllib.request.HTTPBasicAuthHandler) although a bit more work required if need to [send credentials unconditionally](https://stackoverflow.com/a/33509568/175584):
```py
password_mgr = urllib.request.HTTPPasswordMgrWithPriorAuth()
password_mgr.add_password(None, API_URL, login, password, is_authenticated=True)
auth_handler = request.HTTPBasicAuthHandler(password_mgr)
opener = request.build_opener(auth_handler)
request.install_opener(opener)
response = urllib.request.urlopen(API_URL)
print(response.read().decode())
```
|
24,635,064
|
Here is my problem with urllib in python 3.
I wrote a piece of code which works well in Python 2.7 and is using urllib2. It goes to the page on Internet (which requires authorization) and grabs me the info from that page.
The real problem for me is that I can't make my code working in python 3.4 because there is no urllib2, and urllib works differently; even after few hours of googling and reading I got nothing. So if somebody can help me to solve this, I'd really appreciate that help.
Here is my code:
```
request = urllib2.Request('http://mysite/admin/index.cgi?index=127')
base64string = base64.encodestring('%s:%s' % ('login', 'password')).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
resulttext = result.read()
```
|
2014/07/08
|
[
"https://Stackoverflow.com/questions/24635064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816874/"
] |
Thankfully to you guys I finally figured out the way it works.
Here is my code:
```
request = urllib.request.Request('http://mysite/admin/index.cgi?index=127')
base64string = base64.b64encode(bytes('%s:%s' % ('login', 'password'),'ascii'))
request.add_header("Authorization", "Basic %s" % base64string.decode('utf-8'))
result = urllib.request.urlopen(request)
resulttext = result.read()
```
After all, there is one more difference with urllib: the `resulttext` variable in my case had the type of `<bytes>` instead of `<str>`, so to do something with text inside it I had to decode it:
```
text = resulttext.decode(encoding='utf-8',errors='ignore')
```
|
An alternative using [OpenerDirector](https://docs.python.org/3.9/library/urllib.request.html#urllib.request.OpenerDirector) that installs the auth headers for all future urllib requests
```py
login_pass = base64.b64encode(f'{login}:{password}'.encode()).decode()
opener = urllib.request.build_opener()
opener.addheaders = [('Authorization', f'Basic {login_pass}')]
urllib.request.install_opener(opener)
response = urllib.request.urlopen(API_URL)
print(response.read().decode())
```
A further example using [HTTPBasicAuthHandler](https://docs.python.org/3.9/library/urllib.request.html#urllib.request.HTTPBasicAuthHandler) although a bit more work required if need to [send credentials unconditionally](https://stackoverflow.com/a/33509568/175584):
```py
password_mgr = urllib.request.HTTPPasswordMgrWithPriorAuth()
password_mgr.add_password(None, API_URL, login, password, is_authenticated=True)
auth_handler = request.HTTPBasicAuthHandler(password_mgr)
opener = request.build_opener(auth_handler)
request.install_opener(opener)
response = urllib.request.urlopen(API_URL)
print(response.read().decode())
```
|
57,073,765
|
I'm writing API results to CSV file in python 3.7. Problem is it adds double quotes ("") to each row when it writes to file.
I'm passing format as csv to API call, so that I get results in csv format and then I'm writing it to csv file, store to specific location.
Please suggest if there is any better way to do this.
Here is the sample code..
```
with open(target_file_path, 'w', encoding='utf8') as csvFile:
writer = csv.writer(csvFile, quoting=csv.QUOTE_NONE, escapechar='\"')
for line in rec.split('\r\n'):
writer.writerow([line])
```
when I use `escapechar='\"'` it adds (`"`) at the of every column value.
here is sample records..
```
2264855868",42.38454",-71.01367",07/15/2019 00:00:00",07/14/2019 20:00:00"
2264855868",42.38454",-71.01367",07/15/2019 01:00:00",07/14/2019 21:00:00"
```
|
2019/07/17
|
[
"https://Stackoverflow.com/questions/57073765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8449329/"
] |
This is maybe the same as your original code, but use `prop()` instead of `attr()`.
>
> [`attr()`](https://api.jquery.com/attr/) - As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
>
>
>
```js
$('#settingsForm input').on('change', function() {
var len = $('#settingsForm input:checked').length;
if (len === 0) {
$(this).prop('checked', true);
console.log('You must select at least 1 checkbox');
}
});
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="settingsForm">
<input class="form-check-input" type="checkbox" name="emailFrequency_daily">
<label>Daily</label>
<input class="form-check-input" type="checkbox" name="emailFrequency_weekly">
<label>Weekly</label>
<input class="form-check-input" type="checkbox" name="emailFrequency_monthly">
<label>Monthly</label>
</form>
```
|
You can try to bind the change event on the `.form-check-input` class, and inside that event you can check wheter if the checkboxes are "empty" or not.
```js
$('.form-check-input').on("change", function(){
var noChecked = $('.form-check-input:checked').length;
if(noChecked === 0){
console.log("0 checkboxes are checked");
} else {
console.log("checkboxes ok", noChecked);
}
});
```
```html
<form id="settingsForm">
<input class="form-check-input" type="checkbox" name="emailFrequency_daily">
<label>Daily</label>
<input class="form-check-input" type="checkbox" name="emailFrequency_weekly">
<label>Weekly</label>
<input class="form-check-input" type="checkbox" name="emailFrequency_monthly">
<label>Monthly</label>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
```
|
19,736,625
|
I'm trying to write my first python script. I want to write a program that will get information out of a website.
I managed to open the website, read all the data and transform the data from bytes to a string.
```
import urllib.request
response = urllib.request.urlopen('http://www.imdb.com/title/tt0413573/episodes?season=10')
website = response.read()
response.close()
html = website.decode("utf-8")
print(type(html))
print(html)
```
The string is massive, I don't know if I show transform it to a list and iterate over the list or just keep it as a string.
What I would like to do if find all the keyword `airdate` and them get the next line in the string.
When I scroll through the string this is the relevant bits:
```
<meta itemprop="episodeNumber" content="10"/>
<div class="airdate">
Nov. 21, 2013
</div>
```
This happens lots of times inside the string. What I'm trying to do is to loop through the string and return this result:
```
"episodeNumber" = some number
"airdate" = what ever date
```
For overtime this happens in the string. I tried:
```
keywords = ["airdate","episodeNumber"]
for i in keywords:
if i in html:
print (something)
```
I hope I'm explaining myself in the right way. I will edit the question if needed.
|
2013/11/01
|
[
"https://Stackoverflow.com/questions/19736625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2904861/"
] |
When dealing with structured texts like HTML/XML it is a good idea to use existing tools that leverage this structure. Instead of using regex or searching by hand, this gives a much more reliable and readable solution. In this case, I suggest to install [lxml](http://lxml.de/) to parse the HTML.
Applying this principle to your problem, try the following (I assume that you use Python 3 because you imported urllib.request):
```
import lxml.html as html
import urllib.request
resp = urllib.request.urlopen('http://www.imdb.com/title/tt0413573/episodes?season=10')
fragment = html.fromstring(resp.read())
for info in fragment.find_class('info'):
print('"episodeNumber" = ', info.find('meta').attrib['content'])
print('"airdate" =', info.find_class('airdate')[0].text_content().strip())
```
To make sure that the episode number and airdate are corresponding, I search for the surrounding element (a div with class 'info') and then extract the data you want.
I'm sure the code can be made prettier with a fancier selection of elements, but this should get you started.
---
[Added more information on the solution concerning the structure in the HTML.]
The string containing the data of one episode looks as follows:
```
<div class="info" itemprop="episodes" itemscope itemtype="...">
<meta itemprop="episodeNumber" content="1"/>
<div class="airdate">Sep. 26, 2013</div> <!-- already stripped whitespace -->
<strong>
<a href="/title/tt2911802/" title="Seal Our Fate" itemprop="name">...</a>
</strong>
<div class="item_description" itemprop="description">...</div>
<div class="popoverContainer"></div>
<div class="popoverContainer"></div>
</div>
```
You first select the div containing all data of one episode by its class 'info'. The first information you want is in a child of the div.info element, the meta element, stored in its property 'content'.
Next, you want the information stored in the div.airdate element, this time it is stored inside the element as text. To get rid of the whitespace around it, I then used the strip() method.
|
Would that work?
```
lines = website.splitlines()
lines.append('')
for index, line in enumerate(lines):
for keyword in ["airdate","episodeNumber"]:
if keyword in line:
print(lines[index + 1])
```
It prints the next line if the keyword is found in the line.
|
19,736,625
|
I'm trying to write my first python script. I want to write a program that will get information out of a website.
I managed to open the website, read all the data and transform the data from bytes to a string.
```
import urllib.request
response = urllib.request.urlopen('http://www.imdb.com/title/tt0413573/episodes?season=10')
website = response.read()
response.close()
html = website.decode("utf-8")
print(type(html))
print(html)
```
The string is massive, I don't know if I show transform it to a list and iterate over the list or just keep it as a string.
What I would like to do if find all the keyword `airdate` and them get the next line in the string.
When I scroll through the string this is the relevant bits:
```
<meta itemprop="episodeNumber" content="10"/>
<div class="airdate">
Nov. 21, 2013
</div>
```
This happens lots of times inside the string. What I'm trying to do is to loop through the string and return this result:
```
"episodeNumber" = some number
"airdate" = what ever date
```
For overtime this happens in the string. I tried:
```
keywords = ["airdate","episodeNumber"]
for i in keywords:
if i in html:
print (something)
```
I hope I'm explaining myself in the right way. I will edit the question if needed.
|
2013/11/01
|
[
"https://Stackoverflow.com/questions/19736625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2904861/"
] |
If that is your first Python script, it is really impressive to see you have made so far.
You will use some legit parser to help you with your parsing.
Check out [BeautifulSoup4](http://www.crummy.com/software/BeautifulSoup/)
```
# intellectual property belongs to imdb
import urllib2
from bs4 import BeautifulSoup
# get the SOUP: tree structure out of the HTML page
soup = BeautifulSoup(urllib2.urlopen("http://www.imdb.com/title/tt0413573/episodes?season=10"))
result = {}
for div in soup.find_all("div", {"class":"airdate"}):
# get the date and number and store in a dictionary
date = div.text.encode('utf-8').strip()
number = div.find_previous_sibling()['content']
result[number] = date
print result
```
output
```
{'10': 'Nov. 21, 2013', '1': 'Sep. 26, 2013', '3': 'Oct. 3, 2013', '2': 'Sep. 26, 2013', '5': 'Oct. 17, 2013', '4': 'Oct. 10, 2013', '7': 'Oct. 31, 2013', '6': 'Oct. 24, 2013', '9': 'Nov. 14, 2013', '8': 'Nov. 7, 2013'}
```
Let me know if I understood and answered your question correctly.
|
Would that work?
```
lines = website.splitlines()
lines.append('')
for index, line in enumerate(lines):
for keyword in ["airdate","episodeNumber"]:
if keyword in line:
print(lines[index + 1])
```
It prints the next line if the keyword is found in the line.
|
61,370,108
|
I have a data input pipeline that has:
* input datapoints of types that are not castable to a `tf.Tensor` (dicts and whatnot)
* preprocessing functions that could not understand tensorflow types and need to work with those datapoints; some of which do data augmentation on the fly
I've been trying to fit this into a `tf.data` pipeline, and I'm stuck on running the preprocessing for multiple datapoints in parallel. So far I've tried this:
* use `Dataset.from_generator(gen)` and do the preprocessing in the generator; this works but it processes each datapoint sequentially, no matter what arrangement of `prefetch` and fake `map` calls I patch on it. Is it impossible to prefetch in parallel?
* encapsulate the preprocessing in a `tf.py_function` so I could `map` it in parallel over my Dataset, but
1. this requires some pretty ugly (de)serialization to fit exotic
types into string tensors,
2. apparently the execution of the `py_function` would be handed over to the (single-process) python interpreter, so I'd be stuck with the python GIL which would not help me much
* I saw that you could do some tricks with `interleave` but haven't found any which does not have issues from the first two ideas.
Am I missing anything here? Am I forced to either modify my preprocessing so that it can run in a graph or is there a way to multiprocess it?
Our previous way of doing this was using keras.Sequence which worked well but there's just too many people pushing the upgrade to the `tf.data` API. *(hell, even trying the keras.Sequence with tf 2.2 yields `WARNING:tensorflow:multiprocessing can interact badly with TensorFlow, causing nondeterministic deadlocks. For high performance data pipelines tf.data is recommended.`)*
*Note: I'm using tf 2.2rc3*
|
2020/04/22
|
[
"https://Stackoverflow.com/questions/61370108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5235369/"
] |
Please read the documentation first before post any questions. Visit <https://react-bootstrap.github.io/components/toasts/>
change
>
> import { Toast } from 'react-bootstrap';
>
>
>
with
>
> import Toast from 'react-bootstrap/Toast'
>
>
>
|
Change your import to
import { Toast } from 'react-bootstrap/Toast'
|
25,056,700
|
I am trying to connect to cassandra from python , I have installed `cassandra` as `pip install pycassa`.When i am trying to connect to the `cassandra` i am getting the following exception
```
from pycassa.pool import ConnectionPool
pool = ConnectionPool('Keyspace1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 382, in __init__
self.fill()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 442, in fill
conn = self._create_connection()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 431, in _create_connection
(exc.__class__.__name__, exc))
pycassa.pool.AllServersUnavailable: An attempt was made to connect to each of the servers twice, but none of the attempts succeeded. The last failure was TTransportException: Could not connect to localhost:9160
```
I am using python 2.7.
What is the problem, Any help would be appreciated.
|
2014/07/31
|
[
"https://Stackoverflow.com/questions/25056700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
Perhaps the best known is the *branchless absolute value*:
```
int m = x >> 31;
int abs = x + m ^ m;
```
Which uses an arithmetic shift to copy the signbit to all bits. Most uses of arithmetic shift that I've encountered were of that form. Of course an arithmetic shift is not *required* for this, you could replace all occurrences of `x >> 31` (where `x` is an `int`) by `-(x >>> 31)`.
The value 31 comes from the size of `int` in bits, which is 32 by definition in Java. So shifting right by 31 shifts out all bits except the signbit, which (since it's an arithmetic shift) is copied to those 31 bits, leaving a copy of the signbit in every position.
|
In C when writing device drivers, bit shift operators are used extensively since bits are used as switches that need to be turned on and off. Bit shift allow one to easily and correctly target the right switch.
Many hashing and cryptographic functions make use of bit shift. Take a look at [Mercenne Twister](https://en.wikipedia.org/wiki/Mersenne_twister#Pseudocode).
Lastly, it is sometimes useful to use bitfields to contain state information. Bit manipulation functions including bit shift are useful for these things.
|
25,056,700
|
I am trying to connect to cassandra from python , I have installed `cassandra` as `pip install pycassa`.When i am trying to connect to the `cassandra` i am getting the following exception
```
from pycassa.pool import ConnectionPool
pool = ConnectionPool('Keyspace1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 382, in __init__
self.fill()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 442, in fill
conn = self._create_connection()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 431, in _create_connection
(exc.__class__.__name__, exc))
pycassa.pool.AllServersUnavailable: An attempt was made to connect to each of the servers twice, but none of the attempts succeeded. The last failure was TTransportException: Could not connect to localhost:9160
```
I am using python 2.7.
What is the problem, Any help would be appreciated.
|
2014/07/31
|
[
"https://Stackoverflow.com/questions/25056700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
Indeed logical right shift is much more commonly used. However there are many operations that require an arithmetic shift (or are solved much more elegantly with an arithmetic shift)
* Sign extension:
+ Most of the time you only deal with the available types in C and the compiler will automatically sign extend when casting/promoting a narrower type to a wider one (like short to int) so you may not notice it, but under the hood a [left-then-right shift is used](https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tEJIBspLegAyeWpgByxgEaZiXTqQAOqBYXVaPUMTM0tffzU6OwdnIzcPTi8lFSjaBgJmYgJg41MLRWVMVUCMrIIYp1d3T0VM7NzQgoV6ivsq%2BJqkgEpFVANiZA4AcnsCAGp/YFoAfUwADwJrCDHx%2Be7xAAYAQXEAdlkd8ePx4kwCAdpxiAUEEgJu%2BfEAZkPdvYARLd2d1jpgcZ/USTPDTOaLaySFb0NYbHb7N4nU7nS7XKYOdDjZAILKPF5vfZfeG/f6A0no8FLbQzZjodA3O7ZNakEHTTCY7FZcYATzh70RJzOF2IV3m4zkPPx30J32GvVYIGGAFZhqRTMNNqrUIqdHIJQp%2BoNMOLJM9OKqCIrNd1egBrMybAB0Ss2AE5uHs3c9uJtnptNkrJEJFdxVUYuP61VatYrVQoQJtSJaNXLSHBYDBEChUEZvHh2GQKBA0Ln8zViAA3czcZDCUSkKj5pbEeMQFzR0guexZbmK82kEtGLQEADytFYvZTpCwRhEwHYHfwZxKFcw8anC2KBiWfdVY2UHdYeBcxB7eiwu6TxDw4eG5t6NHoTDYHB4/BAzyEc5QepkQmP8aQL0qDeGk64ALQjpIcZFCUGgQNYjSmF41iVHECSCBEAR0EhmF%2BNhtBodUiSFKkpStLhySwWkZTZERnQkS05SUXU5T0RhnC9AaAxDFw8qKiqUZTtqwwAEoAJIMDo4EAGqnFW3DAMgWJ1gCEAEMQBi0La3TXLghAkCaZosnopYFkZzy6bqMhyBa0a9BASAlnmBbkJQzllh4Rh4N4ChKtWDZNu4rbtlOXa0D2l6DsOY4ToumCzqIC5TkuxRqKu66alY8xbjud57vQB5TkeJ5nhgIz9hpN67g%2BdCMCwC5vgIXiqT%2BNl/iVgEQMBoGBBBUEwWR8GIfoeQOlY2jsTUQZYWkuGSIms2BFNHhBikaXkcxo1NIm61wekrQrWYrENNt%2BS7Yd7TodNXGGrxnHBsqqrqllIkALLiQACgw1bjEpylKo63B6fgRDEEZXjjKZLnuBDVm/tIdkpjapAIJgtI1N1pD2uYeyOnsAAceyus8BOcOYuN7Eq1OPaGpDhi6QmvbGiiCMm1pppmjnZmZ7hucWOYwx4WRGK6kheI2rDNiFHbhZF%2BUDjmQ70LFk5ZTOc7JereDLula4dpuyDbhVBVLAqxXHqexDcueJtXtV%2BW1U%2BDWvrwAi8K1EjtfInXwD1YGKpB0GkRtw3aCxqFXcReGRIELFLdEUcMYIe00RRZ0p9Rm10UnHEnTkGfJJdsTRw93FGnxj2CS9MbDNsolvX9yDKa6jqSI6nDXLQdCYLpED6WDEMmYLnlGdw8Pe0jHPcx5rlFrPNTeN4yDVuwwCuoFUvBZQoVZXL1tRUrMXjmrqoa0lIza7reAZQbOVG3l/b7ubWUlVbNvlZeVW3veDZ1c%2BjU3bHU9gjf8Lgur%2Bz6oHAaId9qaHDoXCathc5dB8PhOaiCE6ERQYxLOdBaIFxCMhWBac2I4JTunIhFCyEl2TmXO6r5%2BJPSZrXXwAB3dwq9jTbAACqcGeI6TYIMDLgykMZKGI9zJiMkBPWQMgp5yl6GjDGHgsbmzpgzRMNdSAiTjGzeydoQDEyBq6AMkhTHmCVK6cwrpXR7Ees8Z6HZdFJgMY9YO2iXHs0UaQVcLZAggG4EAA%3D%3D%3D) if the architecture doesn't have an instruction for sign extension. For "odd" number of bits you'll have to do the sign extension manually so this would be much more common. For example if a 10-bit pixel or ADC value is read into the top bits of a 16-bit register: `value >> 6` will move the bits to the lower 10 bit positions and sign extend to preserve the value. If they're read into the low 10 bits with the top 6 bits being zero you'll use `value << 6 >> 6` to sign extend the value to work with it
+ You also need signed extension when working with signed bit fields
```
struct bitfield {
int x: 15;
int y: 12;
int z: 5;
};
int f(bitfield b) {
return (b.x/8 + b.y/5) * b.z;
}
```
[Demo on Godbolt](https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tQVvQAZPLUwA5YwCNMxLp1IAHVAsLraewyaCnt5qdFY29kZOLpxuSiqhtAwEzMQE/samccqYqr7JqQThdo7OroopaRmBcZVF1iVRZbEAlIqoBsTIHADkCgTEBqoA1A6EVHjK6MPiAOyyAAwAgsOrw9YEwwAeIMOcAKziAMyLK2sbwwCeu5ySx6dr6/TDAF67hyfiy3MAIvdfSwBFyoEDGBAmU1GLRm8wBjwueBmRx%2BowAdFsAPQADn%2By3hzz4SJRDlRlwxHwea2ImAInVowwgiLkwz40IAVGiXrjAbM/ssem1WCAevseqRTD0FmLUMKdHJmQoOl1MDNJEdOGKCMKpS02gBrECSbiogBsRu4kix3FmWNiWPtQmF3DFRi4CwW4u10uFYoUIA9WslAtIcFgSDQRnceHYZAoEAjUZjIDwyGQkgWkliAE5SBNWARnH7QV7SGNaKlrj0NaQI0YtAQAPK0ViVqWkLBGETAdgl/DUvIAN0wfqDpEwW1yBgLwurG2UJdYeAcxAreiwM81xDwrqrwZo9CYbA4PH4ICOQi7KHlMiES79kDaqHciRHAFoG5JfTk8hoIOZqlkY7aMUkTREEXg%2BHQAHgSEvggaUMSKN%2BiQFFU%2BiZII8S5ChdTwU0iH9IU0G1IUeFgZwbSKp03RcIKwqip6o4yj0WxYiar4mtw6ypsMmaopwqJZgyuCECQqrqqQwx6JG0bOOJRzQnKMhyJqXptBA4aoDJMbkJQCayS4yDCKIsTurm0YFsQRYOCWZYVhuNZaXW9BNi2vaYJ2og9qOfbYXgQ4jm246TtOu7kPQ86jouy6rhgvTVgM24bm0%2B6MCwPYngIbjGWI17yNF94QI%2Bz6%2BG%2BH5fgkviaNo0FqkBlgNKBzQesEkF%2BOhgR1a1iRkc1SGVXQqHpB1ph1VhP5JLhjUIW6FRESNhrnoRaS9TECyUUqNEUY6IpihKbbMax7GccMRldnsAkLKiCzCfgRDEOJbhSVpiZyVI6qKXlqlBrqpAIJgzBYC4RWkAasz7KiRzg/sswHJm9qxLwQo9M6pCupwZn7d6PS%2BoIgY6nRPSfoxB0%2BqQ%2BMCm0Q5WVV3BAA%3D). The shifts are generated by the compiler but usually you don't use bitfields (as they're not portable) and operate on raw integer values instead so you'll need to do arithmetic shifts yourself to extract the fields
+ Another example: sign-extend a pointer to make a [canonical address in x86-64](https://en.wikipedia.org/wiki/X86-64#Canonical_form_addresses). This is used to [store additional data in the pointer](https://stackoverflow.com/q/16198700/995714): `char* pointer = (char*)((intptr_t)address << 16 >> 16)`. You can think of this as a 48-bit bitfield at the bottom
+ V8 engine's [SMI optimization](https://stackoverflow.com/q/57348783/995714) stores the value in the top 31 bits so it needs a right shift to restore the signed integer
* [Round signed division properly](https://stackoverflow.com/q/15916876/995714) when [converting to a multiplication](https://stackoverflow.com/q/41183935/995714), for example `x/12` will be optimized to `x*43691 >> 19` with some additional rounding. Of course you'll never do this in normal scalar code because the compiler already does this for you but sometimes you may need to vectorize the code or [make some related libraries](https://github.com/ridiculousfish/libdivide) then you'll need to calculate the rounding yourself with arithmetic shift. You can see how compilers round the division results in the output assembly for bitfield above
* Saturated shift or shifts larger than bit width, i.e. the value becomes zero when the shift count >= bit width
```
uint32_t lsh_saturated(uint32_t x, int32_t n) // returns 0 if n == 32
{
return (x << (n & 0x1F)) & ((n-32) >> 5);
}
uint32_t lsh(uint32_t x, int32_t n) // returns 0 if n >= 32
{
return (x << (n & 0x1F)) & ((n-32) >> 31);
}
```
* Bit mask, useful in various cases like branchless selection (i.e. [muxer](https://en.wikipedia.org/wiki/Multiplexer)). You can see lots of ways to conditionally do something on the famous [bithacks page](https://graphics.stanford.edu/%7Eseander/bithacks.html). Most of them are done by generating a mask of all ones or all zeros. The mask is usually calculated by propagating the sign bit of a subtraction like this `(x - y) >> 31` (for 32-bit ints). Of course it can be changed to `-(unsigned(x - y) >> 31)` but that requires 2's complement and needs more operations. Here's the way to get the min and max of two integers without branching:
```
min = y + ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));
max = x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));
```
Another example is `m = m & -((signed)(m - d) >> s);` in [Compute modulus division by (1 << s) - 1 in parallel without a division operator](https://graphics.stanford.edu/%7Eseander/bithacks.html#ModulusDivisionParallel)
|
In C when writing device drivers, bit shift operators are used extensively since bits are used as switches that need to be turned on and off. Bit shift allow one to easily and correctly target the right switch.
Many hashing and cryptographic functions make use of bit shift. Take a look at [Mercenne Twister](https://en.wikipedia.org/wiki/Mersenne_twister#Pseudocode).
Lastly, it is sometimes useful to use bitfields to contain state information. Bit manipulation functions including bit shift are useful for these things.
|
25,056,700
|
I am trying to connect to cassandra from python , I have installed `cassandra` as `pip install pycassa`.When i am trying to connect to the `cassandra` i am getting the following exception
```
from pycassa.pool import ConnectionPool
pool = ConnectionPool('Keyspace1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 382, in __init__
self.fill()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 442, in fill
conn = self._create_connection()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 431, in _create_connection
(exc.__class__.__name__, exc))
pycassa.pool.AllServersUnavailable: An attempt was made to connect to each of the servers twice, but none of the attempts succeeded. The last failure was TTransportException: Could not connect to localhost:9160
```
I am using python 2.7.
What is the problem, Any help would be appreciated.
|
2014/07/31
|
[
"https://Stackoverflow.com/questions/25056700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
It has come in handy for me before, in the creation of masks that were then used in '&' or '|' operators when manipulating bit fields, either for bitwise data packing or bitwise graphics.
I don't have a handy code sample, but I do recall using that technique many years ago in black-and-white graphics to zoom in (by extending a bit, either 1 or 0). For a 3x zoom, '0' would become '000' and '1' would become '111' without having to know the initial value of the bit. The bit to be expanded would be placed in the high order position, then an arithmetic right shift would extend it, regardless of whether it was 0 or 1. A logical shift, either left or right, always brings in zeros to fill vacated bit positions. In this case the sign bit was the key to the solution.
|
In C when writing device drivers, bit shift operators are used extensively since bits are used as switches that need to be turned on and off. Bit shift allow one to easily and correctly target the right switch.
Many hashing and cryptographic functions make use of bit shift. Take a look at [Mercenne Twister](https://en.wikipedia.org/wiki/Mersenne_twister#Pseudocode).
Lastly, it is sometimes useful to use bitfields to contain state information. Bit manipulation functions including bit shift are useful for these things.
|
25,056,700
|
I am trying to connect to cassandra from python , I have installed `cassandra` as `pip install pycassa`.When i am trying to connect to the `cassandra` i am getting the following exception
```
from pycassa.pool import ConnectionPool
pool = ConnectionPool('Keyspace1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 382, in __init__
self.fill()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 442, in fill
conn = self._create_connection()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 431, in _create_connection
(exc.__class__.__name__, exc))
pycassa.pool.AllServersUnavailable: An attempt was made to connect to each of the servers twice, but none of the attempts succeeded. The last failure was TTransportException: Could not connect to localhost:9160
```
I am using python 2.7.
What is the problem, Any help would be appreciated.
|
2014/07/31
|
[
"https://Stackoverflow.com/questions/25056700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
It has come in handy for me before, in the creation of masks that were then used in '&' or '|' operators when manipulating bit fields, either for bitwise data packing or bitwise graphics.
I don't have a handy code sample, but I do recall using that technique many years ago in black-and-white graphics to zoom in (by extending a bit, either 1 or 0). For a 3x zoom, '0' would become '000' and '1' would become '111' without having to know the initial value of the bit. The bit to be expanded would be placed in the high order position, then an arithmetic right shift would extend it, regardless of whether it was 0 or 1. A logical shift, either left or right, always brings in zeros to fill vacated bit positions. In this case the sign bit was the key to the solution.
|
I am not too sure what you mean. BUt i'm going to speculate that you want to use the bit shift as an arithmetic function.
One interesting thing i have seen is this property of binary numbers.
```
int n = 4;
int k = 1;
n = n << k; // is the same as n = n * 2^k
//now n = (4 * 2) i.e. 8
n = n >> k; // is the same as n = n / 2^k
//now n = (8 / 2) i.e. 4
```
hope that helps.
But yes you want to be careful of negative numbers
i would mask and then turn it back accordingly
|
25,056,700
|
I am trying to connect to cassandra from python , I have installed `cassandra` as `pip install pycassa`.When i am trying to connect to the `cassandra` i am getting the following exception
```
from pycassa.pool import ConnectionPool
pool = ConnectionPool('Keyspace1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 382, in __init__
self.fill()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 442, in fill
conn = self._create_connection()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 431, in _create_connection
(exc.__class__.__name__, exc))
pycassa.pool.AllServersUnavailable: An attempt was made to connect to each of the servers twice, but none of the attempts succeeded. The last failure was TTransportException: Could not connect to localhost:9160
```
I am using python 2.7.
What is the problem, Any help would be appreciated.
|
2014/07/31
|
[
"https://Stackoverflow.com/questions/25056700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
Perhaps the best known is the *branchless absolute value*:
```
int m = x >> 31;
int abs = x + m ^ m;
```
Which uses an arithmetic shift to copy the signbit to all bits. Most uses of arithmetic shift that I've encountered were of that form. Of course an arithmetic shift is not *required* for this, you could replace all occurrences of `x >> 31` (where `x` is an `int`) by `-(x >>> 31)`.
The value 31 comes from the size of `int` in bits, which is 32 by definition in Java. So shifting right by 31 shifts out all bits except the signbit, which (since it's an arithmetic shift) is copied to those 31 bits, leaving a copy of the signbit in every position.
|
Indeed logical right shift is much more commonly used. However there are many operations that require an arithmetic shift (or are solved much more elegantly with an arithmetic shift)
* Sign extension:
+ Most of the time you only deal with the available types in C and the compiler will automatically sign extend when casting/promoting a narrower type to a wider one (like short to int) so you may not notice it, but under the hood a [left-then-right shift is used](https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tEJIBspLegAyeWpgByxgEaZiXTqQAOqBYXVaPUMTM0tffzU6OwdnIzcPTi8lFSjaBgJmYgJg41MLRWVMVUCMrIIYp1d3T0VM7NzQgoV6ivsq%2BJqkgEpFVANiZA4AcnsCAGp/YFoAfUwADwJrCDHx%2Be7xAAYAQXEAdlkd8ePx4kwCAdpxiAUEEgJu%2BfEAZkPdvYARLd2d1jpgcZ/USTPDTOaLaySFb0NYbHb7N4nU7nS7XKYOdDjZAILKPF5vfZfeG/f6A0no8FLbQzZjodA3O7ZNakEHTTCY7FZcYATzh70RJzOF2IV3m4zkPPx30J32GvVYIGGAFZhqRTMNNqrUIqdHIJQp%2BoNMOLJM9OKqCIrNd1egBrMybAB0Ss2AE5uHs3c9uJtnptNkrJEJFdxVUYuP61VatYrVQoQJtSJaNXLSHBYDBEChUEZvHh2GQKBA0Ln8zViAA3czcZDCUSkKj5pbEeMQFzR0guexZbmK82kEtGLQEADytFYvZTpCwRhEwHYHfwZxKFcw8anC2KBiWfdVY2UHdYeBcxB7eiwu6TxDw4eG5t6NHoTDYHB4/BAzyEc5QepkQmP8aQL0qDeGk64ALQjpIcZFCUGgQNYjSmF41iVHECSCBEAR0EhmF%2BNhtBodUiSFKkpStLhySwWkZTZERnQkS05SUXU5T0RhnC9AaAxDFw8qKiqUZTtqwwAEoAJIMDo4EAGqnFW3DAMgWJ1gCEAEMQBi0La3TXLghAkCaZosnopYFkZzy6bqMhyBa0a9BASAlnmBbkJQzllh4Rh4N4ChKtWDZNu4rbtlOXa0D2l6DsOY4ToumCzqIC5TkuxRqKu66alY8xbjud57vQB5TkeJ5nhgIz9hpN67g%2BdCMCwC5vgIXiqT%2BNl/iVgEQMBoGBBBUEwWR8GIfoeQOlY2jsTUQZYWkuGSIms2BFNHhBikaXkcxo1NIm61wekrQrWYrENNt%2BS7Yd7TodNXGGrxnHBsqqrqllIkALLiQACgw1bjEpylKo63B6fgRDEEZXjjKZLnuBDVm/tIdkpjapAIJgtI1N1pD2uYeyOnsAAceyus8BOcOYuN7Eq1OPaGpDhi6QmvbGiiCMm1pppmjnZmZ7hucWOYwx4WRGK6kheI2rDNiFHbhZF%2BUDjmQ70LFk5ZTOc7JereDLula4dpuyDbhVBVLAqxXHqexDcueJtXtV%2BW1U%2BDWvrwAi8K1EjtfInXwD1YGKpB0GkRtw3aCxqFXcReGRIELFLdEUcMYIe00RRZ0p9Rm10UnHEnTkGfJJdsTRw93FGnxj2CS9MbDNsolvX9yDKa6jqSI6nDXLQdCYLpED6WDEMmYLnlGdw8Pe0jHPcx5rlFrPNTeN4yDVuwwCuoFUvBZQoVZXL1tRUrMXjmrqoa0lIza7reAZQbOVG3l/b7ubWUlVbNvlZeVW3veDZ1c%2BjU3bHU9gjf8Lgur%2Bz6oHAaId9qaHDoXCathc5dB8PhOaiCE6ERQYxLOdBaIFxCMhWBac2I4JTunIhFCyEl2TmXO6r5%2BJPSZrXXwAB3dwq9jTbAACqcGeI6TYIMDLgykMZKGI9zJiMkBPWQMgp5yl6GjDGHgsbmzpgzRMNdSAiTjGzeydoQDEyBq6AMkhTHmCVK6cwrpXR7Ees8Z6HZdFJgMY9YO2iXHs0UaQVcLZAggG4EAA%3D%3D%3D) if the architecture doesn't have an instruction for sign extension. For "odd" number of bits you'll have to do the sign extension manually so this would be much more common. For example if a 10-bit pixel or ADC value is read into the top bits of a 16-bit register: `value >> 6` will move the bits to the lower 10 bit positions and sign extend to preserve the value. If they're read into the low 10 bits with the top 6 bits being zero you'll use `value << 6 >> 6` to sign extend the value to work with it
+ You also need signed extension when working with signed bit fields
```
struct bitfield {
int x: 15;
int y: 12;
int z: 5;
};
int f(bitfield b) {
return (b.x/8 + b.y/5) * b.z;
}
```
[Demo on Godbolt](https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tQVvQAZPLUwA5YwCNMxLp1IAHVAsLraewyaCnt5qdFY29kZOLpxuSiqhtAwEzMQE/samccqYqr7JqQThdo7OroopaRmBcZVF1iVRZbEAlIqoBsTIHADkCgTEBqoA1A6EVHjK6MPiAOyyAAwAgsOrw9YEwwAeIMOcAKziAMyLK2sbwwCeu5ySx6dr6/TDAF67hyfiy3MAIvdfSwBFyoEDGBAmU1GLRm8wBjwueBmRx%2BowAdFsAPQADn%2By3hzz4SJRDlRlwxHwea2ImAInVowwgiLkwz40IAVGiXrjAbM/ssem1WCAevseqRTD0FmLUMKdHJmQoOl1MDNJEdOGKCMKpS02gBrECSbiogBsRu4kix3FmWNiWPtQmF3DFRi4CwW4u10uFYoUIA9WslAtIcFgSDQRnceHYZAoEAjUZjIDwyGQkgWkliAE5SBNWARnH7QV7SGNaKlrj0NaQI0YtAQAPK0ViVqWkLBGETAdgl/DUvIAN0wfqDpEwW1yBgLwurG2UJdYeAcxAreiwM81xDwrqrwZo9CYbA4PH4ICOQi7KHlMiES79kDaqHciRHAFoG5JfTk8hoIOZqlkY7aMUkTREEXg%2BHQAHgSEvggaUMSKN%2BiQFFU%2BiZII8S5ChdTwU0iH9IU0G1IUeFgZwbSKp03RcIKwqip6o4yj0WxYiar4mtw6ypsMmaopwqJZgyuCECQqrqqQwx6JG0bOOJRzQnKMhyJqXptBA4aoDJMbkJQCayS4yDCKIsTurm0YFsQRYOCWZYVhuNZaXW9BNi2vaYJ2og9qOfbYXgQ4jm246TtOu7kPQ86jouy6rhgvTVgM24bm0%2B6MCwPYngIbjGWI17yNF94QI%2Bz6%2BG%2BH5fgkviaNo0FqkBlgNKBzQesEkF%2BOhgR1a1iRkc1SGVXQqHpB1ph1VhP5JLhjUIW6FRESNhrnoRaS9TECyUUqNEUY6IpihKbbMax7GccMRldnsAkLKiCzCfgRDEOJbhSVpiZyVI6qKXlqlBrqpAIJgzBYC4RWkAasz7KiRzg/sswHJm9qxLwQo9M6pCupwZn7d6PS%2BoIgY6nRPSfoxB0%2BqQ%2BMCm0Q5WVV3BAA%3D). The shifts are generated by the compiler but usually you don't use bitfields (as they're not portable) and operate on raw integer values instead so you'll need to do arithmetic shifts yourself to extract the fields
+ Another example: sign-extend a pointer to make a [canonical address in x86-64](https://en.wikipedia.org/wiki/X86-64#Canonical_form_addresses). This is used to [store additional data in the pointer](https://stackoverflow.com/q/16198700/995714): `char* pointer = (char*)((intptr_t)address << 16 >> 16)`. You can think of this as a 48-bit bitfield at the bottom
+ V8 engine's [SMI optimization](https://stackoverflow.com/q/57348783/995714) stores the value in the top 31 bits so it needs a right shift to restore the signed integer
* [Round signed division properly](https://stackoverflow.com/q/15916876/995714) when [converting to a multiplication](https://stackoverflow.com/q/41183935/995714), for example `x/12` will be optimized to `x*43691 >> 19` with some additional rounding. Of course you'll never do this in normal scalar code because the compiler already does this for you but sometimes you may need to vectorize the code or [make some related libraries](https://github.com/ridiculousfish/libdivide) then you'll need to calculate the rounding yourself with arithmetic shift. You can see how compilers round the division results in the output assembly for bitfield above
* Saturated shift or shifts larger than bit width, i.e. the value becomes zero when the shift count >= bit width
```
uint32_t lsh_saturated(uint32_t x, int32_t n) // returns 0 if n == 32
{
return (x << (n & 0x1F)) & ((n-32) >> 5);
}
uint32_t lsh(uint32_t x, int32_t n) // returns 0 if n >= 32
{
return (x << (n & 0x1F)) & ((n-32) >> 31);
}
```
* Bit mask, useful in various cases like branchless selection (i.e. [muxer](https://en.wikipedia.org/wiki/Multiplexer)). You can see lots of ways to conditionally do something on the famous [bithacks page](https://graphics.stanford.edu/%7Eseander/bithacks.html). Most of them are done by generating a mask of all ones or all zeros. The mask is usually calculated by propagating the sign bit of a subtraction like this `(x - y) >> 31` (for 32-bit ints). Of course it can be changed to `-(unsigned(x - y) >> 31)` but that requires 2's complement and needs more operations. Here's the way to get the min and max of two integers without branching:
```
min = y + ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));
max = x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));
```
Another example is `m = m & -((signed)(m - d) >> s);` in [Compute modulus division by (1 << s) - 1 in parallel without a division operator](https://graphics.stanford.edu/%7Eseander/bithacks.html#ModulusDivisionParallel)
|
25,056,700
|
I am trying to connect to cassandra from python , I have installed `cassandra` as `pip install pycassa`.When i am trying to connect to the `cassandra` i am getting the following exception
```
from pycassa.pool import ConnectionPool
pool = ConnectionPool('Keyspace1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 382, in __init__
self.fill()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 442, in fill
conn = self._create_connection()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 431, in _create_connection
(exc.__class__.__name__, exc))
pycassa.pool.AllServersUnavailable: An attempt was made to connect to each of the servers twice, but none of the attempts succeeded. The last failure was TTransportException: Could not connect to localhost:9160
```
I am using python 2.7.
What is the problem, Any help would be appreciated.
|
2014/07/31
|
[
"https://Stackoverflow.com/questions/25056700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
Here's an example of a function that will find the least power of two greater than or equal to the input. There are other solutions to this problem that are probably faster, namly any hardware oriented solution or just a series of right shifts and ORs. This solution uses arithmetic shift to perform a binary search.
```
unsigned ClosestPowerOfTwo(unsigned num) {
int mask = 0xFFFF0000;
mask = (num & mask) ? (mask << 8) : (mask >> 8);
mask = (num & mask) ? (mask << 4) : (mask >> 4);
mask = (num & mask) ? (mask << 2) : (mask >> 2);
mask = (num & mask) ? (mask << 1) : (mask >> 1);
mask = (num & mask) ? mask : (mask >> 1);
return (num & mask) ? -mask : -(mask << 1);
}
```
|
Indeed logical right shift is much more commonly used. However there are many operations that require an arithmetic shift (or are solved much more elegantly with an arithmetic shift)
* Sign extension:
+ Most of the time you only deal with the available types in C and the compiler will automatically sign extend when casting/promoting a narrower type to a wider one (like short to int) so you may not notice it, but under the hood a [left-then-right shift is used](https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tEJIBspLegAyeWpgByxgEaZiXTqQAOqBYXVaPUMTM0tffzU6OwdnIzcPTi8lFSjaBgJmYgJg41MLRWVMVUCMrIIYp1d3T0VM7NzQgoV6ivsq%2BJqkgEpFVANiZA4AcnsCAGp/YFoAfUwADwJrCDHx%2Be7xAAYAQXEAdlkd8ePx4kwCAdpxiAUEEgJu%2BfEAZkPdvYARLd2d1jpgcZ/USTPDTOaLaySFb0NYbHb7N4nU7nS7XKYOdDjZAILKPF5vfZfeG/f6A0no8FLbQzZjodA3O7ZNakEHTTCY7FZcYATzh70RJzOF2IV3m4zkPPx30J32GvVYIGGAFZhqRTMNNqrUIqdHIJQp%2BoNMOLJM9OKqCIrNd1egBrMybAB0Ss2AE5uHs3c9uJtnptNkrJEJFdxVUYuP61VatYrVQoQJtSJaNXLSHBYDBEChUEZvHh2GQKBA0Ln8zViAA3czcZDCUSkKj5pbEeMQFzR0guexZbmK82kEtGLQEADytFYvZTpCwRhEwHYHfwZxKFcw8anC2KBiWfdVY2UHdYeBcxB7eiwu6TxDw4eG5t6NHoTDYHB4/BAzyEc5QepkQmP8aQL0qDeGk64ALQjpIcZFCUGgQNYjSmF41iVHECSCBEAR0EhmF%2BNhtBodUiSFKkpStLhySwWkZTZERnQkS05SUXU5T0RhnC9AaAxDFw8qKiqUZTtqwwAEoAJIMDo4EAGqnFW3DAMgWJ1gCEAEMQBi0La3TXLghAkCaZosnopYFkZzy6bqMhyBa0a9BASAlnmBbkJQzllh4Rh4N4ChKtWDZNu4rbtlOXa0D2l6DsOY4ToumCzqIC5TkuxRqKu66alY8xbjud57vQB5TkeJ5nhgIz9hpN67g%2BdCMCwC5vgIXiqT%2BNl/iVgEQMBoGBBBUEwWR8GIfoeQOlY2jsTUQZYWkuGSIms2BFNHhBikaXkcxo1NIm61wekrQrWYrENNt%2BS7Yd7TodNXGGrxnHBsqqrqllIkALLiQACgw1bjEpylKo63B6fgRDEEZXjjKZLnuBDVm/tIdkpjapAIJgtI1N1pD2uYeyOnsAAceyus8BOcOYuN7Eq1OPaGpDhi6QmvbGiiCMm1pppmjnZmZ7hucWOYwx4WRGK6kheI2rDNiFHbhZF%2BUDjmQ70LFk5ZTOc7JereDLula4dpuyDbhVBVLAqxXHqexDcueJtXtV%2BW1U%2BDWvrwAi8K1EjtfInXwD1YGKpB0GkRtw3aCxqFXcReGRIELFLdEUcMYIe00RRZ0p9Rm10UnHEnTkGfJJdsTRw93FGnxj2CS9MbDNsolvX9yDKa6jqSI6nDXLQdCYLpED6WDEMmYLnlGdw8Pe0jHPcx5rlFrPNTeN4yDVuwwCuoFUvBZQoVZXL1tRUrMXjmrqoa0lIza7reAZQbOVG3l/b7ubWUlVbNvlZeVW3veDZ1c%2BjU3bHU9gjf8Lgur%2Bz6oHAaId9qaHDoXCathc5dB8PhOaiCE6ERQYxLOdBaIFxCMhWBac2I4JTunIhFCyEl2TmXO6r5%2BJPSZrXXwAB3dwq9jTbAACqcGeI6TYIMDLgykMZKGI9zJiMkBPWQMgp5yl6GjDGHgsbmzpgzRMNdSAiTjGzeydoQDEyBq6AMkhTHmCVK6cwrpXR7Ees8Z6HZdFJgMY9YO2iXHs0UaQVcLZAggG4EAA%3D%3D%3D) if the architecture doesn't have an instruction for sign extension. For "odd" number of bits you'll have to do the sign extension manually so this would be much more common. For example if a 10-bit pixel or ADC value is read into the top bits of a 16-bit register: `value >> 6` will move the bits to the lower 10 bit positions and sign extend to preserve the value. If they're read into the low 10 bits with the top 6 bits being zero you'll use `value << 6 >> 6` to sign extend the value to work with it
+ You also need signed extension when working with signed bit fields
```
struct bitfield {
int x: 15;
int y: 12;
int z: 5;
};
int f(bitfield b) {
return (b.x/8 + b.y/5) * b.z;
}
```
[Demo on Godbolt](https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tQVvQAZPLUwA5YwCNMxLp1IAHVAsLraewyaCnt5qdFY29kZOLpxuSiqhtAwEzMQE/samccqYqr7JqQThdo7OroopaRmBcZVF1iVRZbEAlIqoBsTIHADkCgTEBqoA1A6EVHjK6MPiAOyyAAwAgsOrw9YEwwAeIMOcAKziAMyLK2sbwwCeu5ySx6dr6/TDAF67hyfiy3MAIvdfSwBFyoEDGBAmU1GLRm8wBjwueBmRx%2BowAdFsAPQADn%2By3hzz4SJRDlRlwxHwea2ImAInVowwgiLkwz40IAVGiXrjAbM/ssem1WCAevseqRTD0FmLUMKdHJmQoOl1MDNJEdOGKCMKpS02gBrECSbiogBsRu4kix3FmWNiWPtQmF3DFRi4CwW4u10uFYoUIA9WslAtIcFgSDQRnceHYZAoEAjUZjIDwyGQkgWkliAE5SBNWARnH7QV7SGNaKlrj0NaQI0YtAQAPK0ViVqWkLBGETAdgl/DUvIAN0wfqDpEwW1yBgLwurG2UJdYeAcxAreiwM81xDwrqrwZo9CYbA4PH4ICOQi7KHlMiES79kDaqHciRHAFoG5JfTk8hoIOZqlkY7aMUkTREEXg%2BHQAHgSEvggaUMSKN%2BiQFFU%2BiZII8S5ChdTwU0iH9IU0G1IUeFgZwbSKp03RcIKwqip6o4yj0WxYiar4mtw6ypsMmaopwqJZgyuCECQqrqqQwx6JG0bOOJRzQnKMhyJqXptBA4aoDJMbkJQCayS4yDCKIsTurm0YFsQRYOCWZYVhuNZaXW9BNi2vaYJ2og9qOfbYXgQ4jm246TtOu7kPQ86jouy6rhgvTVgM24bm0%2B6MCwPYngIbjGWI17yNF94QI%2Bz6%2BG%2BH5fgkviaNo0FqkBlgNKBzQesEkF%2BOhgR1a1iRkc1SGVXQqHpB1ph1VhP5JLhjUIW6FRESNhrnoRaS9TECyUUqNEUY6IpihKbbMax7GccMRldnsAkLKiCzCfgRDEOJbhSVpiZyVI6qKXlqlBrqpAIJgzBYC4RWkAasz7KiRzg/sswHJm9qxLwQo9M6pCupwZn7d6PS%2BoIgY6nRPSfoxB0%2BqQ%2BMCm0Q5WVV3BAA%3D). The shifts are generated by the compiler but usually you don't use bitfields (as they're not portable) and operate on raw integer values instead so you'll need to do arithmetic shifts yourself to extract the fields
+ Another example: sign-extend a pointer to make a [canonical address in x86-64](https://en.wikipedia.org/wiki/X86-64#Canonical_form_addresses). This is used to [store additional data in the pointer](https://stackoverflow.com/q/16198700/995714): `char* pointer = (char*)((intptr_t)address << 16 >> 16)`. You can think of this as a 48-bit bitfield at the bottom
+ V8 engine's [SMI optimization](https://stackoverflow.com/q/57348783/995714) stores the value in the top 31 bits so it needs a right shift to restore the signed integer
* [Round signed division properly](https://stackoverflow.com/q/15916876/995714) when [converting to a multiplication](https://stackoverflow.com/q/41183935/995714), for example `x/12` will be optimized to `x*43691 >> 19` with some additional rounding. Of course you'll never do this in normal scalar code because the compiler already does this for you but sometimes you may need to vectorize the code or [make some related libraries](https://github.com/ridiculousfish/libdivide) then you'll need to calculate the rounding yourself with arithmetic shift. You can see how compilers round the division results in the output assembly for bitfield above
* Saturated shift or shifts larger than bit width, i.e. the value becomes zero when the shift count >= bit width
```
uint32_t lsh_saturated(uint32_t x, int32_t n) // returns 0 if n == 32
{
return (x << (n & 0x1F)) & ((n-32) >> 5);
}
uint32_t lsh(uint32_t x, int32_t n) // returns 0 if n >= 32
{
return (x << (n & 0x1F)) & ((n-32) >> 31);
}
```
* Bit mask, useful in various cases like branchless selection (i.e. [muxer](https://en.wikipedia.org/wiki/Multiplexer)). You can see lots of ways to conditionally do something on the famous [bithacks page](https://graphics.stanford.edu/%7Eseander/bithacks.html). Most of them are done by generating a mask of all ones or all zeros. The mask is usually calculated by propagating the sign bit of a subtraction like this `(x - y) >> 31` (for 32-bit ints). Of course it can be changed to `-(unsigned(x - y) >> 31)` but that requires 2's complement and needs more operations. Here's the way to get the min and max of two integers without branching:
```
min = y + ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));
max = x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));
```
Another example is `m = m & -((signed)(m - d) >> s);` in [Compute modulus division by (1 << s) - 1 in parallel without a division operator](https://graphics.stanford.edu/%7Eseander/bithacks.html#ModulusDivisionParallel)
|
25,056,700
|
I am trying to connect to cassandra from python , I have installed `cassandra` as `pip install pycassa`.When i am trying to connect to the `cassandra` i am getting the following exception
```
from pycassa.pool import ConnectionPool
pool = ConnectionPool('Keyspace1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 382, in __init__
self.fill()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 442, in fill
conn = self._create_connection()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 431, in _create_connection
(exc.__class__.__name__, exc))
pycassa.pool.AllServersUnavailable: An attempt was made to connect to each of the servers twice, but none of the attempts succeeded. The last failure was TTransportException: Could not connect to localhost:9160
```
I am using python 2.7.
What is the problem, Any help would be appreciated.
|
2014/07/31
|
[
"https://Stackoverflow.com/questions/25056700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
Indeed logical right shift is much more commonly used. However there are many operations that require an arithmetic shift (or are solved much more elegantly with an arithmetic shift)
* Sign extension:
+ Most of the time you only deal with the available types in C and the compiler will automatically sign extend when casting/promoting a narrower type to a wider one (like short to int) so you may not notice it, but under the hood a [left-then-right shift is used](https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tEJIBspLegAyeWpgByxgEaZiXTqQAOqBYXVaPUMTM0tffzU6OwdnIzcPTi8lFSjaBgJmYgJg41MLRWVMVUCMrIIYp1d3T0VM7NzQgoV6ivsq%2BJqkgEpFVANiZA4AcnsCAGp/YFoAfUwADwJrCDHx%2Be7xAAYAQXEAdlkd8ePx4kwCAdpxiAUEEgJu%2BfEAZkPdvYARLd2d1jpgcZ/USTPDTOaLaySFb0NYbHb7N4nU7nS7XKYOdDjZAILKPF5vfZfeG/f6A0no8FLbQzZjodA3O7ZNakEHTTCY7FZcYATzh70RJzOF2IV3m4zkPPx30J32GvVYIGGAFZhqRTMNNqrUIqdHIJQp%2BoNMOLJM9OKqCIrNd1egBrMybAB0Ss2AE5uHs3c9uJtnptNkrJEJFdxVUYuP61VatYrVQoQJtSJaNXLSHBYDBEChUEZvHh2GQKBA0Ln8zViAA3czcZDCUSkKj5pbEeMQFzR0guexZbmK82kEtGLQEADytFYvZTpCwRhEwHYHfwZxKFcw8anC2KBiWfdVY2UHdYeBcxB7eiwu6TxDw4eG5t6NHoTDYHB4/BAzyEc5QepkQmP8aQL0qDeGk64ALQjpIcZFCUGgQNYjSmF41iVHECSCBEAR0EhmF%2BNhtBodUiSFKkpStLhySwWkZTZERnQkS05SUXU5T0RhnC9AaAxDFw8qKiqUZTtqwwAEoAJIMDo4EAGqnFW3DAMgWJ1gCEAEMQBi0La3TXLghAkCaZosnopYFkZzy6bqMhyBa0a9BASAlnmBbkJQzllh4Rh4N4ChKtWDZNu4rbtlOXa0D2l6DsOY4ToumCzqIC5TkuxRqKu66alY8xbjud57vQB5TkeJ5nhgIz9hpN67g%2BdCMCwC5vgIXiqT%2BNl/iVgEQMBoGBBBUEwWR8GIfoeQOlY2jsTUQZYWkuGSIms2BFNHhBikaXkcxo1NIm61wekrQrWYrENNt%2BS7Yd7TodNXGGrxnHBsqqrqllIkALLiQACgw1bjEpylKo63B6fgRDEEZXjjKZLnuBDVm/tIdkpjapAIJgtI1N1pD2uYeyOnsAAceyus8BOcOYuN7Eq1OPaGpDhi6QmvbGiiCMm1pppmjnZmZ7hucWOYwx4WRGK6kheI2rDNiFHbhZF%2BUDjmQ70LFk5ZTOc7JereDLula4dpuyDbhVBVLAqxXHqexDcueJtXtV%2BW1U%2BDWvrwAi8K1EjtfInXwD1YGKpB0GkRtw3aCxqFXcReGRIELFLdEUcMYIe00RRZ0p9Rm10UnHEnTkGfJJdsTRw93FGnxj2CS9MbDNsolvX9yDKa6jqSI6nDXLQdCYLpED6WDEMmYLnlGdw8Pe0jHPcx5rlFrPNTeN4yDVuwwCuoFUvBZQoVZXL1tRUrMXjmrqoa0lIza7reAZQbOVG3l/b7ubWUlVbNvlZeVW3veDZ1c%2BjU3bHU9gjf8Lgur%2Bz6oHAaId9qaHDoXCathc5dB8PhOaiCE6ERQYxLOdBaIFxCMhWBac2I4JTunIhFCyEl2TmXO6r5%2BJPSZrXXwAB3dwq9jTbAACqcGeI6TYIMDLgykMZKGI9zJiMkBPWQMgp5yl6GjDGHgsbmzpgzRMNdSAiTjGzeydoQDEyBq6AMkhTHmCVK6cwrpXR7Ees8Z6HZdFJgMY9YO2iXHs0UaQVcLZAggG4EAA%3D%3D%3D) if the architecture doesn't have an instruction for sign extension. For "odd" number of bits you'll have to do the sign extension manually so this would be much more common. For example if a 10-bit pixel or ADC value is read into the top bits of a 16-bit register: `value >> 6` will move the bits to the lower 10 bit positions and sign extend to preserve the value. If they're read into the low 10 bits with the top 6 bits being zero you'll use `value << 6 >> 6` to sign extend the value to work with it
+ You also need signed extension when working with signed bit fields
```
struct bitfield {
int x: 15;
int y: 12;
int z: 5;
};
int f(bitfield b) {
return (b.x/8 + b.y/5) * b.z;
}
```
[Demo on Godbolt](https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tQVvQAZPLUwA5YwCNMxLp1IAHVAsLraewyaCnt5qdFY29kZOLpxuSiqhtAwEzMQE/samccqYqr7JqQThdo7OroopaRmBcZVF1iVRZbEAlIqoBsTIHADkCgTEBqoA1A6EVHjK6MPiAOyyAAwAgsOrw9YEwwAeIMOcAKziAMyLK2sbwwCeu5ySx6dr6/TDAF67hyfiy3MAIvdfSwBFyoEDGBAmU1GLRm8wBjwueBmRx%2BowAdFsAPQADn%2By3hzz4SJRDlRlwxHwea2ImAInVowwgiLkwz40IAVGiXrjAbM/ssem1WCAevseqRTD0FmLUMKdHJmQoOl1MDNJEdOGKCMKpS02gBrECSbiogBsRu4kix3FmWNiWPtQmF3DFRi4CwW4u10uFYoUIA9WslAtIcFgSDQRnceHYZAoEAjUZjIDwyGQkgWkliAE5SBNWARnH7QV7SGNaKlrj0NaQI0YtAQAPK0ViVqWkLBGETAdgl/DUvIAN0wfqDpEwW1yBgLwurG2UJdYeAcxAreiwM81xDwrqrwZo9CYbA4PH4ICOQi7KHlMiES79kDaqHciRHAFoG5JfTk8hoIOZqlkY7aMUkTREEXg%2BHQAHgSEvggaUMSKN%2BiQFFU%2BiZII8S5ChdTwU0iH9IU0G1IUeFgZwbSKp03RcIKwqip6o4yj0WxYiar4mtw6ypsMmaopwqJZgyuCECQqrqqQwx6JG0bOOJRzQnKMhyJqXptBA4aoDJMbkJQCayS4yDCKIsTurm0YFsQRYOCWZYVhuNZaXW9BNi2vaYJ2og9qOfbYXgQ4jm246TtOu7kPQ86jouy6rhgvTVgM24bm0%2B6MCwPYngIbjGWI17yNF94QI%2Bz6%2BG%2BH5fgkviaNo0FqkBlgNKBzQesEkF%2BOhgR1a1iRkc1SGVXQqHpB1ph1VhP5JLhjUIW6FRESNhrnoRaS9TECyUUqNEUY6IpihKbbMax7GccMRldnsAkLKiCzCfgRDEOJbhSVpiZyVI6qKXlqlBrqpAIJgzBYC4RWkAasz7KiRzg/sswHJm9qxLwQo9M6pCupwZn7d6PS%2BoIgY6nRPSfoxB0%2BqQ%2BMCm0Q5WVV3BAA%3D). The shifts are generated by the compiler but usually you don't use bitfields (as they're not portable) and operate on raw integer values instead so you'll need to do arithmetic shifts yourself to extract the fields
+ Another example: sign-extend a pointer to make a [canonical address in x86-64](https://en.wikipedia.org/wiki/X86-64#Canonical_form_addresses). This is used to [store additional data in the pointer](https://stackoverflow.com/q/16198700/995714): `char* pointer = (char*)((intptr_t)address << 16 >> 16)`. You can think of this as a 48-bit bitfield at the bottom
+ V8 engine's [SMI optimization](https://stackoverflow.com/q/57348783/995714) stores the value in the top 31 bits so it needs a right shift to restore the signed integer
* [Round signed division properly](https://stackoverflow.com/q/15916876/995714) when [converting to a multiplication](https://stackoverflow.com/q/41183935/995714), for example `x/12` will be optimized to `x*43691 >> 19` with some additional rounding. Of course you'll never do this in normal scalar code because the compiler already does this for you but sometimes you may need to vectorize the code or [make some related libraries](https://github.com/ridiculousfish/libdivide) then you'll need to calculate the rounding yourself with arithmetic shift. You can see how compilers round the division results in the output assembly for bitfield above
* Saturated shift or shifts larger than bit width, i.e. the value becomes zero when the shift count >= bit width
```
uint32_t lsh_saturated(uint32_t x, int32_t n) // returns 0 if n == 32
{
return (x << (n & 0x1F)) & ((n-32) >> 5);
}
uint32_t lsh(uint32_t x, int32_t n) // returns 0 if n >= 32
{
return (x << (n & 0x1F)) & ((n-32) >> 31);
}
```
* Bit mask, useful in various cases like branchless selection (i.e. [muxer](https://en.wikipedia.org/wiki/Multiplexer)). You can see lots of ways to conditionally do something on the famous [bithacks page](https://graphics.stanford.edu/%7Eseander/bithacks.html). Most of them are done by generating a mask of all ones or all zeros. The mask is usually calculated by propagating the sign bit of a subtraction like this `(x - y) >> 31` (for 32-bit ints). Of course it can be changed to `-(unsigned(x - y) >> 31)` but that requires 2's complement and needs more operations. Here's the way to get the min and max of two integers without branching:
```
min = y + ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));
max = x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));
```
Another example is `m = m & -((signed)(m - d) >> s);` in [Compute modulus division by (1 << s) - 1 in parallel without a division operator](https://graphics.stanford.edu/%7Eseander/bithacks.html#ModulusDivisionParallel)
|
I am not too sure what you mean. BUt i'm going to speculate that you want to use the bit shift as an arithmetic function.
One interesting thing i have seen is this property of binary numbers.
```
int n = 4;
int k = 1;
n = n << k; // is the same as n = n * 2^k
//now n = (4 * 2) i.e. 8
n = n >> k; // is the same as n = n / 2^k
//now n = (8 / 2) i.e. 4
```
hope that helps.
But yes you want to be careful of negative numbers
i would mask and then turn it back accordingly
|
25,056,700
|
I am trying to connect to cassandra from python , I have installed `cassandra` as `pip install pycassa`.When i am trying to connect to the `cassandra` i am getting the following exception
```
from pycassa.pool import ConnectionPool
pool = ConnectionPool('Keyspace1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 382, in __init__
self.fill()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 442, in fill
conn = self._create_connection()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 431, in _create_connection
(exc.__class__.__name__, exc))
pycassa.pool.AllServersUnavailable: An attempt was made to connect to each of the servers twice, but none of the attempts succeeded. The last failure was TTransportException: Could not connect to localhost:9160
```
I am using python 2.7.
What is the problem, Any help would be appreciated.
|
2014/07/31
|
[
"https://Stackoverflow.com/questions/25056700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
Perhaps the best known is the *branchless absolute value*:
```
int m = x >> 31;
int abs = x + m ^ m;
```
Which uses an arithmetic shift to copy the signbit to all bits. Most uses of arithmetic shift that I've encountered were of that form. Of course an arithmetic shift is not *required* for this, you could replace all occurrences of `x >> 31` (where `x` is an `int`) by `-(x >>> 31)`.
The value 31 comes from the size of `int` in bits, which is 32 by definition in Java. So shifting right by 31 shifts out all bits except the signbit, which (since it's an arithmetic shift) is copied to those 31 bits, leaving a copy of the signbit in every position.
|
I am not too sure what you mean. BUt i'm going to speculate that you want to use the bit shift as an arithmetic function.
One interesting thing i have seen is this property of binary numbers.
```
int n = 4;
int k = 1;
n = n << k; // is the same as n = n * 2^k
//now n = (4 * 2) i.e. 8
n = n >> k; // is the same as n = n / 2^k
//now n = (8 / 2) i.e. 4
```
hope that helps.
But yes you want to be careful of negative numbers
i would mask and then turn it back accordingly
|
25,056,700
|
I am trying to connect to cassandra from python , I have installed `cassandra` as `pip install pycassa`.When i am trying to connect to the `cassandra` i am getting the following exception
```
from pycassa.pool import ConnectionPool
pool = ConnectionPool('Keyspace1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 382, in __init__
self.fill()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 442, in fill
conn = self._create_connection()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 431, in _create_connection
(exc.__class__.__name__, exc))
pycassa.pool.AllServersUnavailable: An attempt was made to connect to each of the servers twice, but none of the attempts succeeded. The last failure was TTransportException: Could not connect to localhost:9160
```
I am using python 2.7.
What is the problem, Any help would be appreciated.
|
2014/07/31
|
[
"https://Stackoverflow.com/questions/25056700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
Here's an example of a function that will find the least power of two greater than or equal to the input. There are other solutions to this problem that are probably faster, namly any hardware oriented solution or just a series of right shifts and ORs. This solution uses arithmetic shift to perform a binary search.
```
unsigned ClosestPowerOfTwo(unsigned num) {
int mask = 0xFFFF0000;
mask = (num & mask) ? (mask << 8) : (mask >> 8);
mask = (num & mask) ? (mask << 4) : (mask >> 4);
mask = (num & mask) ? (mask << 2) : (mask >> 2);
mask = (num & mask) ? (mask << 1) : (mask >> 1);
mask = (num & mask) ? mask : (mask >> 1);
return (num & mask) ? -mask : -(mask << 1);
}
```
|
I am not too sure what you mean. BUt i'm going to speculate that you want to use the bit shift as an arithmetic function.
One interesting thing i have seen is this property of binary numbers.
```
int n = 4;
int k = 1;
n = n << k; // is the same as n = n * 2^k
//now n = (4 * 2) i.e. 8
n = n >> k; // is the same as n = n / 2^k
//now n = (8 / 2) i.e. 4
```
hope that helps.
But yes you want to be careful of negative numbers
i would mask and then turn it back accordingly
|
25,056,700
|
I am trying to connect to cassandra from python , I have installed `cassandra` as `pip install pycassa`.When i am trying to connect to the `cassandra` i am getting the following exception
```
from pycassa.pool import ConnectionPool
pool = ConnectionPool('Keyspace1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 382, in __init__
self.fill()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 442, in fill
conn = self._create_connection()
File "/usr/lib/python2.7/site-packages/pycassa/pool.py", line 431, in _create_connection
(exc.__class__.__name__, exc))
pycassa.pool.AllServersUnavailable: An attempt was made to connect to each of the servers twice, but none of the attempts succeeded. The last failure was TTransportException: Could not connect to localhost:9160
```
I am using python 2.7.
What is the problem, Any help would be appreciated.
|
2014/07/31
|
[
"https://Stackoverflow.com/questions/25056700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] |
Here's an example of a function that will find the least power of two greater than or equal to the input. There are other solutions to this problem that are probably faster, namly any hardware oriented solution or just a series of right shifts and ORs. This solution uses arithmetic shift to perform a binary search.
```
unsigned ClosestPowerOfTwo(unsigned num) {
int mask = 0xFFFF0000;
mask = (num & mask) ? (mask << 8) : (mask >> 8);
mask = (num & mask) ? (mask << 4) : (mask >> 4);
mask = (num & mask) ? (mask << 2) : (mask >> 2);
mask = (num & mask) ? (mask << 1) : (mask >> 1);
mask = (num & mask) ? mask : (mask >> 1);
return (num & mask) ? -mask : -(mask << 1);
}
```
|
In C when writing device drivers, bit shift operators are used extensively since bits are used as switches that need to be turned on and off. Bit shift allow one to easily and correctly target the right switch.
Many hashing and cryptographic functions make use of bit shift. Take a look at [Mercenne Twister](https://en.wikipedia.org/wiki/Mersenne_twister#Pseudocode).
Lastly, it is sometimes useful to use bitfields to contain state information. Bit manipulation functions including bit shift are useful for these things.
|
45,920,527
|
I would like to download a subset of a WAT archive segment from Amazon S3.
**Background:**
Searching the Common Crawl index at <http://index.commoncrawl.org> yields results with information about the location of WARC files on AWS S3. For example, searching for [url=www.celebuzz.com/2017-01-04/\*&output=json](http://index.commoncrawl.org/CC-MAIN-2017-34-index?url=www.celebuzz.com%2F2017-01-04%2F*&output=json) yields JSON-formatted results, one of which is
`{
"urlkey":"com,celebuzz)/2017-01-04/watch-james-corden-george-michael-tribute",
...
"filename":"crawl-data/CC-MAIN-2017-34/segments/1502886104631.25/warc/CC-MAIN-20170818082911-20170818102911-00023.warc.gz",
...
"offset":"504411150",
"length":"14169",
...
}`
The `filename` entry indicates which archive segment contains the WARC file for this particular page. This archive file is huge; but fortunately the entry also contains `offset` and `length` fields, which can be used to request the range of bytes containing the relevant subset of the archive segment (see, e.g., [lines 22-30 in this gist](https://gist.github.com/Smerity/56bc6f21a8adec920ebf)).
**My question:**
Given the location of a WARC file segment, I know how to construct the name of the corresponding WAT archive segment (see, e.g., [this tutorial](https://dmorgan.info/posts/common-crawl-python/)). I only need a subset of the WAT file, so I would like to request a range of bytes. But how do I find the corresponding offset and length for the WAT archive segment?
I have checked the [API documentation](https://github.com/ikreymer/pywb/wiki/CDX-Server-API) for the Common Crawl index server, and it isn't clear to me that this is even possible. But in case it is, I'm posting this question.
|
2017/08/28
|
[
"https://Stackoverflow.com/questions/45920527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2861935/"
] |
The Common Crawl index does not contain offsets into WAT and WET files. So, the only way is to search the whole WAT/WET file for the desired record/URL. Eventually, it would be possible to estimate the offset because the record order in WARC and WAT/WET files is the same.
|
After many trial and error I had managed to get a range from a warc file in python and boto3 the following way:
```
# You have this form the index
offset, length, filename = 2161478, 12350, "crawl-data/[...].warc.gz"
import boto3
from botocore import UNSIGNED
from botocore.client import Config
# Boto3 anonymous login to common crawl
s3 = boto3.client('s3', config=Config(signature_version=UNSIGNED))
# Count the range
offset_end = offset + length - 1
byte_range = 'bytes={offset}-{end}'.format(offset=2161478, end=offset_end)
gzipped_text = s3.get_object(Bucket='commoncrawl', Key=filename, Range=byte_range)['Body'].read()
# The requested file in GZIP
with open("file.gz", 'w') as f:
f.write(gzipped_text)
```
The rest is optimisation... Hope it helps! :)
|
52,898,576
|
I am trying to read a json data from an input file, and to pass it as the request to make a http call in python.
Here is the highlights in my python code:
```
with open('input.json') as f:
raw_data = json.load(f)
cookies = ...
headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Accept': 'application/json text/plain, */*',
...
}
response = requests.put('https://.../template/...02420afe4907', headers=headers, cookies=cookies, data=raw_data)
```
but it fails for 400 Error. The response contents shows:
```
b'<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>Error</title>\n</head>\n<body>\n<pre>SyntaxError: Unexpected token # in JSON at position 0<br>
```
But if I initialize it directly, such as:
```
raw_data = '{"name":"template-123","comment":"",...}'
```
The call can be made successfully.
This is the my input.json looks like:
```
{
"name":"template-123",
"comment":"",
...
}
```
Does anyone know how to fix this. **I need to get the original data from this file.** Thanks.
|
2018/10/19
|
[
"https://Stackoverflow.com/questions/52898576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3595231/"
] |
When you pass a `dict` (which is what `raw_data` is) as the `data` argument to `requests.put`, it will be form-encoded, which does not make for valid JSON. Either pass serialized JSON to `data`:
```
requests.put(..., data=json.dumps(raw_data), ...)
```
or use the `json` keyword and let `requests` do the serialization for you:
```
requests.put(..., json=raw_data, ...)
```
|
```
with open('input.json') as f:
```
did you mean
```
with open('input.json','r') as f:
```
or
```
with open('input.json','rb') as f:
```
if the data is stored as bytes, you have to read it in as 'rb'.
|
58,660,173
|
Given a list of dictionaries like:
```
history = [
{
"actions": [{"action": "baz", "people": ["a"]}, {"action": "qux", "people": ["d", "e"]}],
"events": ["foo"]
},
{
"actions": [{"action": "baz", "people": ["a", "b", "c"]}],
"events": ["foo", "bar"]
},
]
```
What is the most efficient (whilst still readable) way to get a list of dicts, where each dict is an unique `event` and the list of actions for that event have been merged based on the `action` key. For example, for the above list, the desired output is:
```
output = [
{
"event": "foo",
"actions": [
{"action": "baz", "people": ["a", "b", "c"]},
{"action": "qux", "people": ["d", "e"]}
]
},
{
"event": "bar",
"actions": [
{"action": "baz", "people": ["a", "b", "c"]}
]
},
]
```
I can't change the output structure as it's being consumed by something external. I've wrote the following code which works but is very verbose and has poor readability.
```
from collections import defaultdict
def transform(history):
d = defaultdict(list)
for item in history:
for event in item["events"]:
d[event] = d[event] + item["actions"]
transformed = []
for event, actions in d.items():
merged_actions = {}
for action in actions:
name = action["action"]
if merged_actions.get(name):
merged_actions[name]["people"] = list(set(action["people"]) | set(merged_actions[name]["people"]))
else:
merged_actions[name] = {
"action": action["action"],
"people": action["people"]
}
transformed.append({
"event": event,
"actions": list(merged_actions.values())
})
return transformed
```
I'm only targeting python3.6+
|
2019/11/01
|
[
"https://Stackoverflow.com/questions/58660173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4007992/"
] |
You can use `collections.defaultdict` with `itertools.groupby`:
```
from collections import defaultdict
from itertools import groupby as gb
d = defaultdict(list)
for i in history:
for b in i['events']:
d[b].extend(i['actions'])
new_d = {a:[(j, list(k)) for j, k in gb(sorted(b, key=lambda x:x['action']), key=lambda x:x['action'])] for a, b in d.items()}
result = [{'event':a, 'actions':[{'action':c, 'people':list(set([i for k in b for i in k['people']]))} for c, b in d]} for a, d in new_d.items()]
```
Output:
```
[
{'event': 'foo',
'actions': [
{'action': 'baz', 'people': ['b', 'a', 'c']},
{'action': 'qux', 'people': ['d', 'e']}
]
},
{'event': 'bar',
'actions': [{'action': 'baz', 'people': ['b', 'a', 'c']}]
}
]
```
|
It is not a less verbose answer, but maybe a bit better readable. Also it does not depend on anything else and is just standard python.
```
tmp_dict = {}
for d in history:
for event in d["events"]:
if event not in tmp_dict:
tmp_dict[event] = {}
for actions in d["actions"]:
tmp_dict[event][actions["action"]] = actions["people"]
else:
for actions in d["actions"]:
if actions["action"] in tmp_dict[event]:
tmp_dict[event][actions["action"]].extend(actions["people"])
else:
tmp_dict[event][actions["action"]] = actions["people"]
output = [{"event": event, "actions": [{"action": ac, "people": list(set(peop))} for ac, peop in tmp_dict[event].items()]} for event in tmp_dict]
print (output)
```
Output:
```
[
{'event': 'foo',
'actions': [
{'action': 'qux', 'people': ['e', 'd']},
{'action': 'baz', 'people': ['a', 'c', 'b']}
]
},
{'event': 'bar',
'actions': [{'action': 'baz', 'people': ['a', 'c', 'b']}]
}
]
```
|
25,043,982
|
i'm having some trouble to handle jpeg files on Python under AWS Elastic Beanstalk.
I have this on .ebextensions/python.config file:
```
packages:
yum:
libjpeg-turbo-devel: []
libpng-devel: []
freetype-devel: []
...
```
So i believe i have libjpeg installed and working (i tried libjpeg-devel, but yum can't find this package).
Also, i have this on my requirements.txt:
```
Pillow==2.5.1
...
```
So i believe i have Pillow installed and working on my environment.
Then, since i have Pillow and libjpeg, i'm trying to do some work using PIL.Image in a Python script and save to a file. Like this:
```
from PIL import Image
def resize_image(image,new_size,crop=False,correctOrientationSize=False):
assert type(new_size) == dict
assert new_size.has_key('width') and new_size.has_key('height')
THUM_SIZE = [new_size['width'],new_size['height']]
file_like = cStringIO.StringIO(base64.decodestring(image))
thumbnail = Image.open(file_like)
(width,height) = thumbnail.size
if correctOrientationSize and height > width:
THUM_SIZE.reverse()
thumbnail.thumbnail(THUM_SIZE)
if crop:
# Recorta imagem
thumbnail = crop_image(thumbnail)
output = cStringIO.StringIO()
thumbnail.save(output,format='jpeg')
return output.getvalue().encode('base64')
```
However, when i try to run it on Elastic Beanstalk's instance, the exception "decoder jpeg not available" when it calls .save() method.
If i SSH into my instance, it works just fine and i already tried to rebuild the environment.
What am i doing wrong?
**UPDATE:**
As suggested, i SSHed again into the instance and reinstalled Pillow through pip (/opt/python/run/venv/bin/pip), not before i has had sure libjpeg-devel was on environment before Pillow.
I ran selftest.py and it confirmed that i had support for jpeg. So, in a last try, i went to "Restart App Server" on Elastic Beanstalk interface. It worked.
Thank you all.
|
2014/07/30
|
[
"https://Stackoverflow.com/questions/25043982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541615/"
] |
Following the general advice from [here](https://stackoverflow.com/questions/8915296/python-image-library-fails-with-message-decoder-jpeg-not-available-pil?rq=1), I solved this by adding the following in my .ebextensions configuration and re-deploying.
```
packages:
yum:
libjpeg-turbo-devel: []
libpng-devel: []
freetype-devel: []
container_commands:
...
05_uninstall_pil:
command: "source /opt/python/run/venv/bin/activate && yes | pip uninstall Pillow"
06_reinstall_pil:
command: "source /opt/python/run/venv/bin/activate && yes | pip install Pillow --no-cache-dir"
```
|
As suggested, I SSHed again into the instance and reinstalled Pillow through pip (/opt/python/run/venv/bin/pip), not before I has had sure libjpeg-devel was on environment before Pillow.
I ran selftest.py and it confirmed that I had support for jpeg. So, in a last try, I went to "Restart App Server" on Elastic Beanstalk interface. It worked.
|
25,087,111
|
I'm running a simulation on a 2D space with periodic boundary conditions. A continuous function is represented by its values on a grid. I need to be able to evaluate the function and its gradient at any point in the space. Fundamentally, this isn't a hard problem -- or to be precise, it's an almost already solved problem. The function can be interpolated using a cubic spline with scipy.interpolate.RectBivariateSpline. The reason it's *almost* solved is that RectBivariateSpline cannot handle periodic boundary conditions, nor can anything else in scipy.interpolate, as far as I can figure out from the documentation.
Is there a python package that can do this? If not, can I adapt scipy.interpolate to handle periodic boundary conditions? For instance, would it be enough to put a border of, say, four grid elements around the entire space and explicitly represent the periodic condition on it?
[ADDENDUM] A little more detail, in case it matters: I am simulating the motion of animals in a chemical gradient. The continuous function I mentioned above is the concentration of a chemical that they are attracted to. It changes with time and space according to a straightforward reaction/diffusion equation. Each animal has an x,y position (which cannot be assumed to be at a grid point). They move up the gradient of attractant. I'm using periodic boundary conditions as a simple way of imitating an unbounded space.
|
2014/08/01
|
[
"https://Stackoverflow.com/questions/25087111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2672942/"
] |
It appears that the python function that comes closest is scipy.signal.cspline2d. This is exactly what I want, *except* that it assumes mirror-symmetric boundary conditions. Thus, it appears that I have three options:
1. Write my own cubic spline interpolation function that works with periodic boundary conditions, perhaps using the cspline2d sources (which are based on functions written in C) as a starting point.
2. The kludge: the effect of data at i on the spline coefficient at j
goes as r^|i-j|, with r = -2 + sqrt(3) ~ -0.26. So the effect of
the edge is down to r^20 ~ 10^-5 if I nest the grid within a border
of width 20 all the way around that replicates the periodic values,
something like this:
bzs1 = np.array(
[zs1[i%n,j%n] for i in range(-20, n+20) for j in range(-20, n+20)] )
bzs1 = bzs1.reshape((n + 40, n + 40))
Then I call cspline2d on the whole array, but use only the middle. This should work, but it's ugly.
3. Use Hermite interpolation instead. In a 2D regular grid, this corresponds to [bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation). The disadvantage is that the interpolated function has a discontinuous second derivative. The advantages are it is (1) relatively easy to code, and (2) for my application, computationally efficient. At the moment, this is the solution I'm favoring.
I did the math for interpolation with trig functions rather than polynomials, as @mdurant suggested. It turns out to be very similar to the cubic spline, but requires more computation and produces worse results, so I won't be doing that.
**EDIT:** A colleague told me of a fourth solution:
1. The [GNU Scientific Library](http://www.gnu.org/software/gsl/) (GSL) has interpolation functions that can handle periodic boundary conditions. There are two (at least) python interfaces to GSL: [PyGSL](http://pygsl.sourceforge.net/) and [CythonGSL](https://github.com/twiecki/CythonGSL). Unfortunately, GSL interpolation seems to be restricted to one dimension, so it's not a lot of use to me, but there's lots of good stuff in GSL.
|
Another function that could work is `scipy.ndimage.interpolation.map_coordinates`.
It does spline interpolation with periodic boundary conditions.
It does not not directly provide derivatives, but you could calculate them numerically.
|
25,087,111
|
I'm running a simulation on a 2D space with periodic boundary conditions. A continuous function is represented by its values on a grid. I need to be able to evaluate the function and its gradient at any point in the space. Fundamentally, this isn't a hard problem -- or to be precise, it's an almost already solved problem. The function can be interpolated using a cubic spline with scipy.interpolate.RectBivariateSpline. The reason it's *almost* solved is that RectBivariateSpline cannot handle periodic boundary conditions, nor can anything else in scipy.interpolate, as far as I can figure out from the documentation.
Is there a python package that can do this? If not, can I adapt scipy.interpolate to handle periodic boundary conditions? For instance, would it be enough to put a border of, say, four grid elements around the entire space and explicitly represent the periodic condition on it?
[ADDENDUM] A little more detail, in case it matters: I am simulating the motion of animals in a chemical gradient. The continuous function I mentioned above is the concentration of a chemical that they are attracted to. It changes with time and space according to a straightforward reaction/diffusion equation. Each animal has an x,y position (which cannot be assumed to be at a grid point). They move up the gradient of attractant. I'm using periodic boundary conditions as a simple way of imitating an unbounded space.
|
2014/08/01
|
[
"https://Stackoverflow.com/questions/25087111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2672942/"
] |
It appears that the python function that comes closest is scipy.signal.cspline2d. This is exactly what I want, *except* that it assumes mirror-symmetric boundary conditions. Thus, it appears that I have three options:
1. Write my own cubic spline interpolation function that works with periodic boundary conditions, perhaps using the cspline2d sources (which are based on functions written in C) as a starting point.
2. The kludge: the effect of data at i on the spline coefficient at j
goes as r^|i-j|, with r = -2 + sqrt(3) ~ -0.26. So the effect of
the edge is down to r^20 ~ 10^-5 if I nest the grid within a border
of width 20 all the way around that replicates the periodic values,
something like this:
bzs1 = np.array(
[zs1[i%n,j%n] for i in range(-20, n+20) for j in range(-20, n+20)] )
bzs1 = bzs1.reshape((n + 40, n + 40))
Then I call cspline2d on the whole array, but use only the middle. This should work, but it's ugly.
3. Use Hermite interpolation instead. In a 2D regular grid, this corresponds to [bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation). The disadvantage is that the interpolated function has a discontinuous second derivative. The advantages are it is (1) relatively easy to code, and (2) for my application, computationally efficient. At the moment, this is the solution I'm favoring.
I did the math for interpolation with trig functions rather than polynomials, as @mdurant suggested. It turns out to be very similar to the cubic spline, but requires more computation and produces worse results, so I won't be doing that.
**EDIT:** A colleague told me of a fourth solution:
1. The [GNU Scientific Library](http://www.gnu.org/software/gsl/) (GSL) has interpolation functions that can handle periodic boundary conditions. There are two (at least) python interfaces to GSL: [PyGSL](http://pygsl.sourceforge.net/) and [CythonGSL](https://github.com/twiecki/CythonGSL). Unfortunately, GSL interpolation seems to be restricted to one dimension, so it's not a lot of use to me, but there's lots of good stuff in GSL.
|
These functions can be found at my github, [`master/hmc/lattice.py`](https://github.com/flipdazed/Hybrid-Monte-Carlo/tree/master/hmc/lattice.py):
* **Periodic boundary conditions** The `Periodic_Lattice()` class is [described here](https://stackoverflow.com/a/38066786/4013571) in full.
* **Lattice Derivatives** In the repository you will find a laplacian function, a squared gradient (for the gradient just take the square root) and and overloaded version of `np.ndarray`
* **Unit Tests** The test cases can be found in same repo in [`tests/test_lattice.py`](https://github.com/flipdazed/Hybrid-Monte-Carlo/blob/master/test/test_lattice.py)
|
25,087,111
|
I'm running a simulation on a 2D space with periodic boundary conditions. A continuous function is represented by its values on a grid. I need to be able to evaluate the function and its gradient at any point in the space. Fundamentally, this isn't a hard problem -- or to be precise, it's an almost already solved problem. The function can be interpolated using a cubic spline with scipy.interpolate.RectBivariateSpline. The reason it's *almost* solved is that RectBivariateSpline cannot handle periodic boundary conditions, nor can anything else in scipy.interpolate, as far as I can figure out from the documentation.
Is there a python package that can do this? If not, can I adapt scipy.interpolate to handle periodic boundary conditions? For instance, would it be enough to put a border of, say, four grid elements around the entire space and explicitly represent the periodic condition on it?
[ADDENDUM] A little more detail, in case it matters: I am simulating the motion of animals in a chemical gradient. The continuous function I mentioned above is the concentration of a chemical that they are attracted to. It changes with time and space according to a straightforward reaction/diffusion equation. Each animal has an x,y position (which cannot be assumed to be at a grid point). They move up the gradient of attractant. I'm using periodic boundary conditions as a simple way of imitating an unbounded space.
|
2014/08/01
|
[
"https://Stackoverflow.com/questions/25087111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2672942/"
] |
It appears that the python function that comes closest is scipy.signal.cspline2d. This is exactly what I want, *except* that it assumes mirror-symmetric boundary conditions. Thus, it appears that I have three options:
1. Write my own cubic spline interpolation function that works with periodic boundary conditions, perhaps using the cspline2d sources (which are based on functions written in C) as a starting point.
2. The kludge: the effect of data at i on the spline coefficient at j
goes as r^|i-j|, with r = -2 + sqrt(3) ~ -0.26. So the effect of
the edge is down to r^20 ~ 10^-5 if I nest the grid within a border
of width 20 all the way around that replicates the periodic values,
something like this:
bzs1 = np.array(
[zs1[i%n,j%n] for i in range(-20, n+20) for j in range(-20, n+20)] )
bzs1 = bzs1.reshape((n + 40, n + 40))
Then I call cspline2d on the whole array, but use only the middle. This should work, but it's ugly.
3. Use Hermite interpolation instead. In a 2D regular grid, this corresponds to [bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation). The disadvantage is that the interpolated function has a discontinuous second derivative. The advantages are it is (1) relatively easy to code, and (2) for my application, computationally efficient. At the moment, this is the solution I'm favoring.
I did the math for interpolation with trig functions rather than polynomials, as @mdurant suggested. It turns out to be very similar to the cubic spline, but requires more computation and produces worse results, so I won't be doing that.
**EDIT:** A colleague told me of a fourth solution:
1. The [GNU Scientific Library](http://www.gnu.org/software/gsl/) (GSL) has interpolation functions that can handle periodic boundary conditions. There are two (at least) python interfaces to GSL: [PyGSL](http://pygsl.sourceforge.net/) and [CythonGSL](https://github.com/twiecki/CythonGSL). Unfortunately, GSL interpolation seems to be restricted to one dimension, so it's not a lot of use to me, but there's lots of good stuff in GSL.
|
I have been using the following function which augments the input to create data with effective periodic boundary conditions. Augmenting the data has a distinct advantage over modifying an existing algorithm: the augmented data can easily be interpolated using any algorithm. See below for an example.
```
def augment_with_periodic_bc(points, values, domain):
"""
Augment the data to create periodic boundary conditions.
Parameters
----------
points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
The points defining the regular grid in n dimensions.
values : array_like, shape (m1, ..., mn, ...)
The data on the regular grid in n dimensions.
domain : float or None or array_like of shape (n, )
The size of the domain along each of the n dimenions
or a uniform domain size along all dimensions if a
scalar. Using None specifies aperiodic boundary conditions.
Returns
-------
points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
The points defining the regular grid in n dimensions with
periodic boundary conditions.
values : array_like, shape (m1, ..., mn, ...)
The data on the regular grid in n dimensions with periodic
boundary conditions.
"""
# Validate the domain argument
n = len(points)
if np.ndim(domain) == 0:
domain = [domain] * n
if np.shape(domain) != (n,):
raise ValueError("`domain` must be a scalar or have the same "
"length as `points`")
# Pre- and append repeated points
points = [x if d is None else np.concatenate([x - d, x, x + d])
for x, d in zip(points, domain)]
# Tile the values as necessary
reps = [1 if d is None else 3 for d in domain]
values = np.tile(values, reps)
return points, values
```
Example
=======
The example below shows interpolation with periodic boundary conditions in one dimension but the function above can be applied in arbitrary dimensions.
[](https://i.stack.imgur.com/YTQnF.png)
```
rcParams['figure.dpi'] = 144
fig, axes = plt.subplots(2, 2, True, True)
np.random.seed(0)
x = np.linspace(0, 1, 10, endpoint=False)
y = np.sin(2 * np.pi * x)
ax = axes[0, 0]
ax.plot(x, y, marker='.')
ax.set_title('Points to interpolate')
sampled = np.random.uniform(0, 1, 100)
y_sampled = interpolate.interpn([x], y, sampled, bounds_error=False)
valid = ~np.isnan(y_sampled)
ax = axes[0, 1]
ax.scatter(sampled, np.where(valid, y_sampled, 0), marker='.', c=np.where(valid, 'C0', 'C1'))
ax.set_title('interpn w/o periodic bc')
[x], y = augment_with_periodic_bc([x], y, domain=1.0)
y_sampled_bc = interpolate.interpn([x], y, sampled)
ax = axes[1, 0]
ax.scatter(sampled, y_sampled_bc, marker='.')
ax.set_title('interpn w/ periodic bc')
y_sampled_bc_cubic = interpolate.interp1d(x, y, 'cubic')(sampled)
ax = axes[1, 1]
ax.scatter(sampled, y_sampled_bc_cubic, marker='.')
ax.set_title('cubic interp1d w/ periodic bc')
fig.tight_layout()
```
|
25,087,111
|
I'm running a simulation on a 2D space with periodic boundary conditions. A continuous function is represented by its values on a grid. I need to be able to evaluate the function and its gradient at any point in the space. Fundamentally, this isn't a hard problem -- or to be precise, it's an almost already solved problem. The function can be interpolated using a cubic spline with scipy.interpolate.RectBivariateSpline. The reason it's *almost* solved is that RectBivariateSpline cannot handle periodic boundary conditions, nor can anything else in scipy.interpolate, as far as I can figure out from the documentation.
Is there a python package that can do this? If not, can I adapt scipy.interpolate to handle periodic boundary conditions? For instance, would it be enough to put a border of, say, four grid elements around the entire space and explicitly represent the periodic condition on it?
[ADDENDUM] A little more detail, in case it matters: I am simulating the motion of animals in a chemical gradient. The continuous function I mentioned above is the concentration of a chemical that they are attracted to. It changes with time and space according to a straightforward reaction/diffusion equation. Each animal has an x,y position (which cannot be assumed to be at a grid point). They move up the gradient of attractant. I'm using periodic boundary conditions as a simple way of imitating an unbounded space.
|
2014/08/01
|
[
"https://Stackoverflow.com/questions/25087111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2672942/"
] |
Another function that could work is `scipy.ndimage.interpolation.map_coordinates`.
It does spline interpolation with periodic boundary conditions.
It does not not directly provide derivatives, but you could calculate them numerically.
|
These functions can be found at my github, [`master/hmc/lattice.py`](https://github.com/flipdazed/Hybrid-Monte-Carlo/tree/master/hmc/lattice.py):
* **Periodic boundary conditions** The `Periodic_Lattice()` class is [described here](https://stackoverflow.com/a/38066786/4013571) in full.
* **Lattice Derivatives** In the repository you will find a laplacian function, a squared gradient (for the gradient just take the square root) and and overloaded version of `np.ndarray`
* **Unit Tests** The test cases can be found in same repo in [`tests/test_lattice.py`](https://github.com/flipdazed/Hybrid-Monte-Carlo/blob/master/test/test_lattice.py)
|
25,087,111
|
I'm running a simulation on a 2D space with periodic boundary conditions. A continuous function is represented by its values on a grid. I need to be able to evaluate the function and its gradient at any point in the space. Fundamentally, this isn't a hard problem -- or to be precise, it's an almost already solved problem. The function can be interpolated using a cubic spline with scipy.interpolate.RectBivariateSpline. The reason it's *almost* solved is that RectBivariateSpline cannot handle periodic boundary conditions, nor can anything else in scipy.interpolate, as far as I can figure out from the documentation.
Is there a python package that can do this? If not, can I adapt scipy.interpolate to handle periodic boundary conditions? For instance, would it be enough to put a border of, say, four grid elements around the entire space and explicitly represent the periodic condition on it?
[ADDENDUM] A little more detail, in case it matters: I am simulating the motion of animals in a chemical gradient. The continuous function I mentioned above is the concentration of a chemical that they are attracted to. It changes with time and space according to a straightforward reaction/diffusion equation. Each animal has an x,y position (which cannot be assumed to be at a grid point). They move up the gradient of attractant. I'm using periodic boundary conditions as a simple way of imitating an unbounded space.
|
2014/08/01
|
[
"https://Stackoverflow.com/questions/25087111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2672942/"
] |
Another function that could work is `scipy.ndimage.interpolation.map_coordinates`.
It does spline interpolation with periodic boundary conditions.
It does not not directly provide derivatives, but you could calculate them numerically.
|
I have been using the following function which augments the input to create data with effective periodic boundary conditions. Augmenting the data has a distinct advantage over modifying an existing algorithm: the augmented data can easily be interpolated using any algorithm. See below for an example.
```
def augment_with_periodic_bc(points, values, domain):
"""
Augment the data to create periodic boundary conditions.
Parameters
----------
points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
The points defining the regular grid in n dimensions.
values : array_like, shape (m1, ..., mn, ...)
The data on the regular grid in n dimensions.
domain : float or None or array_like of shape (n, )
The size of the domain along each of the n dimenions
or a uniform domain size along all dimensions if a
scalar. Using None specifies aperiodic boundary conditions.
Returns
-------
points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
The points defining the regular grid in n dimensions with
periodic boundary conditions.
values : array_like, shape (m1, ..., mn, ...)
The data on the regular grid in n dimensions with periodic
boundary conditions.
"""
# Validate the domain argument
n = len(points)
if np.ndim(domain) == 0:
domain = [domain] * n
if np.shape(domain) != (n,):
raise ValueError("`domain` must be a scalar or have the same "
"length as `points`")
# Pre- and append repeated points
points = [x if d is None else np.concatenate([x - d, x, x + d])
for x, d in zip(points, domain)]
# Tile the values as necessary
reps = [1 if d is None else 3 for d in domain]
values = np.tile(values, reps)
return points, values
```
Example
=======
The example below shows interpolation with periodic boundary conditions in one dimension but the function above can be applied in arbitrary dimensions.
[](https://i.stack.imgur.com/YTQnF.png)
```
rcParams['figure.dpi'] = 144
fig, axes = plt.subplots(2, 2, True, True)
np.random.seed(0)
x = np.linspace(0, 1, 10, endpoint=False)
y = np.sin(2 * np.pi * x)
ax = axes[0, 0]
ax.plot(x, y, marker='.')
ax.set_title('Points to interpolate')
sampled = np.random.uniform(0, 1, 100)
y_sampled = interpolate.interpn([x], y, sampled, bounds_error=False)
valid = ~np.isnan(y_sampled)
ax = axes[0, 1]
ax.scatter(sampled, np.where(valid, y_sampled, 0), marker='.', c=np.where(valid, 'C0', 'C1'))
ax.set_title('interpn w/o periodic bc')
[x], y = augment_with_periodic_bc([x], y, domain=1.0)
y_sampled_bc = interpolate.interpn([x], y, sampled)
ax = axes[1, 0]
ax.scatter(sampled, y_sampled_bc, marker='.')
ax.set_title('interpn w/ periodic bc')
y_sampled_bc_cubic = interpolate.interp1d(x, y, 'cubic')(sampled)
ax = axes[1, 1]
ax.scatter(sampled, y_sampled_bc_cubic, marker='.')
ax.set_title('cubic interp1d w/ periodic bc')
fig.tight_layout()
```
|
27,214,053
|
I am getting an error when trying to install uinput
I tried PIP and `easy_install`. I also tried to install 'manually' from tar package.
I always get an error. Below is the error I get when installing with easy\_install.
Can you guide me on how to fix it ?
```
rpi@torpi ~/scripts $ sudo easy_install python-uinput
Searching for python-uinput
Reading http://pypi.python.org/simple/python-uinput/
Best match: python-uinput 0.10.2
Downloading https://pypi.python.org/packages/source/p/python-uinput/python-uinput-0.10.2.tar.gz#md5=abbbbfc50d03a0585a5231d9396f78bd
Processing python-uinput-0.10.2.tar.gz
Running python-uinput-0.10.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-ZWLsct/python-uinput-0.10.2/egg-dist-tmp-bPeztQ
/usr/bin/ld: cannot find libudev.so
collect2: ld returned 1 exit status
error: Setup script exited with error: command 'gcc' failed with exit status 1
```
|
2014/11/30
|
[
"https://Stackoverflow.com/questions/27214053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4308766/"
] |
Had this problem and fixed it with
```
sudo apt-get install libudev-dev
```
|
I could not get input to install properly so, I ended up using [evdev](https://pypi.python.org/pypi/evdev) instead.
|
27,214,053
|
I am getting an error when trying to install uinput
I tried PIP and `easy_install`. I also tried to install 'manually' from tar package.
I always get an error. Below is the error I get when installing with easy\_install.
Can you guide me on how to fix it ?
```
rpi@torpi ~/scripts $ sudo easy_install python-uinput
Searching for python-uinput
Reading http://pypi.python.org/simple/python-uinput/
Best match: python-uinput 0.10.2
Downloading https://pypi.python.org/packages/source/p/python-uinput/python-uinput-0.10.2.tar.gz#md5=abbbbfc50d03a0585a5231d9396f78bd
Processing python-uinput-0.10.2.tar.gz
Running python-uinput-0.10.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-ZWLsct/python-uinput-0.10.2/egg-dist-tmp-bPeztQ
/usr/bin/ld: cannot find libudev.so
collect2: ld returned 1 exit status
error: Setup script exited with error: command 'gcc' failed with exit status 1
```
|
2014/11/30
|
[
"https://Stackoverflow.com/questions/27214053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4308766/"
] |
I could not get input to install properly so, I ended up using [evdev](https://pypi.python.org/pypi/evdev) instead.
|
I see that this is a very old question, but I had the same problem, and running `sudo apt-get install libudev-dev` worked for me. Also, make sure to run pip with sudo.
|
27,214,053
|
I am getting an error when trying to install uinput
I tried PIP and `easy_install`. I also tried to install 'manually' from tar package.
I always get an error. Below is the error I get when installing with easy\_install.
Can you guide me on how to fix it ?
```
rpi@torpi ~/scripts $ sudo easy_install python-uinput
Searching for python-uinput
Reading http://pypi.python.org/simple/python-uinput/
Best match: python-uinput 0.10.2
Downloading https://pypi.python.org/packages/source/p/python-uinput/python-uinput-0.10.2.tar.gz#md5=abbbbfc50d03a0585a5231d9396f78bd
Processing python-uinput-0.10.2.tar.gz
Running python-uinput-0.10.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-ZWLsct/python-uinput-0.10.2/egg-dist-tmp-bPeztQ
/usr/bin/ld: cannot find libudev.so
collect2: ld returned 1 exit status
error: Setup script exited with error: command 'gcc' failed with exit status 1
```
|
2014/11/30
|
[
"https://Stackoverflow.com/questions/27214053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4308766/"
] |
Had this problem and fixed it with
```
sudo apt-get install libudev-dev
```
|
I see that this is a very old question, but I had the same problem, and running `sudo apt-get install libudev-dev` worked for me. Also, make sure to run pip with sudo.
|
49,741,030
|
I am building a RESTful API using Python 3.6, the Falcon Framework, Google App Engine, and Firebase Cloud Firestore. At runtime I am receiving the following error ...
```
File "E:\Bill\Documents\GitHubProjects\LetsHang-BackEnd\lib\google\cloud\firestore_v1beta1\_helpers.py", line 24, in <module> import grpc
File "E:\Bill\Documents\GitHubProjects\LetsHang-BackEnd\lib\grpc\__init__.py", line 22, in <module>
from grpc._cython import cygrpc as _cygrpc
ImportError: cannot import name cygrpc
```
When researching StackOverFlow, I found an [article regarding an AWS Lambda deployment](https://stackoverflow.com/questions/46669176/aws-lambda-to-firestore-error-cannot-import-name-cygrpc), but it suggests a solution based on Docker. Docker is not a viable solution for us. I also found an article off StackOverflow that suggests running "pip install grpcio". We did not without luck.
We build the App Engine dependencies using a requirements.txt file. This file has the following contents ...
```
falcon==1.4.1
google-api-python-client
google-cloud-firestore
firebase-admin
enum34
grpcio
```
We apply the requirements file using the command ...
```
pip install -t lib -r requirements.txt
```
The App Engine server is started with the command ...
```
dev_appserver.py .
```
The development environment is Windows 10.
|
2018/04/09
|
[
"https://Stackoverflow.com/questions/49741030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7183052/"
] |
You seem to be mixing up the GAE standard and flexible environments:
* using Python 3.6 is only possible in the flexible environment (which, BTW, is fundamentally Docker-based)
* installing app dependencies in the `lib` directory and using `dev_appserver.py` for local development are only applicable to the standard environment
Somehow related: [How to tell if a Google App Engine documentation page applies to the standard or the flexible environment](https://stackoverflow.com/questions/45842772/how-to-tell-if-a-google-app-engine-documentation-page-applies-to-the-standard-or)
|
Ok. I will write up my findings just in case there's another fool like me.
First, [Dan's](https://stackoverflow.com/users/4495081/dan-cornilescu) response is correct. I was mixing standard and flexible environments. I had looked up a method for using the Falcon Framework with App Engine; as it turns out, the only article uses the standard environment. So that's how I wound up using dev\_appserver.py. My app, however, is Python 3.6 and has dependencies that prevent stepping down to 2.7.
To develop locally for the flexible environment, you simply need to run as you normally would. In the case of Falcon Framework, that means using the Waitress wsgi server.
I find that it is a good practice to build and use a Python virtual environment. You use the virtualenv command for that. At deployment time, Google builds a docker container for the app in the cloud. To reconstruct all the necessary Python packages, you have to supply a requirements.txt file. If you have a virtual environment, then the requirements file is easily produced using pip freeze.
|
62,463,565
|
I have three csv dataframes of tweets, each ~5M tweets. The following code for concatenating them exists with low memory error. My machine has 32GB memory. How can I assign more memory for this task in pandas?
```
df1 = pd.read_csv('tweets.csv')
df2 = pd.read_csv('tweets2.csv')
df3 = pd.read_csv('tweets3.csv')
frames = [df1, df2, df3]
result = pd.concat(frames)
result.to_csv('tweets_combined.csv')
```
The error is:
```
$ python concantenate_dataframes.py
sys:1: DtypeWarning: Columns (0,1,2,3,4,5,6,8,9,10,11,12,13,14,19,22,23,24) have mixed types.Specify dtype option on import or set low_memory=False.
Traceback (most recent call last):
File "concantenate_dataframes.py", line 19, in <module>
df2 = pd.read_csv('tweets2.csv')
File "/home/mona/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 676, in parser_f
return _read(filepath_or_buffer, kwds)
File "/home/mona/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 454, in _read
data = parser.read(nrows)
File "/home/mona/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 1133, in read
ret = self._engine.read(nrows)
File "/home/mona/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 2037, in read
data = self._reader.read(nrows)
File "pandas/_libs/parsers.pyx", line 859, in pandas._libs.parsers.TextReader.read
```
UPDATE: tried the suggestions in the answer and still get error
```
$ python concantenate_dataframes.py
Traceback (most recent call last):
File "concantenate_dataframes.py", line 18, in <module>
df1 = pd.read_csv('tweets.csv', low_memory=False, error_bad_lines=False)
File "/home/mona/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 676, in parser_f
return _read(filepath_or_buffer, kwds)
File "/home/mona/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 454, in _read
data = parser.read(nrows)
File "/home/mona/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 1133, in read
ret = self._engine.read(nrows)
File "/home/mona/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 2037, in read
data = self._reader.read(nrows)
File "pandas/_libs/parsers.pyx", line 862, in pandas._libs.parsers.TextReader.read
File "pandas/_libs/parsers.pyx", line 943, in pandas._libs.parsers.TextReader._read_rows
File "pandas/_libs/parsers.pyx", line 2070, in pandas._libs.parsers.raise_parser_error
pandas.errors.ParserError: Error tokenizing data. C error: Buffer overflow caught - possible malformed input file.
File "pandas/_libs/parsers.pyx", line 874, in pandas._libs.parsers.TextReader._read_low_memory
File "pandas/_libs/parsers.pyx", line 928, in pandas._libs.parsers.TextReader._read_rows
File "pandas/_libs/parsers.pyx", line 915, in pandas._libs.parsers.TextReader._tokenize_rows
File "pandas/_libs/parsers.pyx", line 2070, in pandas._libs.parsers.raise_parser_error
pandas.errors.ParserError: Error tokenizing data. C error: Buffer overflow caught - possible malformed input file.
I am running the code on Ubuntu 20.04 OS
```
|
2020/06/19
|
[
"https://Stackoverflow.com/questions/62463565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2414957/"
] |
I think this is problem with malformed data (some data not structure properly in `tweets2.csv`) for that you can use `error_bad_lines=False` and try to chnage engine from c to python like `engine='python'`
ex : `df2 = pd.read_csv('tweets2.csv', error_bad_lines=False)`
or
ex : `df2 = pd.read_csv('tweets2.csv', engine='python')`
or maybe
ex : `df2 = pd.read_csv('tweets2.csv', engine='python', error_bad_lines=False)`
but I recommand to identify those revord and repair that.
And also if you want hacky way to do this than use
1) <https://askubuntu.com/questions/941480/how-to-merge-multiple-files-of-the-same-format-into-a-single-file>
2) <https://askubuntu.com/questions/656039/concatenate-multiple-files-without-header>[enter link description here](https://askubuntu.com/questions/656039/concatenate-multiple-files-without-header)
|
Specify `dtype` option on import or set `low_memory=False`
|
61,390,586
|
I am currently working on a schoolproject, and im trying to import data from a CSV file to MySQL using python. This is my code so far:
```
import mysql.connector
import csv
mydb = mysql.connector.connect(host='127.0.0.1', user='root', password='abc123!', db='jd_university')
cursor = mydb.cursor()
with open('C:/Users/xxxxxx/Downloads/Students.csv') as csvfile:
reader = csv.DictReader(csvfile, delimiter=',')
for row in reader:
cursor.execute('INSERT INTO Student (First_Name, Last_Name, DOB, Username, Password, Phone_nr,'
'Email, StreetName_nr, ZIP) '
'VALUES("%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s")',
row)
mydb.commit()
cursor.close()
```
When i run this, i get this error: "mysql.connector.errors.DataError: 1292 (22007): Incorrect date value: '%s' for column 'DOB' at row 1"
The date format used in the CSV file are yyyy-mm-dd
Any tips on this would help greatly!
|
2020/04/23
|
[
"https://Stackoverflow.com/questions/61390586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13391817/"
] |
* You don't need to quote the `%s` placeholders.
* Since you're using `DictReader`, you will need to name the columns in your `row` expression (or not use DictReader and hope for the correct order, which I'd not do).
Try this:
```py
import mysql.connector
import csv
mydb = mysql.connector.connect(
host="127.0.0.1", user="root", password="abc123!", db="jd_university"
)
cursor = mydb.cursor()
with open("C:/Users/xxxxxx/Downloads/Students.csv") as csvfile:
reader = csv.DictReader(csvfile, delimiter=",")
for row in reader:
values = [
row["First_Name"],
row["Last_Name"],
row["DOB"],
row["Username"],
row["Password"],
row["Phone_nr"],
row["Email"],
row["StreetName_nr"],
row["ZIP"],
]
cursor.execute(
"INSERT INTO Student (First_Name, Last_Name, DOB, Username, Password, Phone_nr,"
"Email, StreetName_nr, ZIP) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
values,
)
mydb.commit()
cursor.close()
```
|
Validate the datatype for DOB field in your data file and database column. Could be a data issue or table definition issue.
|
25,608,078
|
I am trying to create an SVG font, so I need to create some paths. One of the letters is defined by the following path:

Which I created with [svgwrite](https://pypi.python.org/pypi/svgwrite), by creating two `circles` and a `rect`, and then using inkscape to take the difference of the two circles and the intersection with the straight line, like so:

My question is if I can do this directly with SVG or svgwrite? Either doing the boolean operations, or creating a path that behaves as the one above.
I've tried to create a black and white circle with a path like:
```
d="M0,128 A128,128,1,1,0 0 127.9 Z\
M 32 128 A 96 96 1 1 0 32 127.9 Z"
```
with `fill="#000000", stroke = "none", fill-rule="evenodd"`
However this ring is not recognized by the SVG font editor (it just creates a black disc).
I also tried to create the combination of paths (outer circle, inner circle, horizontal line)
```
d="M0,128 A128,128,1,1,0 0 127.9 Z\
M 32 128 A 96 96 1 1 0 32 127.9 Z \
M 38 128 l 0 15 l 180 0 l 0 -30 l -180 0 z"
```
but although I can see the right-looking result when I open the SVG, the font editor will not recognize the path created which looks like this:

Is there some way to generate programmatically the path of the first picture above?
|
2014/09/01
|
[
"https://Stackoverflow.com/questions/25608078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/218558/"
] |
The first arc has a negative (0) draw angle, the second must have a positive (1) draw angle and drawn from the opposite side to achieve the desired effect.
```py
#--------------------------N-----------↓↓↓-↓↓↓-------------P-↓↓↓-↓↓↓↓↓----------------------------------------------
d="M 0 128 A 128 128 1 1 0 0 127.9 Z M 224 128 A 96 96 1 1 1 224 127.9 Z M 38 128 L 0 15 L 180 0 L 0 -30 L -180 0 Z"
```
|
following @martineau's suggestion and [this](https://stackoverflow.com/questions/5737975/circle-drawing-with-svgs-arc-path) SO question, I came to this solution:
* Create a circle made of two halfs
* Creates two smaller half circles (not quite circular)
* then use [`fill-rule: evenodd`](http://www.w3.org/TR/SVG/painting.html#FillRuleProperty) to combine all of them.
```
d="
M 128, 128
m -128, 0
a 128,128 0 1,0 256,0\
a 128,128 0 1,0 -256,0\
M 32,112 a 1.15 1 0 1 1 194, 0z\
M 32,142 a 1.15 1 0 1 0 194, 0z\
"
```
which returns something like this:
.
Unfortunately, the Inkscape SVG font editor only renders this:

So I'll have to continue investigating where the problem may come from. Further suggestions are welcome.
|
25,608,078
|
I am trying to create an SVG font, so I need to create some paths. One of the letters is defined by the following path:

Which I created with [svgwrite](https://pypi.python.org/pypi/svgwrite), by creating two `circles` and a `rect`, and then using inkscape to take the difference of the two circles and the intersection with the straight line, like so:

My question is if I can do this directly with SVG or svgwrite? Either doing the boolean operations, or creating a path that behaves as the one above.
I've tried to create a black and white circle with a path like:
```
d="M0,128 A128,128,1,1,0 0 127.9 Z\
M 32 128 A 96 96 1 1 0 32 127.9 Z"
```
with `fill="#000000", stroke = "none", fill-rule="evenodd"`
However this ring is not recognized by the SVG font editor (it just creates a black disc).
I also tried to create the combination of paths (outer circle, inner circle, horizontal line)
```
d="M0,128 A128,128,1,1,0 0 127.9 Z\
M 32 128 A 96 96 1 1 0 32 127.9 Z \
M 38 128 l 0 15 l 180 0 l 0 -30 l -180 0 z"
```
but although I can see the right-looking result when I open the SVG, the font editor will not recognize the path created which looks like this:

Is there some way to generate programmatically the path of the first picture above?
|
2014/09/01
|
[
"https://Stackoverflow.com/questions/25608078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/218558/"
] |
The first arc has a negative (0) draw angle, the second must have a positive (1) draw angle and drawn from the opposite side to achieve the desired effect.
```py
#--------------------------N-----------↓↓↓-↓↓↓-------------P-↓↓↓-↓↓↓↓↓----------------------------------------------
d="M 0 128 A 128 128 1 1 0 0 127.9 Z M 224 128 A 96 96 1 1 1 224 127.9 Z M 38 128 L 0 15 L 180 0 L 0 -30 L -180 0 Z"
```
|
Filters don't produce paths, they just produce bitmaps (so if you need a path - this is the wrong answer). But Here's a version using an SVG Filter - since you tagged the question with it (won't work in Firefox - can't use objects as feImage inputs yet - you'd have to inline them as data URI).
```html
<svg width="200px" height="200px">
<defs>
<circle id="inner" cx="80" cy="80" r="60" fill="white" />
<line id="crossbar" x1="20" x2="140" y1="80" y2="80" stroke-width="22" stroke="black"/>
<filter id="combine" x="0%" y="0%">
<feImage xlink:href="#inner" result="innerwhite"/>
<feImage xlink:href="#crossbar" result="crossbarthing"/>
<feComposite operator="xor" in="SourceGraphic" in2="innerwhite"/>
<feComposite operator="over" in2="crossbarthing"/>
</filter>
</defs>
<circle filter="url(#combine)" cx="100" cy="100" fill=
"black" r="80"/>"
</svg>
```
|
44,430,246
|
I have list of dictionaries and in each one of them the key `site` exists.
So in other words, this code returns `True`:
```
all('site' in site for site in summary)
```
Question is, what will be the pythonic way to iterate over the list of dictionaries and return `True` if a key different from `site` exists in any of the dictionaries?
**Example**: in the following list I would like to return `True` because of the existence of `cost` in the last dictionary BUT, I can't tell what will be the other key, it can be `cost` as in the example and it can be other strings; random keys for that matter.
```
[
{"site": "site_A"},
{"site": "site_B"},
{"site": "site_C", "cost": 1000}
]
```
|
2017/06/08
|
[
"https://Stackoverflow.com/questions/44430246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5517847/"
] |
If all dictionaries have the key `site`, the dictionaries have a length of at least 1. The presence of *any other key* would increase the dictionary size to be greater than 1, test for that:
```
any(len(d) > 1 for d in summary)
```
|
You could just check, for each dictionary `dct`:
```
any(key != "site" for key in dct)
```
If you want to check this for a list of dictionaries `dcts`, shove another `any` around that: `any(any(key != "site" for key in dct) for dct in dcts)`
This also makes it easily extensible to allowing multiple different keys. (E.g. `any(key not in ("site", "otherkey") for key in dct)`) Because what's a dictionary good for if you can only use one key?
|
44,430,246
|
I have list of dictionaries and in each one of them the key `site` exists.
So in other words, this code returns `True`:
```
all('site' in site for site in summary)
```
Question is, what will be the pythonic way to iterate over the list of dictionaries and return `True` if a key different from `site` exists in any of the dictionaries?
**Example**: in the following list I would like to return `True` because of the existence of `cost` in the last dictionary BUT, I can't tell what will be the other key, it can be `cost` as in the example and it can be other strings; random keys for that matter.
```
[
{"site": "site_A"},
{"site": "site_B"},
{"site": "site_C", "cost": 1000}
]
```
|
2017/06/08
|
[
"https://Stackoverflow.com/questions/44430246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5517847/"
] |
If all dictionaries have the key `site`, the dictionaries have a length of at least 1. The presence of *any other key* would increase the dictionary size to be greater than 1, test for that:
```
any(len(d) > 1 for d in summary)
```
|
This is a bit longer version, but it gives you what you need. Just to give more options:
```
any({k: v for k, v in site.items() if k != 'site'} for site in summary)
```
|
44,430,246
|
I have list of dictionaries and in each one of them the key `site` exists.
So in other words, this code returns `True`:
```
all('site' in site for site in summary)
```
Question is, what will be the pythonic way to iterate over the list of dictionaries and return `True` if a key different from `site` exists in any of the dictionaries?
**Example**: in the following list I would like to return `True` because of the existence of `cost` in the last dictionary BUT, I can't tell what will be the other key, it can be `cost` as in the example and it can be other strings; random keys for that matter.
```
[
{"site": "site_A"},
{"site": "site_B"},
{"site": "site_C", "cost": 1000}
]
```
|
2017/06/08
|
[
"https://Stackoverflow.com/questions/44430246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5517847/"
] |
You could just check, for each dictionary `dct`:
```
any(key != "site" for key in dct)
```
If you want to check this for a list of dictionaries `dcts`, shove another `any` around that: `any(any(key != "site" for key in dct) for dct in dcts)`
This also makes it easily extensible to allowing multiple different keys. (E.g. `any(key not in ("site", "otherkey") for key in dct)`) Because what's a dictionary good for if you can only use one key?
|
This is a bit longer version, but it gives you what you need. Just to give more options:
```
any({k: v for k, v in site.items() if k != 'site'} for site in summary)
```
|
71,184,380
|
I have two lists. I want to create a `Literal` using both these lists
```python
category1 = ["image/jpeg", "image/png"]
category2 = ["application/pdf"]
SUPPORTED_TYPES = typing.Literal[category1 + category2]
```
Is there any way to do this?
I have seen the question [typing: Dynamically Create Literal Alias from List of Valid Values](https://stackoverflow.com/questions/64522040/typing-dynamically-create-literal-alias-from-list-of-valid-values) but this doesnt work for my use case because I dont want `mimetype` to be of type `typing.Tuple`.
I will be using the `Literal` in a function -
```python
def process_file(filename: str, mimetype: SUPPORTED_TYPES)
```
What I have tried -
```python
supported_types_list = category1 + category2
SUPPORTED_TYPES = Literal[supported_types_list]
SUPPORTED_TYPES = Literal[*supported_types_list]
# this gives 2 different literals, rather i want only 1 literal
SUPPORTED_TYPES = Union[Literal["image/jpeg", "image/png"], Literal["application/pdf"]]
```
|
2022/02/19
|
[
"https://Stackoverflow.com/questions/71184380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14595305/"
] |
Use the same technique as in the question you linked: build the lists from the literal types, instead of the other way around:
```
SUPPORTED_IMAGE_TYPES = typing.Literal["image/jpeg", "image/png"]
SUPPORTED_OTHER_TYPES = typing.Literal["application/pdf"]
SUPPORTED_TYPES = typing.Literal[SUPPORTED_IMAGE_TYPES, SUPPORTED_OTHER_TYPES]
category1 = list(typing.get_args(SUPPORTED_IMAGE_TYPES))
category2 = list(typing.get_args(SUPPORTED_OTHER_TYPES))
```
The only part of this that wasn't already covered in the other answer is `SUPPORTED_TYPES = typing.Literal[SUPPORTED_IMAGE_TYPES, SUPPORTED_OTHER_TYPES]`, which, [yeah, you can do that](https://www.python.org/dev/peps/pep-0586/#legal-parameters-for-literal-at-type-check-time). It's equivalent to your original definition of `SUPPORTED_TYPES`.
|
I got an answer to this -
Create a literal for both the lists, and then create a combined literal
```python
category1 = Literal["image/jpeg", "image/png"]
category2 = Literal["application/pdf"]
SUPPORTED_TYPES = Literal[category1, category2]
```
Sorry: hadnt seen that monica answered the question
|
74,214,700
|
i wrote this code:
```
admitted_List = [1, 5, 10, 50, 100, 500, 1000]
tempString = ""
finalList = []
for i in range(len(xkcd)-1):
if int(xkcd[i] + xkcd[i+1]) in admitted_List:
tempString += xkcd[i]
continue
else:
tempString += xkcd[i]
finalList.append(int(tempString))
tempString = ""
return (finalList)
```
that basically takes in (xkcd) a string of weights of roman numbers like '10010010010100511' and it should return me the list of weights like [100, 100, 100, 10, 100, 5, 1, 1] so that C C C XC V I I makes sense, of course the first 4 chars of the string make the number 1001 that in roman numbers means nothing so my number will be 100 and then the check should stop and begin a new number.
I tried the above algorithm.
Please excuse me if bad code or bad body question, I'm pretty new to python and stack overflow.
|
2022/10/26
|
[
"https://Stackoverflow.com/questions/74214700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18943770/"
] |
>
>
> ```
> nodejs test.js
>
> ```
>
>
>
>
> ```
> nodejs -v
> v10.19.0
>
> ```
>
>
You are running this with Node 10 which is beyond end of life and does not support ECMAScript modules (with provide `import`) except as an experimental feature locked behind a flag.
Use the other version of Node.js you have installed instead.
|
What worked for me:
1. Install **curl**:
`sudo apt install curl`
2. Install **NVM**:
`sudo curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash`
```
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm.
```
3. List all node versions:
`nvm list`
4. Select a node **version** to use
`nvm use v19.0.0`
5. Run the file using:
`node test.js`
|
74,214,700
|
i wrote this code:
```
admitted_List = [1, 5, 10, 50, 100, 500, 1000]
tempString = ""
finalList = []
for i in range(len(xkcd)-1):
if int(xkcd[i] + xkcd[i+1]) in admitted_List:
tempString += xkcd[i]
continue
else:
tempString += xkcd[i]
finalList.append(int(tempString))
tempString = ""
return (finalList)
```
that basically takes in (xkcd) a string of weights of roman numbers like '10010010010100511' and it should return me the list of weights like [100, 100, 100, 10, 100, 5, 1, 1] so that C C C XC V I I makes sense, of course the first 4 chars of the string make the number 1001 that in roman numbers means nothing so my number will be 100 and then the check should stop and begin a new number.
I tried the above algorithm.
Please excuse me if bad code or bad body question, I'm pretty new to python and stack overflow.
|
2022/10/26
|
[
"https://Stackoverflow.com/questions/74214700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18943770/"
] |
>
>
> ```
> nodejs test.js
>
> ```
>
>
>
>
> ```
> nodejs -v
> v10.19.0
>
> ```
>
>
You are running this with Node 10 which is beyond end of life and does not support ECMAScript modules (with provide `import`) except as an experimental feature locked behind a flag.
Use the other version of Node.js you have installed instead.
|
1. Make sure you're using at least Node@12.0.0
2. Change your run command from `node test.js` to `node test.js --input-type=module` (This will allow using `import` in your code)
See the docs: <https://nodejs.org/api/packages.html#--input-type-flag>
|
74,214,700
|
i wrote this code:
```
admitted_List = [1, 5, 10, 50, 100, 500, 1000]
tempString = ""
finalList = []
for i in range(len(xkcd)-1):
if int(xkcd[i] + xkcd[i+1]) in admitted_List:
tempString += xkcd[i]
continue
else:
tempString += xkcd[i]
finalList.append(int(tempString))
tempString = ""
return (finalList)
```
that basically takes in (xkcd) a string of weights of roman numbers like '10010010010100511' and it should return me the list of weights like [100, 100, 100, 10, 100, 5, 1, 1] so that C C C XC V I I makes sense, of course the first 4 chars of the string make the number 1001 that in roman numbers means nothing so my number will be 100 and then the check should stop and begin a new number.
I tried the above algorithm.
Please excuse me if bad code or bad body question, I'm pretty new to python and stack overflow.
|
2022/10/26
|
[
"https://Stackoverflow.com/questions/74214700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18943770/"
] |
1. Make sure you're using at least Node@12.0.0
2. Change your run command from `node test.js` to `node test.js --input-type=module` (This will allow using `import` in your code)
See the docs: <https://nodejs.org/api/packages.html#--input-type-flag>
|
What worked for me:
1. Install **curl**:
`sudo apt install curl`
2. Install **NVM**:
`sudo curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash`
```
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm.
```
3. List all node versions:
`nvm list`
4. Select a node **version** to use
`nvm use v19.0.0`
5. Run the file using:
`node test.js`
|
66,166,103
|
How do I turn these numbers into a list using python?
16 3 2 13 -> ["16","3","2","13"]
|
2021/02/12
|
[
"https://Stackoverflow.com/questions/66166103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15195153/"
] |
You can divide it by using [split](https://docs.python.org/3/library/stdtypes.html?highlight=split#str.split):
```
"16 3 2 13".split()
```
Output:
```
["16","3","2","13"]
```
|
```
a = '16 3 2 13'
b = ['']
print(type(b))
print(len(b))
j = 0
for i in range(len(a)):
if a[i] != ' ':
b[j] = b[j] + a[i]
else:
j = j+1
b.append('')
print(b)
```
|
66,166,103
|
How do I turn these numbers into a list using python?
16 3 2 13 -> ["16","3","2","13"]
|
2021/02/12
|
[
"https://Stackoverflow.com/questions/66166103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15195153/"
] |
If you just want to split by whitespaces.
```
data = '16 3 2 13'
print(data.split())
```
|
```
a = '16 3 2 13'
b = ['']
print(type(b))
print(len(b))
j = 0
for i in range(len(a)):
if a[i] != ' ':
b[j] = b[j] + a[i]
else:
j = j+1
b.append('')
print(b)
```
|
72,726,621
|
I have two lists.
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
```
If I look closely, L1 has `'not worry'` and `'good very'` which are exact reversed repetitions of `'worry not'` and `'very good'`.
I need to remove such reversed elements from the list. Similary in L2, `'happy be always'` is a reverse of `'always be happy'`, which is to be removed as well.
The final output I'm looking for is:
```
L1 = ['worry not', 'be happy', 'very good', 'full stop']
L2 = ['take into account', 'always be happy', 'stay safe friend']
```
I tried one solution
`[[max(zip(map(set, map(str.split, group)), group))[1]] for group in L1]`
But it is not giving the correct output.
Should I be writing different functions for bigrams and trigrams reverse repetition removal, or is there a pythonic way of doing this in a faster way,because I'll have to run this for about 10K+strings.
|
2022/06/23
|
[
"https://Stackoverflow.com/questions/72726621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6803114/"
] |
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
def solution(lst):
res = []
for item in lst:
if " ".join(item.split()[::-1]) not in res:
res.append(item)
return res
print(solution(L2))
```
|
This is a possible solution (the complexity is linear with respect to the number of strings):
```
from collections import defaultdict
from operator import itemgetter
d = defaultdict(list)
for s in L2:
d[max(s, reversed(s.split()))].append(s)
result = list(map(itemgetter(0), d.values()))
```
Here are the results:
```
['worry not', 'be happy', 'very good', 'full stop']
['take into account', 'always be happy', 'stay safe friend']
```
|
72,726,621
|
I have two lists.
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
```
If I look closely, L1 has `'not worry'` and `'good very'` which are exact reversed repetitions of `'worry not'` and `'very good'`.
I need to remove such reversed elements from the list. Similary in L2, `'happy be always'` is a reverse of `'always be happy'`, which is to be removed as well.
The final output I'm looking for is:
```
L1 = ['worry not', 'be happy', 'very good', 'full stop']
L2 = ['take into account', 'always be happy', 'stay safe friend']
```
I tried one solution
`[[max(zip(map(set, map(str.split, group)), group))[1]] for group in L1]`
But it is not giving the correct output.
Should I be writing different functions for bigrams and trigrams reverse repetition removal, or is there a pythonic way of doing this in a faster way,because I'll have to run this for about 10K+strings.
|
2022/06/23
|
[
"https://Stackoverflow.com/questions/72726621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6803114/"
] |
You can do it with list comprehensions if you iterate over the list from the end
```
lst = L1[::-1] # L2[::-1]
x = [s for i, s in enumerate(lst) if ' '.join(s.split()[::-1]) not in lst[i+1:]][::-1]
# L1: ['worry not', 'be happy', 'very good', 'full stop']
# L2: ['take into account', 'always be happy', 'stay safe friend']
```
|
You can use an index set and add both direct and reversed n-grams to it:
```
index = set()
res = []
for x in L1:
a = tuple(x.split())
b = tuple(reversed(a))
if a in index or b in index:
continue
index.add(a)
index.add(b)
res.append(x)
print(res)
```
|
72,726,621
|
I have two lists.
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
```
If I look closely, L1 has `'not worry'` and `'good very'` which are exact reversed repetitions of `'worry not'` and `'very good'`.
I need to remove such reversed elements from the list. Similary in L2, `'happy be always'` is a reverse of `'always be happy'`, which is to be removed as well.
The final output I'm looking for is:
```
L1 = ['worry not', 'be happy', 'very good', 'full stop']
L2 = ['take into account', 'always be happy', 'stay safe friend']
```
I tried one solution
`[[max(zip(map(set, map(str.split, group)), group))[1]] for group in L1]`
But it is not giving the correct output.
Should I be writing different functions for bigrams and trigrams reverse repetition removal, or is there a pythonic way of doing this in a faster way,because I'll have to run this for about 10K+strings.
|
2022/06/23
|
[
"https://Stackoverflow.com/questions/72726621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6803114/"
] |
You can do it with list comprehensions if you iterate over the list from the end
```
lst = L1[::-1] # L2[::-1]
x = [s for i, s in enumerate(lst) if ' '.join(s.split()[::-1]) not in lst[i+1:]][::-1]
# L1: ['worry not', 'be happy', 'very good', 'full stop']
# L2: ['take into account', 'always be happy', 'stay safe friend']
```
|
Using a set of tuples is the way to deal with this:
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
for list_ in L1, L2:
s = set()
for e in list_:
t = tuple(e.split())
if not t[::-1] in s:
s.add(t)
print([' '.join(e) for e in s])
```
**Output:**
```
['be happy', 'worry not', 'very good', 'full stop']
['always be happy', 'stay safe friend', 'take into account']
```
|
72,726,621
|
I have two lists.
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
```
If I look closely, L1 has `'not worry'` and `'good very'` which are exact reversed repetitions of `'worry not'` and `'very good'`.
I need to remove such reversed elements from the list. Similary in L2, `'happy be always'` is a reverse of `'always be happy'`, which is to be removed as well.
The final output I'm looking for is:
```
L1 = ['worry not', 'be happy', 'very good', 'full stop']
L2 = ['take into account', 'always be happy', 'stay safe friend']
```
I tried one solution
`[[max(zip(map(set, map(str.split, group)), group))[1]] for group in L1]`
But it is not giving the correct output.
Should I be writing different functions for bigrams and trigrams reverse repetition removal, or is there a pythonic way of doing this in a faster way,because I'll have to run this for about 10K+strings.
|
2022/06/23
|
[
"https://Stackoverflow.com/questions/72726621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6803114/"
] |
Using a set of tuples is the way to deal with this:
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
for list_ in L1, L2:
s = set()
for e in list_:
t = tuple(e.split())
if not t[::-1] in s:
s.add(t)
print([' '.join(e) for e in s])
```
**Output:**
```
['be happy', 'worry not', 'very good', 'full stop']
['always be happy', 'stay safe friend', 'take into account']
```
|
This is a possible solution (the complexity is linear with respect to the number of strings):
```
from collections import defaultdict
from operator import itemgetter
d = defaultdict(list)
for s in L2:
d[max(s, reversed(s.split()))].append(s)
result = list(map(itemgetter(0), d.values()))
```
Here are the results:
```
['worry not', 'be happy', 'very good', 'full stop']
['take into account', 'always be happy', 'stay safe friend']
```
|
72,726,621
|
I have two lists.
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
```
If I look closely, L1 has `'not worry'` and `'good very'` which are exact reversed repetitions of `'worry not'` and `'very good'`.
I need to remove such reversed elements from the list. Similary in L2, `'happy be always'` is a reverse of `'always be happy'`, which is to be removed as well.
The final output I'm looking for is:
```
L1 = ['worry not', 'be happy', 'very good', 'full stop']
L2 = ['take into account', 'always be happy', 'stay safe friend']
```
I tried one solution
`[[max(zip(map(set, map(str.split, group)), group))[1]] for group in L1]`
But it is not giving the correct output.
Should I be writing different functions for bigrams and trigrams reverse repetition removal, or is there a pythonic way of doing this in a faster way,because I'll have to run this for about 10K+strings.
|
2022/06/23
|
[
"https://Stackoverflow.com/questions/72726621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6803114/"
] |
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
def solution(lst):
res = []
for item in lst:
if " ".join(item.split()[::-1]) not in res:
res.append(item)
return res
print(solution(L2))
```
|
My solution consist on iterate foreach element in the list, transform that element in a list, sort it and compare with the next element making the same, transform it in a list and sort it, if the arrays are matching, remove this element.
Here is my code:
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams l
def remove_duplicates(L):
for idx_i, l_i in enumerate(L):
aux_i = l_i.split()
aux_i.sort()
for idx_j, l_j in enumerate(L[idx_i+1:]):
aux_j = l_j.split()
aux_j.sort()
if aux_i == aux_j:
L.pop(idx_i + idx_j + 1)
print(L)
remove_duplicates(L1)
remove_duplicates(L2)
```
The output is what you're looking for:
```
>>> remove_duplicates(L1)
['worry not', 'be happy', 'very good', 'full stop']
>>> remove_duplicates(L2)
['take into account', 'always be happy', 'stay safe friend']
```
Hope this works for you
|
72,726,621
|
I have two lists.
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
```
If I look closely, L1 has `'not worry'` and `'good very'` which are exact reversed repetitions of `'worry not'` and `'very good'`.
I need to remove such reversed elements from the list. Similary in L2, `'happy be always'` is a reverse of `'always be happy'`, which is to be removed as well.
The final output I'm looking for is:
```
L1 = ['worry not', 'be happy', 'very good', 'full stop']
L2 = ['take into account', 'always be happy', 'stay safe friend']
```
I tried one solution
`[[max(zip(map(set, map(str.split, group)), group))[1]] for group in L1]`
But it is not giving the correct output.
Should I be writing different functions for bigrams and trigrams reverse repetition removal, or is there a pythonic way of doing this in a faster way,because I'll have to run this for about 10K+strings.
|
2022/06/23
|
[
"https://Stackoverflow.com/questions/72726621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6803114/"
] |
You can do it with list comprehensions if you iterate over the list from the end
```
lst = L1[::-1] # L2[::-1]
x = [s for i, s in enumerate(lst) if ' '.join(s.split()[::-1]) not in lst[i+1:]][::-1]
# L1: ['worry not', 'be happy', 'very good', 'full stop']
# L2: ['take into account', 'always be happy', 'stay safe friend']
```
|
My solution consist on iterate foreach element in the list, transform that element in a list, sort it and compare with the next element making the same, transform it in a list and sort it, if the arrays are matching, remove this element.
Here is my code:
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams l
def remove_duplicates(L):
for idx_i, l_i in enumerate(L):
aux_i = l_i.split()
aux_i.sort()
for idx_j, l_j in enumerate(L[idx_i+1:]):
aux_j = l_j.split()
aux_j.sort()
if aux_i == aux_j:
L.pop(idx_i + idx_j + 1)
print(L)
remove_duplicates(L1)
remove_duplicates(L2)
```
The output is what you're looking for:
```
>>> remove_duplicates(L1)
['worry not', 'be happy', 'very good', 'full stop']
>>> remove_duplicates(L2)
['take into account', 'always be happy', 'stay safe friend']
```
Hope this works for you
|
72,726,621
|
I have two lists.
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
```
If I look closely, L1 has `'not worry'` and `'good very'` which are exact reversed repetitions of `'worry not'` and `'very good'`.
I need to remove such reversed elements from the list. Similary in L2, `'happy be always'` is a reverse of `'always be happy'`, which is to be removed as well.
The final output I'm looking for is:
```
L1 = ['worry not', 'be happy', 'very good', 'full stop']
L2 = ['take into account', 'always be happy', 'stay safe friend']
```
I tried one solution
`[[max(zip(map(set, map(str.split, group)), group))[1]] for group in L1]`
But it is not giving the correct output.
Should I be writing different functions for bigrams and trigrams reverse repetition removal, or is there a pythonic way of doing this in a faster way,because I'll have to run this for about 10K+strings.
|
2022/06/23
|
[
"https://Stackoverflow.com/questions/72726621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6803114/"
] |
You can do it with list comprehensions if you iterate over the list from the end
```
lst = L1[::-1] # L2[::-1]
x = [s for i, s in enumerate(lst) if ' '.join(s.split()[::-1]) not in lst[i+1:]][::-1]
# L1: ['worry not', 'be happy', 'very good', 'full stop']
# L2: ['take into account', 'always be happy', 'stay safe friend']
```
|
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
def solution(lst):
res = []
for item in lst:
if " ".join(item.split()[::-1]) not in res:
res.append(item)
return res
print(solution(L2))
```
|
72,726,621
|
I have two lists.
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
```
If I look closely, L1 has `'not worry'` and `'good very'` which are exact reversed repetitions of `'worry not'` and `'very good'`.
I need to remove such reversed elements from the list. Similary in L2, `'happy be always'` is a reverse of `'always be happy'`, which is to be removed as well.
The final output I'm looking for is:
```
L1 = ['worry not', 'be happy', 'very good', 'full stop']
L2 = ['take into account', 'always be happy', 'stay safe friend']
```
I tried one solution
`[[max(zip(map(set, map(str.split, group)), group))[1]] for group in L1]`
But it is not giving the correct output.
Should I be writing different functions for bigrams and trigrams reverse repetition removal, or is there a pythonic way of doing this in a faster way,because I'll have to run this for about 10K+strings.
|
2022/06/23
|
[
"https://Stackoverflow.com/questions/72726621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6803114/"
] |
You can do it with list comprehensions if you iterate over the list from the end
```
lst = L1[::-1] # L2[::-1]
x = [s for i, s in enumerate(lst) if ' '.join(s.split()[::-1]) not in lst[i+1:]][::-1]
# L1: ['worry not', 'be happy', 'very good', 'full stop']
# L2: ['take into account', 'always be happy', 'stay safe friend']
```
|
This is a possible solution (the complexity is linear with respect to the number of strings):
```
from collections import defaultdict
from operator import itemgetter
d = defaultdict(list)
for s in L2:
d[max(s, reversed(s.split()))].append(s)
result = list(map(itemgetter(0), d.values()))
```
Here are the results:
```
['worry not', 'be happy', 'very good', 'full stop']
['take into account', 'always be happy', 'stay safe friend']
```
|
72,726,621
|
I have two lists.
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
```
If I look closely, L1 has `'not worry'` and `'good very'` which are exact reversed repetitions of `'worry not'` and `'very good'`.
I need to remove such reversed elements from the list. Similary in L2, `'happy be always'` is a reverse of `'always be happy'`, which is to be removed as well.
The final output I'm looking for is:
```
L1 = ['worry not', 'be happy', 'very good', 'full stop']
L2 = ['take into account', 'always be happy', 'stay safe friend']
```
I tried one solution
`[[max(zip(map(set, map(str.split, group)), group))[1]] for group in L1]`
But it is not giving the correct output.
Should I be writing different functions for bigrams and trigrams reverse repetition removal, or is there a pythonic way of doing this in a faster way,because I'll have to run this for about 10K+strings.
|
2022/06/23
|
[
"https://Stackoverflow.com/questions/72726621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6803114/"
] |
Using a set of tuples is the way to deal with this:
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
for list_ in L1, L2:
s = set()
for e in list_:
t = tuple(e.split())
if not t[::-1] in s:
s.add(t)
print([' '.join(e) for e in s])
```
**Output:**
```
['be happy', 'worry not', 'very good', 'full stop']
['always be happy', 'stay safe friend', 'take into account']
```
|
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
def solution(lst):
res = []
for item in lst:
if " ".join(item.split()[::-1]) not in res:
res.append(item)
return res
print(solution(L2))
```
|
72,726,621
|
I have two lists.
```
L1 = ['worry not', 'be happy', 'very good', 'not worry', 'good very', 'full stop'] # bigrams list
L2 = ['take into account', 'always be happy', 'stay safe friend', 'happy be always'] #trigrams list
```
If I look closely, L1 has `'not worry'` and `'good very'` which are exact reversed repetitions of `'worry not'` and `'very good'`.
I need to remove such reversed elements from the list. Similary in L2, `'happy be always'` is a reverse of `'always be happy'`, which is to be removed as well.
The final output I'm looking for is:
```
L1 = ['worry not', 'be happy', 'very good', 'full stop']
L2 = ['take into account', 'always be happy', 'stay safe friend']
```
I tried one solution
`[[max(zip(map(set, map(str.split, group)), group))[1]] for group in L1]`
But it is not giving the correct output.
Should I be writing different functions for bigrams and trigrams reverse repetition removal, or is there a pythonic way of doing this in a faster way,because I'll have to run this for about 10K+strings.
|
2022/06/23
|
[
"https://Stackoverflow.com/questions/72726621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6803114/"
] |
You can use an index set and add both direct and reversed n-grams to it:
```
index = set()
res = []
for x in L1:
a = tuple(x.split())
b = tuple(reversed(a))
if a in index or b in index:
continue
index.add(a)
index.add(b)
res.append(x)
print(res)
```
|
This is a possible solution (the complexity is linear with respect to the number of strings):
```
from collections import defaultdict
from operator import itemgetter
d = defaultdict(list)
for s in L2:
d[max(s, reversed(s.split()))].append(s)
result = list(map(itemgetter(0), d.values()))
```
Here are the results:
```
['worry not', 'be happy', 'very good', 'full stop']
['take into account', 'always be happy', 'stay safe friend']
```
|
63,145,924
|
Let say I have something like this :
```
--module1
def called():
if caller.class.attrX == 1 : ...
--module2
class ABC:
attrX = 1
def method():
called()
```
I want to access caller Class-attribute ?
I know I have to use inspect somehow but can figure how exactly.
python3
|
2020/07/29
|
[
"https://Stackoverflow.com/questions/63145924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1019129/"
] |
The code works perfectly fine for me in python 3.7.3.
`The number is: 2825302`
`['28', '82', '253', '2530', '5302']`
this is the output I have received
|
I don't get the error. Better practice is to pass mutable objects as parameters to functions. Changed `find_ten_substring()` to take additional parameter
```
def find_sum(num_str):
sum1 = 0
for i in num_str:
sum1 += int(i)
return sum1
def find_ten_substring(num_str, dict1):
list1 = []
for i in range(2, len(num_str) + 1):
for j in range(0, i):
if (i != j):
x = num_str[j:i]
if (x in dict1):
if (dict1[x] == 10):
list1.append(x)
elif (x not in dict1):
y = find_sum(x)
if (y == 10):
dict1[x] = y
list1.append(x)
return list1
# Remove pass and write your logic here
return list1
dict1 = {}
num_str = "2825302"
print("The number is:", num_str)
result_list = find_ten_substring(num_str, dict1)
print(result_list, dict1)
```
|
1,223,927
|
I have django running through WSGI like this :
```
<VirtualHost *:80>
WSGIScriptAlias / /home/ptarjan/django/django.wsgi
WSGIDaemonProcess ptarjan processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup ptarjan
Alias /media /home/ptarjan/django/mysite/media/
</VirtualHost>
```
But if in python I do :
```
def handler(request) :
data = urllib2.urlopen("http://example.com/really/unresponsive/url").read()
```
the whole apache server hangs and is unresponsive with this backtrace
```
#0 0x00007ffe3602a570 in __read_nocancel () from /lib/libpthread.so.0
#1 0x00007ffe36251d1c in apr_file_read () from /usr/lib/libapr-1.so.0
#2 0x00007ffe364778b5 in ?? () from /usr/lib/libaprutil-1.so.0
#3 0x0000000000440ec2 in ?? ()
#4 0x00000000004412ae in ap_scan_script_header_err_core ()
#5 0x00007ffe2a2fe512 in ?? () from /usr/lib/apache2/modules/mod_wsgi.so
#6 0x00007ffe2a2f9bdd in ?? () from /usr/lib/apache2/modules/mod_wsgi.so
#7 0x000000000043b623 in ap_run_handler ()
#8 0x000000000043eb4f in ap_invoke_handler ()
#9 0x000000000044bbd8 in ap_process_request ()
#10 0x0000000000448cd8 in ?? ()
#11 0x0000000000442a13 in ap_run_process_connection ()
#12 0x000000000045017d in ?? ()
#13 0x00000000004504d4 in ?? ()
#14 0x00000000004510f6 in ap_mpm_run ()
#15 0x0000000000428425 in main ()
```
on Debian Apache 2.2.11-7.
Similarly, can we be protected against :
```
def handler(request) :
while (1) :
pass
```
In PHP, I would set time and memory limits.
|
2009/08/03
|
[
"https://Stackoverflow.com/questions/1223927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] |
It is not 'deadlock-timeout' you want as specified by another, that is for a very special purpose which will not help in this case.
As far as trying to use mod\_wsgi features, you instead want the 'inactivity-timeout' option for WSGIDaemonProcess directive.
Even then, this is not a complete solution. This is because the 'inactivity-timeout' option is specifically to detect whether all request processing by a daemon process has ceased, it is not a per request timeout. It only equates to a per request timeout if daemon processes are single threaded. As well as help to unstick a process, the option will also have side effect of restarting daemon process if no requests arrive at all in that time.
In short, there is no way at mod\_wsgi level to have per request timeouts, this is because there is no real way of interrupting a request, or thread, in Python.
What you really need to implement is a timeout on the HTTP request in your application code. Am not sure where it is up to and whether available already, but do a Google search for 'urllib2 socket timeout'.
|
If I understand well the question, you want to protect apache from locking up when running some random scripts from people. Well, if you're running untrusted code, I think you have other things to worry about that are worst than apache.
That said, you can use some configuration directives to adjust a *safer* environment. These two below are very useful:
* **WSGIApplicationGroup** - Sets which application group WSGI application belongs to. It allows to separate settings for each user - All WSGI applications within the same application group will execute within the context of the same Python sub interpreter of the process handling the request.
* **WSGIDaemonProcess** - Configures a distinct daemon process for running applications. The daemon processes can be run as a user different to that which the Apache child processes would normally be run as. This directive accepts a lot of useful options, I'll list some of them:
+ `user=name | user=#uid`, `group=name | group=#gid`:
Defines the UNIX user and groupname name or numeric user uid or group gid of the user/group that the daemon processes should be run as.
+ `stack-size=nnn`
The amount of virtual memory in bytes to be allocated for the stack corresponding to each thread created by mod\_wsgi in a daemon process.
+ `deadlock-timeout=sss`
Defines the maximum number of seconds allowed to pass before the daemon process is shutdown and restarted after a potential deadlock on the Python GIL has been detected. The default is 300 seconds.
You can read more about the configuration directives [here](http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives).
|
44,746,078
|
I have some exception handling code in `python` where two exceptions can be raised, the first one being a "superset" of the second one.
I.e. the following code summarizes what I need to do (and works fine)
```
try:
normal_execution_path()
except FirstError:
handle_first_error()
handle_second_error()
except SecondError:
handle_second_error()
```
But it requires me to abstract everything into independent functions for the code to remain clean and readable. I was hopping for some simpler syntax like:
```
try:
normal_execution_path()
except FirstError:
handle_first_error()
raise SecondError
except SecondError:
handle_second_error()
```
But this does not seem to work (`SecondError` does not get re-catched if it is raised inside this block). Is there anything doable in that direction though ?
|
2017/06/25
|
[
"https://Stackoverflow.com/questions/44746078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3246191/"
] |
If you wish to manually throw the second error to be handled, you can use nested try-catch blocks like these:
```
try:
normal_execution_path()
except FirstError:
try:
handle_first_error()
raise SecondError
except SecondError:
handle_second_error()
except SecondError:
handle_second_error()
```
|
Perhaps it is worth reviewing the code architecture. But for your particular case:
Create a generic class that handles this type of error. To inherit from it for the first and second error cases. Create a handler for this type of error. In the handler, check the first or second special case and process it with a waterfall.
```
class SupersetException(Exception):
pass
class FirstError(SupersetException):
pass
class SecondError(SupersetException):
pass
def normal_execution_path():
raise SecondError
def handle_superset_ex(state):
# Our waterfall
# We determine from whom the moment to start processing the exception.
if type(state) is FirstError:
handle_first_error()
# If not the first, the handler above will be skipped
handle_second_error()
try:
normal_execution_path()
except SupersetException as state:
handle_superset_ex(state)
```
Then just develop the idea.
|
39,902,759
|
I have a cube of size `N * N * N`, say `N=8`. Each dimension of the cube is discretised to 1, so that I have labelled points `(0,0,0), (0,0,1)..(N,N,N)`. At each labelled points, I would like to assign a random value, and thus produce an array which stores value at each vertex. For example `val[0,0,0]=1, val[0,0,1]=1.2 val[0,1,0]=1.3`, ...
How do I write a python code to acheive this?
|
2016/10/06
|
[
"https://Stackoverflow.com/questions/39902759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6700176/"
] |
You could simply generate lists of lists. While not in any way efficient, it would allow you to access your cube like `val[0][0][0]`.
```
arr = [[[] for _ in range(8)] for _ in range(8)]
arr[0][0].append(1)
```
|
For large matrices, look into using `numpy`. This is the problem that it's designed to solve
|
39,902,759
|
I have a cube of size `N * N * N`, say `N=8`. Each dimension of the cube is discretised to 1, so that I have labelled points `(0,0,0), (0,0,1)..(N,N,N)`. At each labelled points, I would like to assign a random value, and thus produce an array which stores value at each vertex. For example `val[0,0,0]=1, val[0,0,1]=1.2 val[0,1,0]=1.3`, ...
How do I write a python code to acheive this?
|
2016/10/06
|
[
"https://Stackoverflow.com/questions/39902759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6700176/"
] |
Did you mean this:
```
import numpy as np
n = 5
val = np.empty((n, n, n)) # Create an 3d array full of 0's
val[0,0,0] = 11
val[0,0,1] = 33
print(val[0, 0])
array([ 11., 33., 0., 0., 0.])
```
|
For large matrices, look into using `numpy`. This is the problem that it's designed to solve
|
53,480,515
|
Note: I am quite new to Python so the problem could be anything.
* Python: 3.6
* MySQL: 8
I have a MySQL database setup and can successfully query from it through Python, so I am sure my connection is OK. I can insert records inside MySQL Workbench, so I am fairly sure the DB is OK. However, when I run the following code, I get no error ("Done" does print, "error" does not print). However, the record is not being inserted.
```
import mysql.connector
cnx = mysql.connector.connect(user='furby',
password='something',host='127.0.0.1', database='mydb')
cursor = cnx.cursor()
document_root = ET.fromstring(semester.read('data'))
semester_name = document_root.get("Name")
print(semester_name)
query = ("SELECT semester_id
FROM StudentData.semesters
WHERE name = '%s'")
cursor.execute(query % semester_name)
cursor.fetchall()
print(cursor.rowcount)
if (cursor.rowcount == 0):
print("hi")
start_date = document_root.get("StartDate")
end_date = document_root.get("EndDate")
notes = document_root.get("Notes")
try:
query = "INSERT INTO StudentData.semesters
(name, start_date, end_date, notes) VALUES
('" + semester_name + "', '" + start_date + "',
'" + end_date + "', '" + notes + "')"
print(query)
cursor.execute(query)
except:
print("error")
print("done")
```
I had gotten lots of errors building up to this but suddenly, no errors. However, there must be some error, right?
What am I doing wrong here that would stop the record from being inserted without generating any kind of error?
**Edit**
After Douglas's answer, I changed to print the SQL insert statement and then copy and pasted it into SQL Workbench. Again, it does nothing running it through python but running in SQL Workbench does insert the record as expected.
|
2018/11/26
|
[
"https://Stackoverflow.com/questions/53480515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/546813/"
] |
I thin you should close your cursor. And your connection is autocommited?
Plese check it, and you should commit it!
|
I don't see anything obvious, though I have a suggestion.
The same way you created the query above before executing it,
do the same below and print it before execution so you can be sure
what you are executing. As a general rule I don't construct query
strings within the execute function. I don't see a close which might
have helped commit the data. I hope this helps.
|
36,490,093
|
Can anyone tell me how to use if statement in python for the difference between the two nos is 1..??
I have written like below and I am getting error
if num1 = num2 + 1:
what should be the content with if?
|
2016/04/08
|
[
"https://Stackoverflow.com/questions/36490093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6174977/"
] |
Your guess was mostly correct. It's not that the passing of references was a problem, is that after all the references got passed around, here, and there, and everywhere, the object that was referenced went out of scope and got destroyed, with the reference left hanging around. Using the reference at that point becomes undefined behavior.
When all is said and done, `_cycles` ends up being a reference to a function-scoped object from a function that has returned, thus destroying the object that was referenced. A simplified example of what you did:
```
int &foo()
{
int bar=4;
return bar;
}
void foobar()
{
int &blah=foo();
}
```
`foo()` returned a reference to a function-scoped object that was already destroyed by the time `foo()` returned, so the returned reference is referring to an object that went out of scope and got destroyed. Using the reference is now undefined behavior.
|
I changed the line:
const vector >& \_cycles;
to
const vector > \_cycles;
and everything worked fine!
|
36,490,093
|
Can anyone tell me how to use if statement in python for the difference between the two nos is 1..??
I have written like below and I am getting error
if num1 = num2 + 1:
what should be the content with if?
|
2016/04/08
|
[
"https://Stackoverflow.com/questions/36490093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6174977/"
] |
Your guess was mostly correct. It's not that the passing of references was a problem, is that after all the references got passed around, here, and there, and everywhere, the object that was referenced went out of scope and got destroyed, with the reference left hanging around. Using the reference at that point becomes undefined behavior.
When all is said and done, `_cycles` ends up being a reference to a function-scoped object from a function that has returned, thus destroying the object that was referenced. A simplified example of what you did:
```
int &foo()
{
int bar=4;
return bar;
}
void foobar()
{
int &blah=foo();
}
```
`foo()` returned a reference to a function-scoped object that was already destroyed by the time `foo()` returned, so the returned reference is referring to an object that went out of scope and got destroyed. Using the reference is now undefined behavior.
|
In foo() you're allocating a Permutation object in the current stack frame and then returning to your caller, destroying the frame(i.e. going out scope). You could instead allocate the new Permutation object on the heap and return the pointer, keeping in mind you'll want to free it at some point if done in something besides an example that exits immediately.
```
#include <vector>
#include <iostream>
#include <cassert>
using namespace std;
class Permutation
{
public:
Permutation(const vector<vector<int> >& cycles) : _cycles(cycles)
{}
static Permutation * foo()
{
vector<vector<int> > cycles = {{2,3}};
assert(cycles.front().size() == 2); // foo seems to create the correct thing locally
return new Permutation(cycles);
}
const vector<vector<int> >& _cycles;
};
int main()
{
vector<vector<int> > cycles = {{2,3}};
Permutation perm(cycles);
cout << perm._cycles.front().size() << endl; // outputs 2, as expected
cout << Permutation::foo()->_cycles.front().size() << endl; // outputs 6, seems like garbage to me
return 0;
}
```
|
36,490,093
|
Can anyone tell me how to use if statement in python for the difference between the two nos is 1..??
I have written like below and I am getting error
if num1 = num2 + 1:
what should be the content with if?
|
2016/04/08
|
[
"https://Stackoverflow.com/questions/36490093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6174977/"
] |
In foo() you're allocating a Permutation object in the current stack frame and then returning to your caller, destroying the frame(i.e. going out scope). You could instead allocate the new Permutation object on the heap and return the pointer, keeping in mind you'll want to free it at some point if done in something besides an example that exits immediately.
```
#include <vector>
#include <iostream>
#include <cassert>
using namespace std;
class Permutation
{
public:
Permutation(const vector<vector<int> >& cycles) : _cycles(cycles)
{}
static Permutation * foo()
{
vector<vector<int> > cycles = {{2,3}};
assert(cycles.front().size() == 2); // foo seems to create the correct thing locally
return new Permutation(cycles);
}
const vector<vector<int> >& _cycles;
};
int main()
{
vector<vector<int> > cycles = {{2,3}};
Permutation perm(cycles);
cout << perm._cycles.front().size() << endl; // outputs 2, as expected
cout << Permutation::foo()->_cycles.front().size() << endl; // outputs 6, seems like garbage to me
return 0;
}
```
|
I changed the line:
const vector >& \_cycles;
to
const vector > \_cycles;
and everything worked fine!
|
44,933,326
|
I am having problems connecting to my database through postgreSQL3 version 9.5. However, after running the code below:
```
import psycopg2 as p
con = p.connect("dbname ='dvdrental' user = 'myusername' host ='localhost' password ='somepassword'")
cur = con.cursor()
cur.execute("select * from title")
rows = cur.fetchall()
```
I get this error message:
```
psycopg2.OperationalError: could not connect to server: Connection refused
(0x0000274D/10061)
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
```
For background information, I accidentally downloaded the newest version of PostgreSQL, and it connected to the part 5432. I need it to connect to PostgreSQL port 5433. I do not know how to do that. How can I solve this DB problem? Is this a PostgreSQL problem or a python problem?
|
2017/07/05
|
[
"https://Stackoverflow.com/questions/44933326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7620397/"
] |
Check the listen adresses of postgres, using `netstat` (from the shell):
---
```
plasser@pisbak$ netstat -nl |grep 5432
tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN
tcp6 0 0 :::5432 :::* LISTEN
unix 2 [ ACC ] STREAM LISTENING 9002 /tmp/.s.PGSQL.5432
plasser@pisbak$
```
---
If nothing shows up, Postgres is *not* listening on port 5432.
|
what if you add `port = '5433'` to your `p.connect` line?
```
import psycopg2 as p
con = p.connect("dbname ='dvdrental' user = 'myusername' host ='localhost' password ='somepassword' port='5433'")
cur = con.cursor()
cur.execute("select * from title")
rows = cur.fetchall()
```
|
34,936,039
|
Env: Windows 10 Pro
I installed python 2.7.9 and using `pip` installed `robotframework` and `robotframework-selenium2library` and it all worked fine with no errors.
Then I was doing some research and found that unless there is a reason for me to use 2.x versions of Python, I should stick with 3.x versions. Since 3.4 support already exists for *selenium2library* (read somewhere), so I decided to switch to it.
I uninstalled `python 2.7.9` and installed `python 3.4` version. When I installed `robotframerwork`, I am getting the following:
>
> **C:\Users\username>**`pip install robotframework`
>
> Downloading/unpacking RobotFramework
> Running setup.py (path:C:\Users\username\AppData\Local\Temp\pip\_build\_username\RobotFramework\setup.py) egg\_info for package RobotFramework
> no previously-included directories found matching 'src\robot\htmldata\testdata'
> Installing collected packages: RobotFramework
> Running setup.py install for RobotFramework
> File "C:\Python34\Lib\site-packages\robot\running\timeouts\ironpython.py", line 57
> raise self.\_error[0], self.\_error[1], self.\_error[2]
> ^
> SyntaxError: invalid syntax
> File "C:\Python34\Lib\site-packages\robot\running\timeouts\jython.py", line 56
> raise self.\_error[0], self.\_error[1], self.\_error[2]
> ^
> SyntaxError: invalid syntax
> no previously-included directories found matching 'src\robot\htmldata\testdata'
> replacing interpreter in robot.bat and rebot.bat.
> Successfully installed RobotFramework
> Cleaning up...
>
>
>
When I did pip list I do see robotframework is installed.
```
C:\Users\username>pip list
pip (1.5.4)
robotframework (3.0)
setuptools (2.1)
```
Should I be concerned and stick to `Python 2.7.9`?
|
2016/01/21
|
[
"https://Stackoverflow.com/questions/34936039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4496252/"
] |
You need to assign `heroclass.toLowerCase();` to the original value of `heroclass`:
```
heroclass = heroclass.toLowerCase();
```
If you do not do this, the lowercase version of heroclass is not saved.
|
Put your loop in a labeled block:
```
myblock: {
while (true) {
//code
heroclass = heroclass.toLowerCase();
switch(heroclass)
{
case "slayer": A = "text";
break myblock;
//repeat with other cases
}
}
}
//goes to here when you say "break myblock;"
```
What you're doing is basically assigning the label `myblock` to the entire loop. When you say `break myblock` it breaks out of the entire section inside of the brackets.
NOTE: I would recommend this solution over the others because it doesn't depend on the magic value assigned by the `switch`; it works no matter what it is.
Also, I've added the part to make it case insensitive. Sorry about the confusion!
|
34,936,039
|
Env: Windows 10 Pro
I installed python 2.7.9 and using `pip` installed `robotframework` and `robotframework-selenium2library` and it all worked fine with no errors.
Then I was doing some research and found that unless there is a reason for me to use 2.x versions of Python, I should stick with 3.x versions. Since 3.4 support already exists for *selenium2library* (read somewhere), so I decided to switch to it.
I uninstalled `python 2.7.9` and installed `python 3.4` version. When I installed `robotframerwork`, I am getting the following:
>
> **C:\Users\username>**`pip install robotframework`
>
> Downloading/unpacking RobotFramework
> Running setup.py (path:C:\Users\username\AppData\Local\Temp\pip\_build\_username\RobotFramework\setup.py) egg\_info for package RobotFramework
> no previously-included directories found matching 'src\robot\htmldata\testdata'
> Installing collected packages: RobotFramework
> Running setup.py install for RobotFramework
> File "C:\Python34\Lib\site-packages\robot\running\timeouts\ironpython.py", line 57
> raise self.\_error[0], self.\_error[1], self.\_error[2]
> ^
> SyntaxError: invalid syntax
> File "C:\Python34\Lib\site-packages\robot\running\timeouts\jython.py", line 56
> raise self.\_error[0], self.\_error[1], self.\_error[2]
> ^
> SyntaxError: invalid syntax
> no previously-included directories found matching 'src\robot\htmldata\testdata'
> replacing interpreter in robot.bat and rebot.bat.
> Successfully installed RobotFramework
> Cleaning up...
>
>
>
When I did pip list I do see robotframework is installed.
```
C:\Users\username>pip list
pip (1.5.4)
robotframework (3.0)
setuptools (2.1)
```
Should I be concerned and stick to `Python 2.7.9`?
|
2016/01/21
|
[
"https://Stackoverflow.com/questions/34936039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4496252/"
] |
You need to assign `heroclass.toLowerCase();` to the original value of `heroclass`:
```
heroclass = heroclass.toLowerCase();
```
If you do not do this, the lowercase version of heroclass is not saved.
|
heroclass is of String type. String is immutable type of object, so you can't update this string. heroclass.toLowerCase() just return another String object with lower cased characters, so you need to reassign this string result to this variable:
```
heroclass = heroclass.toLowerCase();
```
|
34,936,039
|
Env: Windows 10 Pro
I installed python 2.7.9 and using `pip` installed `robotframework` and `robotframework-selenium2library` and it all worked fine with no errors.
Then I was doing some research and found that unless there is a reason for me to use 2.x versions of Python, I should stick with 3.x versions. Since 3.4 support already exists for *selenium2library* (read somewhere), so I decided to switch to it.
I uninstalled `python 2.7.9` and installed `python 3.4` version. When I installed `robotframerwork`, I am getting the following:
>
> **C:\Users\username>**`pip install robotframework`
>
> Downloading/unpacking RobotFramework
> Running setup.py (path:C:\Users\username\AppData\Local\Temp\pip\_build\_username\RobotFramework\setup.py) egg\_info for package RobotFramework
> no previously-included directories found matching 'src\robot\htmldata\testdata'
> Installing collected packages: RobotFramework
> Running setup.py install for RobotFramework
> File "C:\Python34\Lib\site-packages\robot\running\timeouts\ironpython.py", line 57
> raise self.\_error[0], self.\_error[1], self.\_error[2]
> ^
> SyntaxError: invalid syntax
> File "C:\Python34\Lib\site-packages\robot\running\timeouts\jython.py", line 56
> raise self.\_error[0], self.\_error[1], self.\_error[2]
> ^
> SyntaxError: invalid syntax
> no previously-included directories found matching 'src\robot\htmldata\testdata'
> replacing interpreter in robot.bat and rebot.bat.
> Successfully installed RobotFramework
> Cleaning up...
>
>
>
When I did pip list I do see robotframework is installed.
```
C:\Users\username>pip list
pip (1.5.4)
robotframework (3.0)
setuptools (2.1)
```
Should I be concerned and stick to `Python 2.7.9`?
|
2016/01/21
|
[
"https://Stackoverflow.com/questions/34936039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4496252/"
] |
You need to assign `heroclass.toLowerCase();` to the original value of `heroclass`:
```
heroclass = heroclass.toLowerCase();
```
If you do not do this, the lowercase version of heroclass is not saved.
|
Although coding wombat is right, i'm not a big fan of the way you did things here. A loop around your whole program like this isn't good practice. It's super clunky and will lead to many problems, not to mention you're making things more complicated for yourself. Ideally you'd want to put this class selection part of the program inside a method. Then if the user's input is invalid, simply call back the method recursively until you get correct input.
Ex.
case A: do this...
case B: do this...
case C: System.out.println("Not a valid input);, classSelector();
Also, when you use OOP you have the benefit of storing all the player's attributes inside an object, as well as making methods that manipulates those attributes. It will make your code a lot cleaner and easier to work with.
Ex.
Player1.heal(10);
|
34,936,039
|
Env: Windows 10 Pro
I installed python 2.7.9 and using `pip` installed `robotframework` and `robotframework-selenium2library` and it all worked fine with no errors.
Then I was doing some research and found that unless there is a reason for me to use 2.x versions of Python, I should stick with 3.x versions. Since 3.4 support already exists for *selenium2library* (read somewhere), so I decided to switch to it.
I uninstalled `python 2.7.9` and installed `python 3.4` version. When I installed `robotframerwork`, I am getting the following:
>
> **C:\Users\username>**`pip install robotframework`
>
> Downloading/unpacking RobotFramework
> Running setup.py (path:C:\Users\username\AppData\Local\Temp\pip\_build\_username\RobotFramework\setup.py) egg\_info for package RobotFramework
> no previously-included directories found matching 'src\robot\htmldata\testdata'
> Installing collected packages: RobotFramework
> Running setup.py install for RobotFramework
> File "C:\Python34\Lib\site-packages\robot\running\timeouts\ironpython.py", line 57
> raise self.\_error[0], self.\_error[1], self.\_error[2]
> ^
> SyntaxError: invalid syntax
> File "C:\Python34\Lib\site-packages\robot\running\timeouts\jython.py", line 56
> raise self.\_error[0], self.\_error[1], self.\_error[2]
> ^
> SyntaxError: invalid syntax
> no previously-included directories found matching 'src\robot\htmldata\testdata'
> replacing interpreter in robot.bat and rebot.bat.
> Successfully installed RobotFramework
> Cleaning up...
>
>
>
When I did pip list I do see robotframework is installed.
```
C:\Users\username>pip list
pip (1.5.4)
robotframework (3.0)
setuptools (2.1)
```
Should I be concerned and stick to `Python 2.7.9`?
|
2016/01/21
|
[
"https://Stackoverflow.com/questions/34936039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4496252/"
] |
Put your loop in a labeled block:
```
myblock: {
while (true) {
//code
heroclass = heroclass.toLowerCase();
switch(heroclass)
{
case "slayer": A = "text";
break myblock;
//repeat with other cases
}
}
}
//goes to here when you say "break myblock;"
```
What you're doing is basically assigning the label `myblock` to the entire loop. When you say `break myblock` it breaks out of the entire section inside of the brackets.
NOTE: I would recommend this solution over the others because it doesn't depend on the magic value assigned by the `switch`; it works no matter what it is.
Also, I've added the part to make it case insensitive. Sorry about the confusion!
|
Although coding wombat is right, i'm not a big fan of the way you did things here. A loop around your whole program like this isn't good practice. It's super clunky and will lead to many problems, not to mention you're making things more complicated for yourself. Ideally you'd want to put this class selection part of the program inside a method. Then if the user's input is invalid, simply call back the method recursively until you get correct input.
Ex.
case A: do this...
case B: do this...
case C: System.out.println("Not a valid input);, classSelector();
Also, when you use OOP you have the benefit of storing all the player's attributes inside an object, as well as making methods that manipulates those attributes. It will make your code a lot cleaner and easier to work with.
Ex.
Player1.heal(10);
|
34,936,039
|
Env: Windows 10 Pro
I installed python 2.7.9 and using `pip` installed `robotframework` and `robotframework-selenium2library` and it all worked fine with no errors.
Then I was doing some research and found that unless there is a reason for me to use 2.x versions of Python, I should stick with 3.x versions. Since 3.4 support already exists for *selenium2library* (read somewhere), so I decided to switch to it.
I uninstalled `python 2.7.9` and installed `python 3.4` version. When I installed `robotframerwork`, I am getting the following:
>
> **C:\Users\username>**`pip install robotframework`
>
> Downloading/unpacking RobotFramework
> Running setup.py (path:C:\Users\username\AppData\Local\Temp\pip\_build\_username\RobotFramework\setup.py) egg\_info for package RobotFramework
> no previously-included directories found matching 'src\robot\htmldata\testdata'
> Installing collected packages: RobotFramework
> Running setup.py install for RobotFramework
> File "C:\Python34\Lib\site-packages\robot\running\timeouts\ironpython.py", line 57
> raise self.\_error[0], self.\_error[1], self.\_error[2]
> ^
> SyntaxError: invalid syntax
> File "C:\Python34\Lib\site-packages\robot\running\timeouts\jython.py", line 56
> raise self.\_error[0], self.\_error[1], self.\_error[2]
> ^
> SyntaxError: invalid syntax
> no previously-included directories found matching 'src\robot\htmldata\testdata'
> replacing interpreter in robot.bat and rebot.bat.
> Successfully installed RobotFramework
> Cleaning up...
>
>
>
When I did pip list I do see robotframework is installed.
```
C:\Users\username>pip list
pip (1.5.4)
robotframework (3.0)
setuptools (2.1)
```
Should I be concerned and stick to `Python 2.7.9`?
|
2016/01/21
|
[
"https://Stackoverflow.com/questions/34936039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4496252/"
] |
heroclass is of String type. String is immutable type of object, so you can't update this string. heroclass.toLowerCase() just return another String object with lower cased characters, so you need to reassign this string result to this variable:
```
heroclass = heroclass.toLowerCase();
```
|
Although coding wombat is right, i'm not a big fan of the way you did things here. A loop around your whole program like this isn't good practice. It's super clunky and will lead to many problems, not to mention you're making things more complicated for yourself. Ideally you'd want to put this class selection part of the program inside a method. Then if the user's input is invalid, simply call back the method recursively until you get correct input.
Ex.
case A: do this...
case B: do this...
case C: System.out.println("Not a valid input);, classSelector();
Also, when you use OOP you have the benefit of storing all the player's attributes inside an object, as well as making methods that manipulates those attributes. It will make your code a lot cleaner and easier to work with.
Ex.
Player1.heal(10);
|
73,616,000
|
I want to hide this warning `UserWarning: pandas only support SQLAlchemy connectable(engine/connection) ordatabase string URI or sqlite3 DBAPI2 connectionother DBAPI2 objects are not tested, please consider using SQLAlchemy` and I've tried
```
import warnings
warnings.simplefilter(action='ignore', category=UserWarning)
import pandas
```
but the warning still shows.
My python script read data from databases. I'm using `pandas.read_sql` for SQL queries and `psycopg2` for db connections.
Also I'd like to know which line triggers the warning.
|
2022/09/06
|
[
"https://Stackoverflow.com/questions/73616000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8089312/"
] |
It seems I cannot disable the pandas warning, so I used SQLAlchemy (as the warning message wants me to do so) to wrap the psycopg2 connection.
I followed the instruction here: [SQLAlchemy for psycopg2 documentation](https://docs.sqlalchemy.org/en/14/dialects/postgresql.html#module-sqlalchemy.dialects.postgresql.psycopg2)
A simple example:
```
import psycopg2
import sqlalchemy
import pandas as pd
conn = sqlalchemy.create_engine(f"postgresql+psycopg2://{user}:{pw}@{host}:{port}/{db}")
query = "select count(*) from my_table"
pd.read_sql(query, conn)
```
The warning doesn't get triggered anymore.
|
The warnings that you're filtering right now are warnings of type `FutureWarning`. The warning that you're getting is of type `UserWarning`, so you should change the warning category to `UserWarning`. I hope [this](https://stackoverflow.com/a/71083448/8293793) answers your question regarding why pandas is giving that warning.
|
6,595,673
|
I'm trying to read a column oriented csv file into R as a data frame.
the first line of the file is like so:
`sDATE, sTIME,iGPS_ALT, ...`
and then each additional line is a measurement:
`4/10/2011,2:15,78, ...`
when I try to read this into R, via
`d = read.csv('filename')`
I get a duplicate row.names error since R thinks that the first column of the data is the row names, and since all of the measurements were taken on the same day, the values in the first column do not change.
If I put in `row.names = NULL` into the `read.csv` call, I get an extraneous column `d$row.names` which corresponds to the sDATE column, and everything is "shifted" one column down, so `d$sDATE` would have `2:15` in it, not `4/10/2011` as needed.
If I open my csv in excel, do nothing and then save it, everything's cool. I have to process hundreds of these, so manually saving in excel is not something I want. If there's something programmatically I can do to preprocess these csv's in python or otherwise, that would be great.
|
2011/07/06
|
[
"https://Stackoverflow.com/questions/6595673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3926/"
] |
`read.csv` only assumes there are any row names if there are less values in the header than in the other rows. So somehow you are either missing a column name or have an extra column you don't want.
|
You probably DO have an extra column.
But it probably arises from a stray formatted cell (or column of cells) that is actually empty, to the right of your data in your original spreadsheet.
Here is the key: Excel will save empty fields in the CSV file for any empty cells that are formatted in your sheet.
Here is why you probably have this problem: Because when you open the CSV file with Excel and re-save it the problem with R goes away.
What is happening: when you pull a CSV file back into Excel, it will subsequently ignore empty cells to the right or below your data (since CSV files have no formatting).
**Conclusion**: be careful saving formatted spreadsheets as CSV files for use with statistical packages. Stray formatting means stray fields in the CSV.
|
6,595,673
|
I'm trying to read a column oriented csv file into R as a data frame.
the first line of the file is like so:
`sDATE, sTIME,iGPS_ALT, ...`
and then each additional line is a measurement:
`4/10/2011,2:15,78, ...`
when I try to read this into R, via
`d = read.csv('filename')`
I get a duplicate row.names error since R thinks that the first column of the data is the row names, and since all of the measurements were taken on the same day, the values in the first column do not change.
If I put in `row.names = NULL` into the `read.csv` call, I get an extraneous column `d$row.names` which corresponds to the sDATE column, and everything is "shifted" one column down, so `d$sDATE` would have `2:15` in it, not `4/10/2011` as needed.
If I open my csv in excel, do nothing and then save it, everything's cool. I have to process hundreds of these, so manually saving in excel is not something I want. If there's something programmatically I can do to preprocess these csv's in python or otherwise, that would be great.
|
2011/07/06
|
[
"https://Stackoverflow.com/questions/6595673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3926/"
] |
`read.csv` only assumes there are any row names if there are less values in the header than in the other rows. So somehow you are either missing a column name or have an extra column you don't want.
|
One possible reason can be an extra comma at the end of lines after the header line.
Excel silently ignores them and removes while saving.
At least it was the case for me
|
6,595,673
|
I'm trying to read a column oriented csv file into R as a data frame.
the first line of the file is like so:
`sDATE, sTIME,iGPS_ALT, ...`
and then each additional line is a measurement:
`4/10/2011,2:15,78, ...`
when I try to read this into R, via
`d = read.csv('filename')`
I get a duplicate row.names error since R thinks that the first column of the data is the row names, and since all of the measurements were taken on the same day, the values in the first column do not change.
If I put in `row.names = NULL` into the `read.csv` call, I get an extraneous column `d$row.names` which corresponds to the sDATE column, and everything is "shifted" one column down, so `d$sDATE` would have `2:15` in it, not `4/10/2011` as needed.
If I open my csv in excel, do nothing and then save it, everything's cool. I have to process hundreds of these, so manually saving in excel is not something I want. If there's something programmatically I can do to preprocess these csv's in python or otherwise, that would be great.
|
2011/07/06
|
[
"https://Stackoverflow.com/questions/6595673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3926/"
] |
`read.csv` only assumes there are any row names if there are less values in the header than in the other rows. So somehow you are either missing a column name or have an extra column you don't want.
|
I faced the same issue. It got resolved by adding `header=TRUE` like below
```
tempdata <- read.csv("C:\\File.csv",header=TRUE)
```
The first column which was the date column got aligned properly.
|
6,595,673
|
I'm trying to read a column oriented csv file into R as a data frame.
the first line of the file is like so:
`sDATE, sTIME,iGPS_ALT, ...`
and then each additional line is a measurement:
`4/10/2011,2:15,78, ...`
when I try to read this into R, via
`d = read.csv('filename')`
I get a duplicate row.names error since R thinks that the first column of the data is the row names, and since all of the measurements were taken on the same day, the values in the first column do not change.
If I put in `row.names = NULL` into the `read.csv` call, I get an extraneous column `d$row.names` which corresponds to the sDATE column, and everything is "shifted" one column down, so `d$sDATE` would have `2:15` in it, not `4/10/2011` as needed.
If I open my csv in excel, do nothing and then save it, everything's cool. I have to process hundreds of these, so manually saving in excel is not something I want. If there's something programmatically I can do to preprocess these csv's in python or otherwise, that would be great.
|
2011/07/06
|
[
"https://Stackoverflow.com/questions/6595673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3926/"
] |
You probably DO have an extra column.
But it probably arises from a stray formatted cell (or column of cells) that is actually empty, to the right of your data in your original spreadsheet.
Here is the key: Excel will save empty fields in the CSV file for any empty cells that are formatted in your sheet.
Here is why you probably have this problem: Because when you open the CSV file with Excel and re-save it the problem with R goes away.
What is happening: when you pull a CSV file back into Excel, it will subsequently ignore empty cells to the right or below your data (since CSV files have no formatting).
**Conclusion**: be careful saving formatted spreadsheets as CSV files for use with statistical packages. Stray formatting means stray fields in the CSV.
|
One possible reason can be an extra comma at the end of lines after the header line.
Excel silently ignores them and removes while saving.
At least it was the case for me
|
6,595,673
|
I'm trying to read a column oriented csv file into R as a data frame.
the first line of the file is like so:
`sDATE, sTIME,iGPS_ALT, ...`
and then each additional line is a measurement:
`4/10/2011,2:15,78, ...`
when I try to read this into R, via
`d = read.csv('filename')`
I get a duplicate row.names error since R thinks that the first column of the data is the row names, and since all of the measurements were taken on the same day, the values in the first column do not change.
If I put in `row.names = NULL` into the `read.csv` call, I get an extraneous column `d$row.names` which corresponds to the sDATE column, and everything is "shifted" one column down, so `d$sDATE` would have `2:15` in it, not `4/10/2011` as needed.
If I open my csv in excel, do nothing and then save it, everything's cool. I have to process hundreds of these, so manually saving in excel is not something I want. If there's something programmatically I can do to preprocess these csv's in python or otherwise, that would be great.
|
2011/07/06
|
[
"https://Stackoverflow.com/questions/6595673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3926/"
] |
You probably DO have an extra column.
But it probably arises from a stray formatted cell (or column of cells) that is actually empty, to the right of your data in your original spreadsheet.
Here is the key: Excel will save empty fields in the CSV file for any empty cells that are formatted in your sheet.
Here is why you probably have this problem: Because when you open the CSV file with Excel and re-save it the problem with R goes away.
What is happening: when you pull a CSV file back into Excel, it will subsequently ignore empty cells to the right or below your data (since CSV files have no formatting).
**Conclusion**: be careful saving formatted spreadsheets as CSV files for use with statistical packages. Stray formatting means stray fields in the CSV.
|
I faced the same issue. It got resolved by adding `header=TRUE` like below
```
tempdata <- read.csv("C:\\File.csv",header=TRUE)
```
The first column which was the date column got aligned properly.
|
43,882,498
|
The following code is my pipeline for reading images and labels from files:
```
import tensorflow as tf
import numpy as np
import tflearn.data_utils
from tensorflow.python.framework import ops
from tensorflow.python.framework import dtypes
import sys
#process labels in the input file
def process_label(label):
info=np.zeros(6)
...
return info
def read_label_file(file):
f = open(file, "r")
filepaths = []
labels = []
lines = []
for line in f:
tokens = line.split(",")
filepaths.append([tokens[0],tokens[1],tokens[2]])
labels.append(process_label(tokens[3:]))
lines.append(line)
return filepaths, np.vstack(labels), lines
def get_data_batches(params):
# reading labels and file path
train_filepaths, train_labels, train_line = read_label_file(params.train_info)
test_filepaths, test_labels, test_line = read_label_file(params.test_info)
# convert string into tensors
train_images = ops.convert_to_tensor(train_filepaths)
train_labels = ops.convert_to_tensor(train_labels)
train_line = ops.convert_to_tensor(train_line)
test_images = ops.convert_to_tensor(test_filepaths)
test_labels = ops.convert_to_tensor(test_labels)
test_line = ops.convert_to_tensor(test_line)
# create input queues
train_input_queue = tf.train.slice_input_producer([train_images, train_labels, train_line], shuffle=params.shuffle)
test_input_queue = tf.train.slice_input_producer([test_images, test_labels, test_line],shuffle=False)
# process path and string tensor into an image and a label
train_image=None
for i in range(train_input_queue[0].get_shape()[0]):
file_content = tf.read_file(params.path_prefix+train_input_queue[0][i])
train_imageT = (tf.to_float(tf.image.decode_jpeg(file_content, channels=params.num_channels)))*(1.0/255)
train_imageT = tf.image.resize_images(train_imageT,[params.load_size[0],params.load_size[1]])
train_imageT = tf.random_crop(train_imageT,size=[params.crop_size[0],params.crop_size[1],params.num_channels])
train_imageT = tf.image.random_flip_up_down(train_imageT)
train_imageT = tf.image.per_image_standardization(train_imageT)
if(i==0):
train_image = train_imageT
else:
train_image = tf.concat([train_image, train_imageT], 2)
train_label = train_input_queue[1]
train_lineInfo = train_input_queue[2]
test_image=None
for i in range(test_input_queue[0].get_shape()[0]):
file_content = tf.read_file(params.path_prefix+test_input_queue[0][i])
test_imageT = tf.to_float(tf.image.decode_jpeg(file_content, channels=params.num_channels))*(1.0/255)
test_imageT = tf.image.resize_images(test_imageT,[params.load_size[0],params.load_size[1]])
test_imageT = tf.image.central_crop(test_imageT, (params.crop_size[0]+0.0)/params.load_size[0])
test_imageT = tf.image.per_image_standardization(test_imageT)
if(i==0):
test_image = test_imageT
else:
test_image = tf.concat([test_image, test_imageT],2)
test_label = test_input_queue[1]
test_lineInfo = test_input_queue[2]
# define tensor shape
train_image.set_shape([params.crop_size[0], params.crop_size[1], params.num_channels*3])
train_label.set_shape([66])
test_image.set_shape( [params.crop_size[0], params.crop_size[1], params.num_channels*3])
test_label.set_shape([66])
# collect batches of images before processing
train_image_batch, train_label_batch, train_lineno = tf.train.batch([train_image, train_label, train_lineInfo],batch_size=params.batch_size,num_threads=params.num_threads,allow_smaller_final_batch=True)
test_image_batch, test_label_batch, test_lineno = tf.train.batch([test_image, test_label, test_lineInfo],batch_size=params.test_size,num_threads=params.num_threads,allow_smaller_final_batch=True)
if(params.loadSlice=='all'):
return train_image_batch, train_label_batch, train_lineno, test_image_batch, test_label_batch, test_lineno
elif params.loadSlice=='train':
return train_image_batch, train_label_batch
elif params.loadSlice=='test':
return test_image_batch, test_label_batch
elif params.loadSlice=='train_info':
return train_image_batch, train_label_batch, train_lineno
elif params.loadSlice=='test_info':
return test_image_batch, test_label_batch, test_lineno
else:
return train_image_batch, train_label_batch, test_image_batch, test_label_batch
```
I want to use the same pipeline for loading the test data. The size of my test data is huge and I cannot load all of them at once.
I have 20453 test examples which is not an integer multiply of the batch size (here 512).
**How can I read all of my test examples via this pipeline one and only one time and then measure the performance on them?**
Currently, I am using this code for batching my test data and it does not work. It always read a full batch from the queue even when I set **allow\_smaller\_final\_batch** to True
```
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver.restore(sess,"checkpoints2/snapshot-16")
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
more = True
num_examples=0
while(more):
img_test, lbl_test, lbl_line=sess.run([test_image_batch,test_label_batch,test_lineno])
print(lbl_test.shape)
size=lbl_test.shape[0]
num_examples += size
if size<args.batch_size:
more = False
sess.close()
```
This is the code of my model:
```
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.normalization import local_response_normalization
from tflearn.layers.normalization import batch_normalization
from tflearn.layers.estimator import regression
from tflearn.activations import relu
def get_alexnet(x,num_output):
network = conv_2d(x, 64, 11, strides=4)
network = batch_normalization(network,epsilon=0.001)
network = relu (network)
network = max_pool_2d(network, 3, strides=2)
network = conv_2d(network, 192, 5)
network = batch_normalization(network,epsilon=0.001)
network = relu(network)
network = max_pool_2d(network, 3, strides=2)
network = conv_2d(network, 384, 3)
network = batch_normalization(network,epsilon=0.0001)
network = relu(network)
network = conv_2d(network, 256, 3)
network = batch_normalization(network,epsilon=0.001)
network = relu(network)
network = conv_2d(network, 256, 3)
network = batch_normalization(network,epsilon=0.001)
network = relu(network)
network = max_pool_2d(network, 3, strides=2)
network = fully_connected(network, 4096)
network = batch_normalization(network,epsilon=0.001)
network = relu(network)
network = dropout(network, 0.5)
network = fully_connected(network, 4096)
network = batch_normalization(network,epsilon=0.001)
network = relu(network)
network = dropout(network, 0.5)
network1 = fully_connected(network, num_output)
network2 = fully_connected(network, 12)
network3 = fully_connected(network,6)
return network1,network2,network3
```
|
2017/05/10
|
[
"https://Stackoverflow.com/questions/43882498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332289/"
] |
`tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)` is called by the table view each time it needs a new cell.
If only 12 cells are visible at a time then the table view initially needs only 12 cells so will ask for only 12 cells. You'd have to scroll before it would need to ask for more. It won't request cells until it needs them.
|
So interestingly, even though the table is displaying correctly, the printout only reaches 12, and that happens regardless of how many cells you scroll to. Is that what you are finding? This is because you have 12 rows in a view, and the cells are reused, so you are not creating more cells but you are just reusing the 12 that you already have.
|
23,271,575
|
I'm trying to get text to display as bold, or in colors, or possibly in italics, in ipython's qtconsole.
I found this link: [How do I print bold text in Python?](https://stackoverflow.com/questions/8924173/python-print-bold-text), and used the first and second answers, but in qtconsole, only the underlining option works.
I try:
`print '\033[1m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
(No boldface). The colors don't work either. But:
`print '\033[4m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
With underlining.
This is only in the qtconsole. Running ipython just in the terminal, it works to do boldface and color in this way.
There were other options suggested in that link and another, [Print in terminal with colors using Python?](https://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python), linked from it, but they all seem more complex, and to use more elaborate packages, than seems necessary for what I want to do, which is simply to get qtconsole to display like the ordinary terminal does.
Does anyone know what's going on? Is this simply a limitation of the qtconsole?
|
2014/04/24
|
[
"https://Stackoverflow.com/questions/23271575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3566002/"
] |
Those are ANSI escapes, special sequences of characters which terminals process to switch font styles. The Qt console interprets some of them, but not all of the ones that serious terminals do. This sequence works to print in red, for instance:
```
print('\x1b[1;31m'+'Hello world'+'\x1b[0m')
```
However, if you're trying to write a cross platform application, be aware that the Windows command prompt doesn't handle these codes. Some of the more complex packages can process them to produce similar effects on Windows.
The Qt console can also display simple HTML, like this:
```
from IPython.display import HTML
HTML("<i>Italic text</i>")
```
But of course, HTML doesn't work in regular terminals.
|
If you mean the body text of the iPython notebook (Markdowns), you can put 2 underline characters directly before and after your text to make it **BOLD**:
`__BOLD TEXT__` => **BOLD TEXT**
if you put a backslash before that, it will be counteracted:
`\__BOLD TEXT__` => \_\_BOLD TEXT\_\_
|
23,271,575
|
I'm trying to get text to display as bold, or in colors, or possibly in italics, in ipython's qtconsole.
I found this link: [How do I print bold text in Python?](https://stackoverflow.com/questions/8924173/python-print-bold-text), and used the first and second answers, but in qtconsole, only the underlining option works.
I try:
`print '\033[1m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
(No boldface). The colors don't work either. But:
`print '\033[4m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
With underlining.
This is only in the qtconsole. Running ipython just in the terminal, it works to do boldface and color in this way.
There were other options suggested in that link and another, [Print in terminal with colors using Python?](https://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python), linked from it, but they all seem more complex, and to use more elaborate packages, than seems necessary for what I want to do, which is simply to get qtconsole to display like the ordinary terminal does.
Does anyone know what's going on? Is this simply a limitation of the qtconsole?
|
2014/04/24
|
[
"https://Stackoverflow.com/questions/23271575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3566002/"
] |
Those are ANSI escapes, special sequences of characters which terminals process to switch font styles. The Qt console interprets some of them, but not all of the ones that serious terminals do. This sequence works to print in red, for instance:
```
print('\x1b[1;31m'+'Hello world'+'\x1b[0m')
```
However, if you're trying to write a cross platform application, be aware that the Windows command prompt doesn't handle these codes. Some of the more complex packages can process them to produce similar effects on Windows.
The Qt console can also display simple HTML, like this:
```
from IPython.display import HTML
HTML("<i>Italic text</i>")
```
But of course, HTML doesn't work in regular terminals.
|
Few more ways you can tweak around (I tried in iPython Notebook, not sure about other)..
```
**BOLD TEXT**
```
Above will produce bold text: **BOLD TEXT**
```
*__BOLD TEXT__*
```
will produce bold and italic text: ***BOLD TEXT***
|
23,271,575
|
I'm trying to get text to display as bold, or in colors, or possibly in italics, in ipython's qtconsole.
I found this link: [How do I print bold text in Python?](https://stackoverflow.com/questions/8924173/python-print-bold-text), and used the first and second answers, but in qtconsole, only the underlining option works.
I try:
`print '\033[1m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
(No boldface). The colors don't work either. But:
`print '\033[4m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
With underlining.
This is only in the qtconsole. Running ipython just in the terminal, it works to do boldface and color in this way.
There were other options suggested in that link and another, [Print in terminal with colors using Python?](https://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python), linked from it, but they all seem more complex, and to use more elaborate packages, than seems necessary for what I want to do, which is simply to get qtconsole to display like the ordinary terminal does.
Does anyone know what's going on? Is this simply a limitation of the qtconsole?
|
2014/04/24
|
[
"https://Stackoverflow.com/questions/23271575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3566002/"
] |
In Jupyter Notebooks, one clean way of solving this problem is using markdown:
```
from IPython.display import Markdown, display
def printmd(string):
display(Markdown(string))
```
And then do something like:
```
printmd("**bold text**")
```
Of course, this is great for bold, italics, etc., but markdown itself does not implement color. However, you can place html in your markdown, and get something like this:
```
printmd("<span style='color:red'>Red text</span>")
```
You could also wrap this in the `printmd` function :
```
def printmd(string, color=None):
colorstr = "<span style='color:{}'>{}</span>".format(color, string)
display(Markdown(colorstr))
```
And then do cool things like
```
printmd("**bold and blue**", color="blue")
```
For the colors, you can use the hexadecimal notation too (eg. `color = "#00FF00"` for green)
To clarify, although we use markdown, this is a *code* cell: you can do things like:
```
for c in ('green', 'blue', 'red', 'yellow'):
printmd("Writing in {}".format(c), color=c)
```
Of course, a drawback of this method is the reliance on being within a Jupyter notebook.
|
Those are ANSI escapes, special sequences of characters which terminals process to switch font styles. The Qt console interprets some of them, but not all of the ones that serious terminals do. This sequence works to print in red, for instance:
```
print('\x1b[1;31m'+'Hello world'+'\x1b[0m')
```
However, if you're trying to write a cross platform application, be aware that the Windows command prompt doesn't handle these codes. Some of the more complex packages can process them to produce similar effects on Windows.
The Qt console can also display simple HTML, like this:
```
from IPython.display import HTML
HTML("<i>Italic text</i>")
```
But of course, HTML doesn't work in regular terminals.
|
23,271,575
|
I'm trying to get text to display as bold, or in colors, or possibly in italics, in ipython's qtconsole.
I found this link: [How do I print bold text in Python?](https://stackoverflow.com/questions/8924173/python-print-bold-text), and used the first and second answers, but in qtconsole, only the underlining option works.
I try:
`print '\033[1m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
(No boldface). The colors don't work either. But:
`print '\033[4m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
With underlining.
This is only in the qtconsole. Running ipython just in the terminal, it works to do boldface and color in this way.
There were other options suggested in that link and another, [Print in terminal with colors using Python?](https://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python), linked from it, but they all seem more complex, and to use more elaborate packages, than seems necessary for what I want to do, which is simply to get qtconsole to display like the ordinary terminal does.
Does anyone know what's going on? Is this simply a limitation of the qtconsole?
|
2014/04/24
|
[
"https://Stackoverflow.com/questions/23271575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3566002/"
] |
In Jupyter Notebooks, one clean way of solving this problem is using markdown:
```
from IPython.display import Markdown, display
def printmd(string):
display(Markdown(string))
```
And then do something like:
```
printmd("**bold text**")
```
Of course, this is great for bold, italics, etc., but markdown itself does not implement color. However, you can place html in your markdown, and get something like this:
```
printmd("<span style='color:red'>Red text</span>")
```
You could also wrap this in the `printmd` function :
```
def printmd(string, color=None):
colorstr = "<span style='color:{}'>{}</span>".format(color, string)
display(Markdown(colorstr))
```
And then do cool things like
```
printmd("**bold and blue**", color="blue")
```
For the colors, you can use the hexadecimal notation too (eg. `color = "#00FF00"` for green)
To clarify, although we use markdown, this is a *code* cell: you can do things like:
```
for c in ('green', 'blue', 'red', 'yellow'):
printmd("Writing in {}".format(c), color=c)
```
Of course, a drawback of this method is the reliance on being within a Jupyter notebook.
|
If you mean the body text of the iPython notebook (Markdowns), you can put 2 underline characters directly before and after your text to make it **BOLD**:
`__BOLD TEXT__` => **BOLD TEXT**
if you put a backslash before that, it will be counteracted:
`\__BOLD TEXT__` => \_\_BOLD TEXT\_\_
|
23,271,575
|
I'm trying to get text to display as bold, or in colors, or possibly in italics, in ipython's qtconsole.
I found this link: [How do I print bold text in Python?](https://stackoverflow.com/questions/8924173/python-print-bold-text), and used the first and second answers, but in qtconsole, only the underlining option works.
I try:
`print '\033[1m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
(No boldface). The colors don't work either. But:
`print '\033[4m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
With underlining.
This is only in the qtconsole. Running ipython just in the terminal, it works to do boldface and color in this way.
There were other options suggested in that link and another, [Print in terminal with colors using Python?](https://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python), linked from it, but they all seem more complex, and to use more elaborate packages, than seems necessary for what I want to do, which is simply to get qtconsole to display like the ordinary terminal does.
Does anyone know what's going on? Is this simply a limitation of the qtconsole?
|
2014/04/24
|
[
"https://Stackoverflow.com/questions/23271575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3566002/"
] |
I would like to complete the previous incomplete answer.
Way more complex and fun things can be done without importing additional packages. e.g.
```
print('\x1b[1;03;31;46m'+'Hello'+ '\x1b[0;4;30;42m' + ' world' '\x1b[0m')
```
i.e.:
Open with:
```
'\x1b[XX;YY;ZZm'
```
Close with:
```
'\x1b[0m'
```
Where XX, YY and ZZ are numbers from:
<https://en.wikipedia.org/wiki/ANSI_escape_code>
It should be noted that it is very much dependant on what you use as a console to see what works.
Working for me are combinations of the following:
**Text styling**
* 1 Increased intensity (it operates on highlight and text simultaneously in my case)
* 3 Itallic
* 4 Underline
**Text colors**
* 30 Black text
* 31 Dark Red text
* 32 Dark Green text
* 33 Red text
* 34 Dark blue text
* 35 Purple text
* 36 Blue text
* 37 Gray text
**Bright text colors**
* 1;30 Gray text (Bright black)
* 1;31 Orange text (Bright red)
* 1;32 Bright Green text
* 1;33 Bright Yellow text
* 1;34 Bright Blue text
* 1;35 Bright Purple text
* 1;36 Bright Cyan text
* 1;37 White text (Bright
gray)
**Background colors (i.e. highlights)**
* 40 Black highlight
* 41 Dark Red highlight
* 42 Dark Green highlight
* 43 Red highlight
* 44 Dark blue highlight
* 45 Purple highlight
* 46 Blue highlight
* 47 Gray highlight
Note that 1;42 etc. also works similarly
Tested on windows 7, python 3.6, IPython console, in spyder 3.2.3 this works for me
|
If you mean the body text of the iPython notebook (Markdowns), you can put 2 underline characters directly before and after your text to make it **BOLD**:
`__BOLD TEXT__` => **BOLD TEXT**
if you put a backslash before that, it will be counteracted:
`\__BOLD TEXT__` => \_\_BOLD TEXT\_\_
|
23,271,575
|
I'm trying to get text to display as bold, or in colors, or possibly in italics, in ipython's qtconsole.
I found this link: [How do I print bold text in Python?](https://stackoverflow.com/questions/8924173/python-print-bold-text), and used the first and second answers, but in qtconsole, only the underlining option works.
I try:
`print '\033[1m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
(No boldface). The colors don't work either. But:
`print '\033[4m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
With underlining.
This is only in the qtconsole. Running ipython just in the terminal, it works to do boldface and color in this way.
There were other options suggested in that link and another, [Print in terminal with colors using Python?](https://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python), linked from it, but they all seem more complex, and to use more elaborate packages, than seems necessary for what I want to do, which is simply to get qtconsole to display like the ordinary terminal does.
Does anyone know what's going on? Is this simply a limitation of the qtconsole?
|
2014/04/24
|
[
"https://Stackoverflow.com/questions/23271575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3566002/"
] |
In Jupyter Notebooks, one clean way of solving this problem is using markdown:
```
from IPython.display import Markdown, display
def printmd(string):
display(Markdown(string))
```
And then do something like:
```
printmd("**bold text**")
```
Of course, this is great for bold, italics, etc., but markdown itself does not implement color. However, you can place html in your markdown, and get something like this:
```
printmd("<span style='color:red'>Red text</span>")
```
You could also wrap this in the `printmd` function :
```
def printmd(string, color=None):
colorstr = "<span style='color:{}'>{}</span>".format(color, string)
display(Markdown(colorstr))
```
And then do cool things like
```
printmd("**bold and blue**", color="blue")
```
For the colors, you can use the hexadecimal notation too (eg. `color = "#00FF00"` for green)
To clarify, although we use markdown, this is a *code* cell: you can do things like:
```
for c in ('green', 'blue', 'red', 'yellow'):
printmd("Writing in {}".format(c), color=c)
```
Of course, a drawback of this method is the reliance on being within a Jupyter notebook.
|
Few more ways you can tweak around (I tried in iPython Notebook, not sure about other)..
```
**BOLD TEXT**
```
Above will produce bold text: **BOLD TEXT**
```
*__BOLD TEXT__*
```
will produce bold and italic text: ***BOLD TEXT***
|
23,271,575
|
I'm trying to get text to display as bold, or in colors, or possibly in italics, in ipython's qtconsole.
I found this link: [How do I print bold text in Python?](https://stackoverflow.com/questions/8924173/python-print-bold-text), and used the first and second answers, but in qtconsole, only the underlining option works.
I try:
`print '\033[1m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
(No boldface). The colors don't work either. But:
`print '\033[4m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
With underlining.
This is only in the qtconsole. Running ipython just in the terminal, it works to do boldface and color in this way.
There were other options suggested in that link and another, [Print in terminal with colors using Python?](https://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python), linked from it, but they all seem more complex, and to use more elaborate packages, than seems necessary for what I want to do, which is simply to get qtconsole to display like the ordinary terminal does.
Does anyone know what's going on? Is this simply a limitation of the qtconsole?
|
2014/04/24
|
[
"https://Stackoverflow.com/questions/23271575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3566002/"
] |
I would like to complete the previous incomplete answer.
Way more complex and fun things can be done without importing additional packages. e.g.
```
print('\x1b[1;03;31;46m'+'Hello'+ '\x1b[0;4;30;42m' + ' world' '\x1b[0m')
```
i.e.:
Open with:
```
'\x1b[XX;YY;ZZm'
```
Close with:
```
'\x1b[0m'
```
Where XX, YY and ZZ are numbers from:
<https://en.wikipedia.org/wiki/ANSI_escape_code>
It should be noted that it is very much dependant on what you use as a console to see what works.
Working for me are combinations of the following:
**Text styling**
* 1 Increased intensity (it operates on highlight and text simultaneously in my case)
* 3 Itallic
* 4 Underline
**Text colors**
* 30 Black text
* 31 Dark Red text
* 32 Dark Green text
* 33 Red text
* 34 Dark blue text
* 35 Purple text
* 36 Blue text
* 37 Gray text
**Bright text colors**
* 1;30 Gray text (Bright black)
* 1;31 Orange text (Bright red)
* 1;32 Bright Green text
* 1;33 Bright Yellow text
* 1;34 Bright Blue text
* 1;35 Bright Purple text
* 1;36 Bright Cyan text
* 1;37 White text (Bright
gray)
**Background colors (i.e. highlights)**
* 40 Black highlight
* 41 Dark Red highlight
* 42 Dark Green highlight
* 43 Red highlight
* 44 Dark blue highlight
* 45 Purple highlight
* 46 Blue highlight
* 47 Gray highlight
Note that 1;42 etc. also works similarly
Tested on windows 7, python 3.6, IPython console, in spyder 3.2.3 this works for me
|
Few more ways you can tweak around (I tried in iPython Notebook, not sure about other)..
```
**BOLD TEXT**
```
Above will produce bold text: **BOLD TEXT**
```
*__BOLD TEXT__*
```
will produce bold and italic text: ***BOLD TEXT***
|
23,271,575
|
I'm trying to get text to display as bold, or in colors, or possibly in italics, in ipython's qtconsole.
I found this link: [How do I print bold text in Python?](https://stackoverflow.com/questions/8924173/python-print-bold-text), and used the first and second answers, but in qtconsole, only the underlining option works.
I try:
`print '\033[1m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
(No boldface). The colors don't work either. But:
`print '\033[4m' + 'Hello World!' + '\033[0m'`
And get:
`Hello World!`
With underlining.
This is only in the qtconsole. Running ipython just in the terminal, it works to do boldface and color in this way.
There were other options suggested in that link and another, [Print in terminal with colors using Python?](https://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python), linked from it, but they all seem more complex, and to use more elaborate packages, than seems necessary for what I want to do, which is simply to get qtconsole to display like the ordinary terminal does.
Does anyone know what's going on? Is this simply a limitation of the qtconsole?
|
2014/04/24
|
[
"https://Stackoverflow.com/questions/23271575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3566002/"
] |
In Jupyter Notebooks, one clean way of solving this problem is using markdown:
```
from IPython.display import Markdown, display
def printmd(string):
display(Markdown(string))
```
And then do something like:
```
printmd("**bold text**")
```
Of course, this is great for bold, italics, etc., but markdown itself does not implement color. However, you can place html in your markdown, and get something like this:
```
printmd("<span style='color:red'>Red text</span>")
```
You could also wrap this in the `printmd` function :
```
def printmd(string, color=None):
colorstr = "<span style='color:{}'>{}</span>".format(color, string)
display(Markdown(colorstr))
```
And then do cool things like
```
printmd("**bold and blue**", color="blue")
```
For the colors, you can use the hexadecimal notation too (eg. `color = "#00FF00"` for green)
To clarify, although we use markdown, this is a *code* cell: you can do things like:
```
for c in ('green', 'blue', 'red', 'yellow'):
printmd("Writing in {}".format(c), color=c)
```
Of course, a drawback of this method is the reliance on being within a Jupyter notebook.
|
I would like to complete the previous incomplete answer.
Way more complex and fun things can be done without importing additional packages. e.g.
```
print('\x1b[1;03;31;46m'+'Hello'+ '\x1b[0;4;30;42m' + ' world' '\x1b[0m')
```
i.e.:
Open with:
```
'\x1b[XX;YY;ZZm'
```
Close with:
```
'\x1b[0m'
```
Where XX, YY and ZZ are numbers from:
<https://en.wikipedia.org/wiki/ANSI_escape_code>
It should be noted that it is very much dependant on what you use as a console to see what works.
Working for me are combinations of the following:
**Text styling**
* 1 Increased intensity (it operates on highlight and text simultaneously in my case)
* 3 Itallic
* 4 Underline
**Text colors**
* 30 Black text
* 31 Dark Red text
* 32 Dark Green text
* 33 Red text
* 34 Dark blue text
* 35 Purple text
* 36 Blue text
* 37 Gray text
**Bright text colors**
* 1;30 Gray text (Bright black)
* 1;31 Orange text (Bright red)
* 1;32 Bright Green text
* 1;33 Bright Yellow text
* 1;34 Bright Blue text
* 1;35 Bright Purple text
* 1;36 Bright Cyan text
* 1;37 White text (Bright
gray)
**Background colors (i.e. highlights)**
* 40 Black highlight
* 41 Dark Red highlight
* 42 Dark Green highlight
* 43 Red highlight
* 44 Dark blue highlight
* 45 Purple highlight
* 46 Blue highlight
* 47 Gray highlight
Note that 1;42 etc. also works similarly
Tested on windows 7, python 3.6, IPython console, in spyder 3.2.3 this works for me
|
17,128,878
|
I was trying to install `autoclose.vim` to Vim. I noticed I didn't have a `~/.vim/plugin` folder, so I accidentally made a `~/.vim/plugins` folder (notice the extra 's' in plugins). I then added `au FileType python set rtp += ~/.vim/plugins` to my .vimrc, because from what I've read, that will allow me to automatically source the scripts in that folder.
The plugin didn't load for me until I realized my mistake and took out the extra 's' from 'plugins'. I'm confused because this new path isn't even defined in my runtime path. I'm basically wondering why the plugin loaded when I had it in `~/.vim/plugin` but not in `~/.vim/plugins`?
|
2013/06/15
|
[
"https://Stackoverflow.com/questions/17128878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2467761/"
] |
[:help load-plugins](http://vimdoc.sourceforge.net/htmldoc/starting.html#load-plugins) outlines how plugins are loaded.
Adding a folder to your `rtp` alone does not suffice; it must have a `plugin` subdirectory. For example, given `:set rtp+=/tmp/foo`, a file `/tmp/foo/plugin/bar.vim` would be detected and loaded, but neither `/tmp/foo/plugins/bar.vim` nor `/tmp/foo/bar.vim` would be.
|
You are on the right track with `set rtp+=...` but there's a bit more to it (`rtp` is non-recursive, help indexing, many corner cases) than what meets the eye so it is not a very good idea to do it by yourself. Unless you are ready for a months-long drop in productivity.
If you want to store all your plugins in a special directory you should use a proper `runtimepath`/plugin-management solution. I suggest [Pathogen](http://www.vim.org/scripts/script.php?script_id=2332) (`rtp`-manager) or [Vundle](http://www.vim.org/scripts/script.php?script_id=3458) (plugin-manager) but there are many others.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.