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
41,883,254
I am trying to process a form in django/python using the following code. --- home.html: ```html <form action="{% url 'home:submit' %}" method='post'> ``` --- views.py: ```py def submit(request): a = request.POST(['initial']) return render(request, 'home/home.html', { 'error_message': "returned" }) ``` --- urls.py: ```py from django.conf.urls import url from . import views urlpatterns = [ url(r'^submit/$', views.submit, name='submit') ] ``` when I try to run it in a browser I get the error: `NoReverseMatch at /home/ u'home' is not a registered namespace` and another error message indicating a problem with the form.
2017/01/26
[ "https://Stackoverflow.com/questions/41883254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7169431/" ]
For Django 3.0, if you're handling your urls within the app and using `include` with `path`, in your `project/urls.py`: ``` urlpatterns = [ path(os.getenv('ADMIN_PATH'), admin.site.urls), path('', include('my_simple_blog.urls', namespace='my_simple_blog')), path('account/', include('account.urls', namespace='account')), ] ``` You need to specify `namespace` in `include`. And then in your `app/urls.py`: ``` app_name = 'account' urlpatterns = [ path('register/', registration_view, name='register'), path('logout/', logout_view, name='logout'), path('login/', login_view, name='login'), ] ``` The `app_name` must match the `namespace` you've specified in `project/urls.py`. Whenever you're referring to these urls, you need to do it like this: ``` {% url 'namespace:name' %} ``` If you're using it with `redirect`: ``` return redirect('namespace:name') ```
Maybe someone will find this suggestion helpful. Go to your applications `urls.py` and type this before the urlpatterns: ``` app_name = 'Your app name' ```
41,883,254
I am trying to process a form in django/python using the following code. --- home.html: ```html <form action="{% url 'home:submit' %}" method='post'> ``` --- views.py: ```py def submit(request): a = request.POST(['initial']) return render(request, 'home/home.html', { 'error_message': "returned" }) ``` --- urls.py: ```py from django.conf.urls import url from . import views urlpatterns = [ url(r'^submit/$', views.submit, name='submit') ] ``` when I try to run it in a browser I get the error: `NoReverseMatch at /home/ u'home' is not a registered namespace` and another error message indicating a problem with the form.
2017/01/26
[ "https://Stackoverflow.com/questions/41883254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7169431/" ]
In your main project, open url.py first. Then check, there should be app\_name declared at first. If it is not, declare it. For example, my app name is user info which is declared in url.py ``` app_name = "userinfo" urlpatterns = [ url(r'home/', views.home, name='home'), url(r'register/', views.registration, name='register') ] ```
Probably 2 things could be a root cause, in app/urls.py do include as below ``` app_name = 'required_name' ``` and in project urls.py also include the app\_name ``` url(r'^required_name/$',views.home,name='required_name'), ``` Check: register app in settings.py INSTALLED\_APPS
41,883,254
I am trying to process a form in django/python using the following code. --- home.html: ```html <form action="{% url 'home:submit' %}" method='post'> ``` --- views.py: ```py def submit(request): a = request.POST(['initial']) return render(request, 'home/home.html', { 'error_message': "returned" }) ``` --- urls.py: ```py from django.conf.urls import url from . import views urlpatterns = [ url(r'^submit/$', views.submit, name='submit') ] ``` when I try to run it in a browser I get the error: `NoReverseMatch at /home/ u'home' is not a registered namespace` and another error message indicating a problem with the form.
2017/01/26
[ "https://Stackoverflow.com/questions/41883254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7169431/" ]
You should just change you action url in your template: ``` <form action="{% url 'submit' %} "method='post'> ``` --- On the note of url namespaces... In order to be able to call urls using `home` namespace you should have in your main urls.py file line something like: for django 1.x: ``` url(r'^', include('home.urls', namespace='home')), ``` for django 2.x and 3.x ``` path('', include(('home.urls', 'home'), namespace='home')) ```
I also faced the same issue. it is fixed now by adding ``` app_name = "<name of your app>" ``` in app/urls.py
41,883,254
I am trying to process a form in django/python using the following code. --- home.html: ```html <form action="{% url 'home:submit' %}" method='post'> ``` --- views.py: ```py def submit(request): a = request.POST(['initial']) return render(request, 'home/home.html', { 'error_message': "returned" }) ``` --- urls.py: ```py from django.conf.urls import url from . import views urlpatterns = [ url(r'^submit/$', views.submit, name='submit') ] ``` when I try to run it in a browser I get the error: `NoReverseMatch at /home/ u'home' is not a registered namespace` and another error message indicating a problem with the form.
2017/01/26
[ "https://Stackoverflow.com/questions/41883254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7169431/" ]
In your main project, open url.py first. Then check, there should be app\_name declared at first. If it is not, declare it. For example, my app name is user info which is declared in url.py ``` app_name = "userinfo" urlpatterns = [ url(r'home/', views.home, name='home'), url(r'register/', views.registration, name='register') ] ```
For the ***namespace error***, Make sure you have linked the app's url in the main urls.py file ``` path('app_name/',include('app_name.urls')) ``` also in the urls.py of your app,make sure you mention the app's name as ``` app_name='app_name' ``` Also make sure you have registered the app's name on your installed apps in settings.py
41,883,254
I am trying to process a form in django/python using the following code. --- home.html: ```html <form action="{% url 'home:submit' %}" method='post'> ``` --- views.py: ```py def submit(request): a = request.POST(['initial']) return render(request, 'home/home.html', { 'error_message': "returned" }) ``` --- urls.py: ```py from django.conf.urls import url from . import views urlpatterns = [ url(r'^submit/$', views.submit, name='submit') ] ``` when I try to run it in a browser I get the error: `NoReverseMatch at /home/ u'home' is not a registered namespace` and another error message indicating a problem with the form.
2017/01/26
[ "https://Stackoverflow.com/questions/41883254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7169431/" ]
tag name must be unique in the `urls.py` file inside your application package inside the project! it is important for the template tagging to route whats what and where. now [1] inside the `urls.py` file you need to declare the variable `appName` and give it the unique value. for example `appName = "myApp";` in your case *myHomeApp* and [2] also define the urlpatterns list... ``` urlpatterns = [..., url(r'^submit/$', views.submit, name='submit'), ...]; ``` in the html file just change the url tag to: ``` <form action="{% url 'myHomeApp:submit' %}" method='post'> ``` this should sifuce... else just write here and we'll see how to continue on
Check your urls.py ``` urlpatterns = [ re_path(r'^submit/expense/$', views.submit_expense, name='submit_expense'), re_path(r'^submit/income/$', views.submit_income, name='submit_income'), re_path(r'^register/$', views.register, name='register'), ] ``` then open template.html put for example register register in your HTML tag like this: ``` <a class="navbar-brand" href="{% url 'register' %}"> ```
41,883,254
I am trying to process a form in django/python using the following code. --- home.html: ```html <form action="{% url 'home:submit' %}" method='post'> ``` --- views.py: ```py def submit(request): a = request.POST(['initial']) return render(request, 'home/home.html', { 'error_message': "returned" }) ``` --- urls.py: ```py from django.conf.urls import url from . import views urlpatterns = [ url(r'^submit/$', views.submit, name='submit') ] ``` when I try to run it in a browser I get the error: `NoReverseMatch at /home/ u'home' is not a registered namespace` and another error message indicating a problem with the form.
2017/01/26
[ "https://Stackoverflow.com/questions/41883254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7169431/" ]
I also faced the same issue. it is fixed now by adding ``` app_name = "<name of your app>" ``` in app/urls.py
For Django 3.0, if you're handling your urls within the app and using `include` with `path`, in your `project/urls.py`: ``` urlpatterns = [ path(os.getenv('ADMIN_PATH'), admin.site.urls), path('', include('my_simple_blog.urls', namespace='my_simple_blog')), path('account/', include('account.urls', namespace='account')), ] ``` You need to specify `namespace` in `include`. And then in your `app/urls.py`: ``` app_name = 'account' urlpatterns = [ path('register/', registration_view, name='register'), path('logout/', logout_view, name='logout'), path('login/', login_view, name='login'), ] ``` The `app_name` must match the `namespace` you've specified in `project/urls.py`. Whenever you're referring to these urls, you need to do it like this: ``` {% url 'namespace:name' %} ``` If you're using it with `redirect`: ``` return redirect('namespace:name') ```
41,883,254
I am trying to process a form in django/python using the following code. --- home.html: ```html <form action="{% url 'home:submit' %}" method='post'> ``` --- views.py: ```py def submit(request): a = request.POST(['initial']) return render(request, 'home/home.html', { 'error_message': "returned" }) ``` --- urls.py: ```py from django.conf.urls import url from . import views urlpatterns = [ url(r'^submit/$', views.submit, name='submit') ] ``` when I try to run it in a browser I get the error: `NoReverseMatch at /home/ u'home' is not a registered namespace` and another error message indicating a problem with the form.
2017/01/26
[ "https://Stackoverflow.com/questions/41883254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7169431/" ]
As azmirfakkri has said if you're using `redirect`, dont use this `{% url 'namespace:name' %}` syntax, use `return redirect('namespace:name')`.
tag name must be unique in the `urls.py` file inside your application package inside the project! it is important for the template tagging to route whats what and where. now [1] inside the `urls.py` file you need to declare the variable `appName` and give it the unique value. for example `appName = "myApp";` in your case *myHomeApp* and [2] also define the urlpatterns list... ``` urlpatterns = [..., url(r'^submit/$', views.submit, name='submit'), ...]; ``` in the html file just change the url tag to: ``` <form action="{% url 'myHomeApp:submit' %}" method='post'> ``` this should sifuce... else just write here and we'll see how to continue on
41,883,254
I am trying to process a form in django/python using the following code. --- home.html: ```html <form action="{% url 'home:submit' %}" method='post'> ``` --- views.py: ```py def submit(request): a = request.POST(['initial']) return render(request, 'home/home.html', { 'error_message': "returned" }) ``` --- urls.py: ```py from django.conf.urls import url from . import views urlpatterns = [ url(r'^submit/$', views.submit, name='submit') ] ``` when I try to run it in a browser I get the error: `NoReverseMatch at /home/ u'home' is not a registered namespace` and another error message indicating a problem with the form.
2017/01/26
[ "https://Stackoverflow.com/questions/41883254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7169431/" ]
A common mistake that I always find is when you have some name space in your template, and in YourApp.url you don't have any name space so if you should use name space add in YourApp.url something like this app\_name = "blog" then on your temples make sure you add your name space, so you will have some thing like this "assumption errors are coming from `edit.html`" then on that particular template you will do this `"{% url 'blog:vote' pk=post.pk %}"` `"{% url 'blog:post_category' category.name %}"`
I got the same error below: > > NoReverseMatch at /account/register/ 'account' is not a registered > namespace > > > So, I set **"app\_name"** with **the application name "account"** to **"account/urls.py"** as shown below then the error above is solved: ```py # "account/urls.py" from django.urls import path from . import views app_name = "account" # Here urlpatterns = [ path("register/", views.register_request, name="register") ] ```
41,883,254
I am trying to process a form in django/python using the following code. --- home.html: ```html <form action="{% url 'home:submit' %}" method='post'> ``` --- views.py: ```py def submit(request): a = request.POST(['initial']) return render(request, 'home/home.html', { 'error_message': "returned" }) ``` --- urls.py: ```py from django.conf.urls import url from . import views urlpatterns = [ url(r'^submit/$', views.submit, name='submit') ] ``` when I try to run it in a browser I get the error: `NoReverseMatch at /home/ u'home' is not a registered namespace` and another error message indicating a problem with the form.
2017/01/26
[ "https://Stackoverflow.com/questions/41883254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7169431/" ]
You should just change you action url in your template: ``` <form action="{% url 'submit' %} "method='post'> ``` --- On the note of url namespaces... In order to be able to call urls using `home` namespace you should have in your main urls.py file line something like: for django 1.x: ``` url(r'^', include('home.urls', namespace='home')), ``` for django 2.x and 3.x ``` path('', include(('home.urls', 'home'), namespace='home')) ```
For the ***namespace error***, Make sure you have linked the app's url in the main urls.py file ``` path('app_name/',include('app_name.urls')) ``` also in the urls.py of your app,make sure you mention the app's name as ``` app_name='app_name' ``` Also make sure you have registered the app's name on your installed apps in settings.py
59,918,219
``` AttributeError at /addpatient_to_db 'QuerySet' object has no attribute 'wardno' ``` Request Method: POST Request URL: <http://127.0.0.1:8000/addpatient_to_db> Django Version: 2.2.5 Exception Type: `AttributeError` Exception Value: `'QuerySet' object has no attribute 'wardno'` Exception Location: `C:\Users\Saurabh Patil\Desktop\SanjeevniHospital\admininterface\views.py in addpatient_to_db, line 114` Python Executable: `C:\Users\Saurabh Patil\AppData\Local\Programs\Python\Python37\python.exe` Python Version: 3.7.4 Python Path: ``` ['C:\\Users\\Saurabh Patil\\Desktop\\SanjeevniHospital', 'C:\\Users\\Saurabh ' 'Patil\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', 'C:\\Users\\Saurabh Patil\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\Saurabh Patil\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\Saurabh Patil\\AppData\\Local\\Programs\\Python\\Python37', 'C:\\Users\\Saurabh Patil\\AppData\\Roaming\\Python\\Python37\\site-packages', 'C:\\Users\\Saurabh ' 'Patil\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages'] ``` Server time: Sun, 26 Jan 2020 12:07:40 +0000 Here is my code ***views.py*** ``` def addpatient_to_db(request): if request.method == 'POST': name = request.POST['name'] age = request.POST['age'] sex = request.POST['sex'] address = request.POST['address'] contno = request.POST['contno'] wardno = request.POST['wardno'] bedno = request.POST['bedno'] doa = request.POST['doa'] docass = request.POST['docass'] pii = request.POST['pii'] alldata = patientdetails.objects.all() if alldata.wardno == wardno and alldata.bedno == bedno: # <---- This is the issuing line return render(request, "addpatient.html") else: addp = patientdetails(name=name, age=age, sex=sex, address=address, mobno=contno, wardno=wardno, bedno=bedno, dateofallot=doa, docass=docass, illness_issue=pii) addp.save() return redirect('addpatient') else: return render(request, 'addpatient.html') ``` ***models.py*** ``` from django.db import models # Create your models here. class patientdetails(models.Model): name = models.CharField(max_length=50) age = models.CharField(max_length=3) sex = models.CharField(max_length=10) address = models.CharField(max_length=100) mobno = models.CharField(max_length=10) wardno = models.CharField(max_length=3) bedno = models.CharField(max_length=3) dateofallot = models.CharField(max_length=10) docass = models.CharField(max_length=50) illness_issue = models.CharField(max_length=50) ```
2020/01/26
[ "https://Stackoverflow.com/questions/59918219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11056524/" ]
**TLDR:** **Solution is that you should either provide engine and user\_id in params or you should remove presence true validation and add optional true case (for user association) from model.** **Explanation:** If your model says that it should validate presence of `engine` then how can you not provide engine param (in form). When you post the form without engine, what happens is that your model does not save it and as you have handled that case, it moves on. As it belongs to user, same goes for user ID. although you could make it optional too by adding optional: true both in schema and model (because a car can "be" without a user IRL but depends here in your use-case). Going one step further, to exactly understand the issue yourself, use pry or byebug to see the params and happenings in runtime. Easier and faster way to verify the error is that put a bang in front of create method and it will show the error like: `if @car.save!`. One more thing: copy the car params and try to do this in rails console yourself manually with bang. It will give you the cause. These things will help you diagnose model save/create issues in rails. Happy Coding :)
From your log file ``` Started POST "/cars" for ::1 at 2020-01-26 14:45:06 +0000 ``` Shows that the create action is being called on the cars controller The parameters being passed in are ``` {"authenticity_token"=>"Oom+xdVDc0PqSwLbLIEP0R8H6U38+v9ISVql4Fr/0WSxZGSrxzTHccsgghd1U30OugcUBAA1R4BtsB0YigAUtA==", "car"=>{"vehicle_type"=>"Sports", "car_type"=>"Private", "seat"=>"5", "colour_type"=>"Black", "transmission_type"=>"Automatic"}, "commit"=>"Create car"} ``` The first method called on your create action is authenticate\_user ``` before_action :authenticate_user!, except: [:show] ``` You can see that this happens ``` User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]] ``` According to your log the next thing that happens is ``` Rendering cars/new.html.erb within layouts/application ``` Which means that the else clause was hit `render :new, notice: "Something went wrong..."` ``` @car = current_user.cars.build(car_params) if @car.save redirect_to listing_car_path(@car), notice: "Saved..." else render :new, notice: "Something went wrong..." end ``` Therefore the car did not save so validation must have failed. Your new car form should have an errors loop to display all the errors. If it did have this then your user (You) would know what went wrong Something like this ``` <% if car.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(car.errors.count, "error") %> prohibited this car from being saved:</h2> <ul> <% car.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> ``` Should do the trick but it's standard in all rails generated forms so it should be there anyway
62,377,906
I want to run a batch file in a Conda environment, not in the **base** env, but in another virtual environment (here **pylayers**). I copied the `activate.bat` script from `F:\Anaconda3\Scripts` to `F:\Anaconda3\envs\pylayers\Scripts`. And my batch script (`installer_win.bat`) is: ``` call F:\Anaconda3\envs\pylayers\Scripts\activate.bat conda install numpy --yes conda install mayavi --yes conda install shapely --yes conda install libgdal --yes conda install gdal --yes conda install h5py --yes conda install seaborn --yes conda install PIL --yes conda install basemap --yes conda install wxpython --yes conda install netCDF4 --yes pip install protobuf pip install tqdm pip install descartes pip install bitstring pip install geocoder pip install triangle pip install osmapi pip install pyshp pip install Image pip install pathos pip install SimPy==2.2 pip install simplekml pip install smopy python setup.py install ``` When I execute the `installer_win.bat` file, it shows the following behavior: ``` Output: #stops after executing very first line in the batch file. (base) C:\Users\mkdth>activate pylayers (pylayers) C:\Users\mkdth>cd /d F:\Pycharm\Projects\pylayers-master (pylayers) F:\Pycharm\Projects\pylayers-master>installer_win.bat (pylayers) F:\Pycharm\Projects\pylayers-master>call F:\Anaconda3\envs\pylayers\Scripts\activate.bat The system cannot find the path specified. (pylayers) F:\Pycharm\Projects\pylayers-master>conda install numpy --yes Collecting package metadata (current_repodata.json): done Solving environment: done ## Package Plan ## environment location: F:\Anaconda3\envs\pylayers added / updated specs: - numpy The following packages will be downloaded: package | build ---------------------------|----------------- openssl-1.1.1g | he774522_0 4.8 MB ------------------------------------------------------------ Total: 4.8 MB The following NEW packages will be INSTALLED: numpy-base pkgs/main/win-64::numpy-base-1.18.1-py36hc3f5095_1 The following packages will be SUPERSEDED by a higher-priority channel: ca-certificates conda-forge::ca-certificates-2020.4.5~ --> pkgs/main::ca-certificates-2020.1.1-0 certifi conda-forge::certifi-2020.4.5.2-py36h~ --> pkgs/main::certifi-2020.4.5.1-py36_0 numpy conda-forge::numpy-1.18.5-py36h4d86e3~ --> pkgs/main::numpy-1.18.1-py36h93ca92e_0 openssl conda-forge --> pkgs/main Downloading and Extracting Packages openssl-1.1.1g | 4.8 MB | ############################################################################ | 100% Preparing transaction: done Verifying transaction: done Executing transaction: done (pylayers) F:\Pycharm\Projects\pylayers-master> ``` I also tried to modify the batch file to activate **pylayers** environment from the **base** env and run the `conda` or `pip` commands one by one, but it installs to **base** environment only. See the bat script Attempt 1 --------- `Installer_win.bat` file: ``` call F:\Anaconda3\Scripts\activate.bat activate pylayers pause conda install numpy --yes conda install mayavi --yes conda install shapely --yes conda install libgdal --yes conda install gdal --yes conda install h5py --yes conda install seaborn --yes conda install PIL --yes conda install basemap --yes conda install wxpython --yes conda install netCDF4 --yes pip install protobuf pip install tqdm pip install descartes pip install bitstring pip install geocoder pip install triangle pip install osmapi pip install pyshp pip install Image pip install pathos pip install SimPy==2.2 pip install simplekml pip install smopy python setup.py install ``` Output: activates pylayers env and stops ``` (pylayers) F:\Pycharm\Projects\pylayers-master>installer_win.bat (pylayers) F:\Pycharm\Projects\pylayers-master>call F:\Anaconda3\Scripts\activate.bat (base) F:\Pycharm\Projects\pylayers-master>activate pylayers (pylayers) F:\Pycharm\Projects\pylayers-master> ``` Attempt2: --------- `Installer_win.bat` file: ``` call F:\Anaconda3\Scripts\activate.bat activate pylayers conda install numpy --yes conda install mayavi --yes conda install shapely --yes conda install libgdal --yes conda install gdal --yes conda install h5py --yes conda install seaborn --yes conda install PIL --yes conda install basemap --yes conda install wxpython --yes conda install netCDF4 --yes pip install protobuf pip install tqdm pip install descartes pip install bitstring pip install geocoder pip install triangle pip install osmapi pip install pyshp pip install Image pip install pathos pip install SimPy==2.2 pip install simplekml pip install smopy python setup.py install ``` Output: #activates base env and stops ``` (pylayers) F:\Pycharm\Projects\pylayers-master>installer_win.bat (pylayers) F:\Pycharm\Projects\pylayers-master>call F:\Anaconda3\Scripts\activate.bat (base) F:\Pycharm\Projects\pylayers-master>activate pylayers ``` Attempt 3 --------- `Installer_win.bat` file: ``` call F:\Anaconda3\Scripts\activate.bat conda install numpy --yes conda install mayavi --yes conda install shapely --yes conda install libgdal --yes conda install gdal --yes conda install h5py --yes conda install seaborn --yes conda install PIL --yes conda install basemap --yes conda install wxpython --yes conda install netCDF4 --yes pip install protobuf pip install tqdm pip install descartes pip install bitstring pip install geocoder pip install triangle pip install osmapi pip install pyshp pip install Image pip install pathos pip install SimPy==2.2 pip install simplekml pip install smopy python setup.py install ``` Output: #starts installing in base env ``` (pylayers) F:\Pycharm\Projects\pylayers-master>installer_win.bat (pylayers) F:\Pycharm\Projects\pylayers-master>call F:\Anaconda3\Scripts\activate.bat (base) F:\Pycharm\Projects\pylayers-master>activate pylayers (pylayers) F:\Pycharm\Projects\pylayers-master>installer_win.bat (pylayers) F:\Pycharm\Projects\pylayers-master>call F:\Anaconda3\Scripts\activate.bat (base) F:\Pycharm\Projects\pylayers-master>conda install numpy --yes Collecting package metadata (current_repodata.json): failed CondaError: KeyboardInterrupt ^CTerminate batch job (Y/N)? ^C ``` Can someone help me to run this batch file under a Conda virtual env, please? Any suggestions would be very much appreciated.
2020/06/14
[ "https://Stackoverflow.com/questions/62377906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11051182/" ]
There are two ways to go. I think the first is the cleaner way to go. Option 1: YAML Definition ========================= If the entire procedure is only for installations, it can be condensed into a single [YAML environment definition](https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#create-env-file-manually) and executed in a one go. This includes the local package installation, which for the current example I'll call `foo`. **foo\_install.yaml** ``` name: foo_install channels: - defaults dependencies: - numpy - mayavi - shapely - libgdal - gdal - h5py - seaborn - PIL - basemap - wxpython - netCDF4 - pip - pip: - protobuf - tqdm - descartes - bitstring - geocoder - triangle - osmapi - pyshp - Image - pathos - SimPy==2.2 - simplekml - smopy - -e ./../foo # this assumes running from inside the `foo` folder ``` To install this into an arbitrary env (e.g., `pylevels`) as an *addition* to the env, one would use ``` conda env update -n pylevels -f foo_install.yaml ``` where this is run from within the `foo` folder. See [the Advanced Pip Example](https://github.com/conda/conda/blob/4.8.3/tests/conda_env/support/advanced-pip/environment.yml) for a showcase of other options (basically, everything `pip install` accepts can be included in a YAML file). Option 2: `conda run` ===================== More generically, one can run arbitrary scripts inside a specific environment by using `conda run`. This avoids having to include activation commands inside scripts themselves. In this case, you could run your script with ``` conda run -n pylevels installer_win.bat ``` I would only resort to this if you need to also configure some environment variables or something similar. In that case, I would still make the YAML, and reduce all the installation to the single line: **installer\_win.bat** ``` conda env update -f foo_install.yaml ``` and include further actions after that.
To run a bat file from a dos prompt inside a new (non-base) conda env, you can try something like this: prompt> cmd "/c activate ds\_tensorflow && myfile.bat && deactivate" contents of myfile.bat to show you are in the non-base env: ``` echo hello python -c "import sys; print(sys.version)" ``` You can replace myfile.bat in the >> line above with your bat file. This will also work without the bat file, just run each command within the /c activate .... deactivate wrapper. ``` cmd "/c activate ds_tensorflow && python -c "import sys; print(sys.version)" && deactivate" ```
66,577,552
I would like to suppress some sensitive information displayed in the logs. Code: ``` pipeline { parameters { string(defaultValue: '', description: '', name: 'pki_client_cacert_password', trim: true) string(defaultValue: '', description: '', name: 'db_url', trim: true) } stages { stage('DeployToDev') { steps { script{ env.artifacts = sh( returnStdout: true, script: "/var/lib/jenkins/python_jobs/venv/bin/python3 /var/lib/jenkins/python_jobs/encrypter_creds.py --db_url=${env.db_url} --pki_client_cacert_password='${env.pki_client_cacert_password}'" ) } } } } } ``` Output: ``` + /var/lib/jenkins/python_jobs/venv/bin/python3 /var/lib/jenkins/python_jobs/encrypter_creds.py --db_url=<hide this from jenkins logs> '--pki_client_cacert_password=<hide this from jenkins logs>' ```
2021/03/11
[ "https://Stackoverflow.com/questions/66577552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1234419/" ]
First option is to set it as environment var: ``` withEnv(["MYSECRET=${params.pki_client_cacert_password}", "MYURL=${env.db_url}"]) { env.artifacts = sh( returnStdout: true, script: '.. python3 .. encrypter_creds.py --db_url=$MYURL ' + ' --pki_client_cacert_password=$MYSECRET' ) ``` Note the single quotes around the command to prevent any Groovy string interpolation. Second option is to save something like `pki_client_cacert_password` (which hopefully doesn't change much) into Jenkins Credentials Store and use it `withCredentials`: ``` withCredentials([usernamePassword( credentialsId: 'MY_PKI_CLIENT_CREDENTIALS', passwordVariable: 'DB_URL', usernameVariable: 'PKI_USER')]) { env.artifacts = sh( returnStdout: true, script: '.. python3 .. encrypter_creds.py --db_url=$DB_URL' + ' --pki_client_cacert_password=$PKI_PASSWORD' } ``` You can also roll your own third option, e.g. by writing the info you need into a file and modifying your script to read the parameters from that file.
I have added @MaratC suggestion however that did not help much, so I ended up adding `set +x` and `set -x` more so this question was related to [Echo off in Jenkins Console Output](https://stackoverflow.com/questions/26797219/echo-off-in-jenkins-console-output) which worked as expected ``` script{ withEnv(["ENV_PKI_CLIENT_CACERT_PASSWORD=${params.pki_client_cacert_password}", "ENV_DB_URL=${params.db_url}"]) { env.artifacts = sh( returnStdout: true, script: """ set +x /var/lib/jenkins/python_jobs/venv/bin/python3 /var/lib/jenkins/python_jobs/encrypter_creds.py --db_url=${ENV_DB_URL} --pki_client_cacert_password='${ENV_PKI_CLIENT_CACERT_PASSWORD}' set -x """ ) } } ``` Jenkins output ``` + set +x [Pipeline] ..... [Pipeline] ..... ```
54,811,697
I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form. Is there any other form? I am used to looping until a condition is false. There doesn't seem to be a way to evaluate a condition in a for loop in Python. Is that correct? Since there is no (init;condition;post) , how would you do something like iterate over every other string in a collection of strings, in python? C++ would look like: ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ```
2019/02/21
[ "https://Stackoverflow.com/questions/54811697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5191073/" ]
A for loop is the same thing as a while loop, just in a slightly different syntax. If you have a for loop that looks like ``` for(init; condition; post) //do something ``` that is equivalent to the while loop ``` init; while(condition) //do something post; ``` because Python has while loops, if you wanted to iterate over every other string, you would change ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ``` to ``` mystuff = [ "poop", "dooky", "doodoo" ] index = 0 while index < 3: print(mystuff[index]) index += 2 ```
(Most Common)Three kinds of loops : 1. `Count controlled` - You dont have this kind of loop in python 2. `Condition controlled` - while loop in python 3. `Collection controlled` - for loop in python
54,811,697
I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form. Is there any other form? I am used to looping until a condition is false. There doesn't seem to be a way to evaluate a condition in a for loop in Python. Is that correct? Since there is no (init;condition;post) , how would you do something like iterate over every other string in a collection of strings, in python? C++ would look like: ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ```
2019/02/21
[ "https://Stackoverflow.com/questions/54811697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5191073/" ]
Consider this (credit to @Teghan for pointing out [::2] version): ``` > myStrs = ['A', 'B', 'C', 'D', 'E', 'F'] > > for i in range(0, len(myStrs), 2): > print(myStrs[i]) > > print([(myStrs[i]) for i in range(0, len(myStrs), 2)]) > print([x+"a" for x in myStrs[::2]]) ``` Output: > > > ``` > A > C > E > ['A', 'C', 'E'] > ['Aa', 'Ca', 'Ea'] > > ``` > >
You want a while loop: ``` i = 0 n = int while i < n: # do something if some_possible_condition = True: i = i + 1 ``` To your specific example: > > how would you do something like iterate over every other string in a collection of strings, in python? > > > You could use a for loop and check a condition: ``` strings = ['string1', 'string2', ... , 'stringN'] for i in range(len(strings)): if i % 2 == 0: # do things to strings[i] ``` But a more pythonic way would be to access only every other element in the list of strings using list indexing, and process each string: ``` for each_even_string in strings[::2]: # do things to each_even_string ```
54,811,697
I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form. Is there any other form? I am used to looping until a condition is false. There doesn't seem to be a way to evaluate a condition in a for loop in Python. Is that correct? Since there is no (init;condition;post) , how would you do something like iterate over every other string in a collection of strings, in python? C++ would look like: ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ```
2019/02/21
[ "https://Stackoverflow.com/questions/54811697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5191073/" ]
> > I am used to looping until a condition is false. There doesn't seem to > be a way to evaluate a condition in a for loop in Python. Is that > correct? > > > Correct. For loops don't evaluate conditions by themselfs, they iterate through an iterable. When you write `for i in something`, that `something` must be an [iterable](https://docs.python.org/3/glossary.html#term-iterable). See the link for more details. The important part is that a for loop goes through **all** the elements of the iterable. If you want to skip one or more elements, you have to implement a condition inside the loop (like `if i == certain_value: continue`) or build a second iterable where you exclude the elements that must be skipped and use the for loop on that. > > Since there is no (init;condition;post) , how would you do something > like iterate over every other string in a collection of strings, in > python? > > > There is an high chance that a collection of string is an iterable (depends of what object you use to collect the strings). If you need conditions on the index you can use [range()](https://docs.python.org/3/library/functions.html#func-range) and use indexes, or [enumerate()](https://docs.python.org/3/library/functions.html#enumerate). If fact there are several ways to obtain the same result, other answers already pointed out few of them. Your c++ code: ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ``` can be rendered for example using *range()*: ``` ll = ["poop", "dooky", "doodoo"] for i in range(0, len(ll), 2): print(ll[i]) ``` In this case `range(0, len(ll), 2)` is an iterable. In python2 would be a list: `[0, 2]`. In python3 is a range object, which if converted to a list would be again `[0, 2]`.
You want a while loop: ``` i = 0 n = int while i < n: # do something if some_possible_condition = True: i = i + 1 ``` To your specific example: > > how would you do something like iterate over every other string in a collection of strings, in python? > > > You could use a for loop and check a condition: ``` strings = ['string1', 'string2', ... , 'stringN'] for i in range(len(strings)): if i % 2 == 0: # do things to strings[i] ``` But a more pythonic way would be to access only every other element in the list of strings using list indexing, and process each string: ``` for each_even_string in strings[::2]: # do things to each_even_string ```
54,811,697
I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form. Is there any other form? I am used to looping until a condition is false. There doesn't seem to be a way to evaluate a condition in a for loop in Python. Is that correct? Since there is no (init;condition;post) , how would you do something like iterate over every other string in a collection of strings, in python? C++ would look like: ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ```
2019/02/21
[ "https://Stackoverflow.com/questions/54811697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5191073/" ]
A for loop is the same thing as a while loop, just in a slightly different syntax. If you have a for loop that looks like ``` for(init; condition; post) //do something ``` that is equivalent to the while loop ``` init; while(condition) //do something post; ``` because Python has while loops, if you wanted to iterate over every other string, you would change ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ``` to ``` mystuff = [ "poop", "dooky", "doodoo" ] index = 0 while index < 3: print(mystuff[index]) index += 2 ```
> > I am used to looping until a condition is false. There doesn't seem to > be a way to evaluate a condition in a for loop in Python. Is that > correct? > > > Correct. For loops don't evaluate conditions by themselfs, they iterate through an iterable. When you write `for i in something`, that `something` must be an [iterable](https://docs.python.org/3/glossary.html#term-iterable). See the link for more details. The important part is that a for loop goes through **all** the elements of the iterable. If you want to skip one or more elements, you have to implement a condition inside the loop (like `if i == certain_value: continue`) or build a second iterable where you exclude the elements that must be skipped and use the for loop on that. > > Since there is no (init;condition;post) , how would you do something > like iterate over every other string in a collection of strings, in > python? > > > There is an high chance that a collection of string is an iterable (depends of what object you use to collect the strings). If you need conditions on the index you can use [range()](https://docs.python.org/3/library/functions.html#func-range) and use indexes, or [enumerate()](https://docs.python.org/3/library/functions.html#enumerate). If fact there are several ways to obtain the same result, other answers already pointed out few of them. Your c++ code: ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ``` can be rendered for example using *range()*: ``` ll = ["poop", "dooky", "doodoo"] for i in range(0, len(ll), 2): print(ll[i]) ``` In this case `range(0, len(ll), 2)` is an iterable. In python2 would be a list: `[0, 2]`. In python3 is a range object, which if converted to a list would be again `[0, 2]`.
54,811,697
I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form. Is there any other form? I am used to looping until a condition is false. There doesn't seem to be a way to evaluate a condition in a for loop in Python. Is that correct? Since there is no (init;condition;post) , how would you do something like iterate over every other string in a collection of strings, in python? C++ would look like: ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ```
2019/02/21
[ "https://Stackoverflow.com/questions/54811697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5191073/" ]
> > I am used to looping until a condition is false. There doesn't seem to > be a way to evaluate a condition in a for loop in Python. Is that > correct? > > > Correct. For loops don't evaluate conditions by themselfs, they iterate through an iterable. When you write `for i in something`, that `something` must be an [iterable](https://docs.python.org/3/glossary.html#term-iterable). See the link for more details. The important part is that a for loop goes through **all** the elements of the iterable. If you want to skip one or more elements, you have to implement a condition inside the loop (like `if i == certain_value: continue`) or build a second iterable where you exclude the elements that must be skipped and use the for loop on that. > > Since there is no (init;condition;post) , how would you do something > like iterate over every other string in a collection of strings, in > python? > > > There is an high chance that a collection of string is an iterable (depends of what object you use to collect the strings). If you need conditions on the index you can use [range()](https://docs.python.org/3/library/functions.html#func-range) and use indexes, or [enumerate()](https://docs.python.org/3/library/functions.html#enumerate). If fact there are several ways to obtain the same result, other answers already pointed out few of them. Your c++ code: ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ``` can be rendered for example using *range()*: ``` ll = ["poop", "dooky", "doodoo"] for i in range(0, len(ll), 2): print(ll[i]) ``` In this case `range(0, len(ll), 2)` is an iterable. In python2 would be a list: `[0, 2]`. In python3 is a range object, which if converted to a list would be again `[0, 2]`.
You might be searching for [while](https://www.w3schools.com/python/python_while_loops.asp) loops
54,811,697
I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form. Is there any other form? I am used to looping until a condition is false. There doesn't seem to be a way to evaluate a condition in a for loop in Python. Is that correct? Since there is no (init;condition;post) , how would you do something like iterate over every other string in a collection of strings, in python? C++ would look like: ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ```
2019/02/21
[ "https://Stackoverflow.com/questions/54811697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5191073/" ]
A for loop is the same thing as a while loop, just in a slightly different syntax. If you have a for loop that looks like ``` for(init; condition; post) //do something ``` that is equivalent to the while loop ``` init; while(condition) //do something post; ``` because Python has while loops, if you wanted to iterate over every other string, you would change ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ``` to ``` mystuff = [ "poop", "dooky", "doodoo" ] index = 0 while index < 3: print(mystuff[index]) index += 2 ```
You might be searching for [while](https://www.w3schools.com/python/python_while_loops.asp) loops
54,811,697
I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form. Is there any other form? I am used to looping until a condition is false. There doesn't seem to be a way to evaluate a condition in a for loop in Python. Is that correct? Since there is no (init;condition;post) , how would you do something like iterate over every other string in a collection of strings, in python? C++ would look like: ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ```
2019/02/21
[ "https://Stackoverflow.com/questions/54811697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5191073/" ]
A for loop is the same thing as a while loop, just in a slightly different syntax. If you have a for loop that looks like ``` for(init; condition; post) //do something ``` that is equivalent to the while loop ``` init; while(condition) //do something post; ``` because Python has while loops, if you wanted to iterate over every other string, you would change ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ``` to ``` mystuff = [ "poop", "dooky", "doodoo" ] index = 0 while index < 3: print(mystuff[index]) index += 2 ```
Consider this (credit to @Teghan for pointing out [::2] version): ``` > myStrs = ['A', 'B', 'C', 'D', 'E', 'F'] > > for i in range(0, len(myStrs), 2): > print(myStrs[i]) > > print([(myStrs[i]) for i in range(0, len(myStrs), 2)]) > print([x+"a" for x in myStrs[::2]]) ``` Output: > > > ``` > A > C > E > ['A', 'C', 'E'] > ['Aa', 'Ca', 'Ea'] > > ``` > >
54,811,697
I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form. Is there any other form? I am used to looping until a condition is false. There doesn't seem to be a way to evaluate a condition in a for loop in Python. Is that correct? Since there is no (init;condition;post) , how would you do something like iterate over every other string in a collection of strings, in python? C++ would look like: ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ```
2019/02/21
[ "https://Stackoverflow.com/questions/54811697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5191073/" ]
A for loop is the same thing as a while loop, just in a slightly different syntax. If you have a for loop that looks like ``` for(init; condition; post) //do something ``` that is equivalent to the while loop ``` init; while(condition) //do something post; ``` because Python has while loops, if you wanted to iterate over every other string, you would change ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ``` to ``` mystuff = [ "poop", "dooky", "doodoo" ] index = 0 while index < 3: print(mystuff[index]) index += 2 ```
You want a while loop: ``` i = 0 n = int while i < n: # do something if some_possible_condition = True: i = i + 1 ``` To your specific example: > > how would you do something like iterate over every other string in a collection of strings, in python? > > > You could use a for loop and check a condition: ``` strings = ['string1', 'string2', ... , 'stringN'] for i in range(len(strings)): if i % 2 == 0: # do things to strings[i] ``` But a more pythonic way would be to access only every other element in the list of strings using list indexing, and process each string: ``` for each_even_string in strings[::2]: # do things to each_even_string ```
54,811,697
I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form. Is there any other form? I am used to looping until a condition is false. There doesn't seem to be a way to evaluate a condition in a for loop in Python. Is that correct? Since there is no (init;condition;post) , how would you do something like iterate over every other string in a collection of strings, in python? C++ would look like: ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ```
2019/02/21
[ "https://Stackoverflow.com/questions/54811697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5191073/" ]
(Most Common)Three kinds of loops : 1. `Count controlled` - You dont have this kind of loop in python 2. `Condition controlled` - while loop in python 3. `Collection controlled` - for loop in python
You want a while loop: ``` i = 0 n = int while i < n: # do something if some_possible_condition = True: i = i + 1 ``` To your specific example: > > how would you do something like iterate over every other string in a collection of strings, in python? > > > You could use a for loop and check a condition: ``` strings = ['string1', 'string2', ... , 'stringN'] for i in range(len(strings)): if i % 2 == 0: # do things to strings[i] ``` But a more pythonic way would be to access only every other element in the list of strings using list indexing, and process each string: ``` for each_even_string in strings[::2]: # do things to each_even_string ```
54,811,697
I am learning python, coming from c++. From what I am reading, there only appears to be two forms of for loops in python. I can either iterate over a range, or through the elements of a collection. I suppose the former really is the latter...so maybe one form. Is there any other form? I am used to looping until a condition is false. There doesn't seem to be a way to evaluate a condition in a for loop in Python. Is that correct? Since there is no (init;condition;post) , how would you do something like iterate over every other string in a collection of strings, in python? C++ would look like: ``` string mystuff[] = {"poop", "dooky", "doodoo"}; for(size_t index = 0; index < 3; index += 2) cout << mystuff[index]; ```
2019/02/21
[ "https://Stackoverflow.com/questions/54811697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5191073/" ]
(Most Common)Three kinds of loops : 1. `Count controlled` - You dont have this kind of loop in python 2. `Condition controlled` - while loop in python 3. `Collection controlled` - for loop in python
You might be searching for [while](https://www.w3schools.com/python/python_while_loops.asp) loops
6,289,699
> > **Possible Duplicate:** > > [How do I get the name of a function or method from within a Python function or method?](https://stackoverflow.com/questions/245304/how-do-i-get-the-name-of-a-function-or-method-from-within-a-python-function-or-me) > > > The below code function return it's name. It works but I still have to specify the 'test.' in front of of the `__name__`. Is there any general way to refer the `__name__` ? ``` def test(): print test.__name__ ```
2011/06/09
[ "https://Stackoverflow.com/questions/6289699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240041/" ]
If I understand correctly - [Inspect](http://docs.python.org/library/inspect.html) is what you are looking for. ``` import inspect def test(): print inspect.stack()[0][3] ```
There is no way to access the function name in a python function without using a backtrace. ``` In [1]: import inspect In [2]: def test(): ...: print inspect.stack()[0][3] ...: In [3]: test() test ``` So, what you want to use is `inspect.stack()[0][3]` or, if you want to move it into a separate function, `inspect.stack()[1][3]` (from [How do I get the name of a function or method from within a Python function or method?](https://stackoverflow.com/questions/245304/how-do-i-get-the-name-of-a-function-or-method-from-within-a-python-function-or-me))
614,458
How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign * Case 1: `str1=str2` * Case 2: `str1 = str2` please note there can be a **space or none** between the either side of the "=" sign Mine is like this, but only works for one of the cases! ``` m=re.search('(?<=str\s\=\s)\w+','str = str2') ``` returns str2 Help! Gath
2009/03/05
[ "https://Stackoverflow.com/questions/614458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74170/" ]
if you indeed have only such simple strings to parse you don't need regular expression. you can just partition on `=` and strip (or even lstrip) last element of a resulting tuple: ``` >>> case = 'str = str2' >>> case.partition('=')[2].lstrip() 'str2' ``` it'll be much faster than regexps. and just to show how fast i've made a simple test: ``` >>> timeit.timeit("'str1 = str2 '.partition('=')[2].strip()") 0.49051564213846177 >>> timeit.timeit("'str1 = str2 '.split('=')[1].strip()") 0.97673281637025866 >>> timeit.timeit('import re') 0.65663786250422618 ```
``` re.search(r'=\s*(.*)', 'str = str2').group(1) ``` or if you just want a single word: ``` re.search(r'=\s*(\w+)', 'str = str2').group(1) ``` Extended to specific initial string: ``` re.search(r'\bstr\s*=\s*(\w+)', 'str=str2').group(1) ``` `\b` = word boundary, so won't match `"somestr=foo"` It would be quicker to go trough all options once, instead of searching for single options one at the time: ``` option_str = "a=b, c=d, g=h" options = dict(re.findall(r'(\w+)\s*=\s*(\w+)', option_str)) options['c'] # -> 'd' ```
614,458
How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign * Case 1: `str1=str2` * Case 2: `str1 = str2` please note there can be a **space or none** between the either side of the "=" sign Mine is like this, but only works for one of the cases! ``` m=re.search('(?<=str\s\=\s)\w+','str = str2') ``` returns str2 Help! Gath
2009/03/05
[ "https://Stackoverflow.com/questions/614458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74170/" ]
``` re.search(r'=\s*(.*)', 'str = str2').group(1) ``` or if you just want a single word: ``` re.search(r'=\s*(\w+)', 'str = str2').group(1) ``` Extended to specific initial string: ``` re.search(r'\bstr\s*=\s*(\w+)', 'str=str2').group(1) ``` `\b` = word boundary, so won't match `"somestr=foo"` It would be quicker to go trough all options once, instead of searching for single options one at the time: ``` option_str = "a=b, c=d, g=h" options = dict(re.findall(r'(\w+)\s*=\s*(\w+)', option_str)) options['c'] # -> 'd' ```
Expanding on @batbrat's answer, and the other suggestions, you can use `re.split()` to separate the input string. The pattern can use `\s` (whitespace) or an explicit space. ``` >>> import re >>> c1="str1=str2" >>> c2="str1 = str2" >>> re.split(' ?= ?',c1) ['str1', 'str2'] >>> re.split(' ?= ?',c2) ['str1', 'str2'] >>> re.split(r'\s?=\s?',c1) ['str1', 'str2'] >>> re.split(r'\s?=\s?',c2) ['str1', 'str2'] >>> ```
614,458
How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign * Case 1: `str1=str2` * Case 2: `str1 = str2` please note there can be a **space or none** between the either side of the "=" sign Mine is like this, but only works for one of the cases! ``` m=re.search('(?<=str\s\=\s)\w+','str = str2') ``` returns str2 Help! Gath
2009/03/05
[ "https://Stackoverflow.com/questions/614458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74170/" ]
if you indeed have only such simple strings to parse you don't need regular expression. you can just partition on `=` and strip (or even lstrip) last element of a resulting tuple: ``` >>> case = 'str = str2' >>> case.partition('=')[2].lstrip() 'str2' ``` it'll be much faster than regexps. and just to show how fast i've made a simple test: ``` >>> timeit.timeit("'str1 = str2 '.partition('=')[2].strip()") 0.49051564213846177 >>> timeit.timeit("'str1 = str2 '.split('=')[1].strip()") 0.97673281637025866 >>> timeit.timeit('import re') 0.65663786250422618 ```
If your data is fixed then you can do this without using regex. Just split it on '='. For example: ``` >>> case1 = "str1=str2" >>> case2 = "str1 = str2" >>> str2 = case1.split('=')[1].strip() >>> str2 = case2.split('=')[1].strip() ``` This `YOURCASE.split('=')[1].strip()` statement will work for any cases.
614,458
How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign * Case 1: `str1=str2` * Case 2: `str1 = str2` please note there can be a **space or none** between the either side of the "=" sign Mine is like this, but only works for one of the cases! ``` m=re.search('(?<=str\s\=\s)\w+','str = str2') ``` returns str2 Help! Gath
2009/03/05
[ "https://Stackoverflow.com/questions/614458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74170/" ]
if you indeed have only such simple strings to parse you don't need regular expression. you can just partition on `=` and strip (or even lstrip) last element of a resulting tuple: ``` >>> case = 'str = str2' >>> case.partition('=')[2].lstrip() 'str2' ``` it'll be much faster than regexps. and just to show how fast i've made a simple test: ``` >>> timeit.timeit("'str1 = str2 '.partition('=')[2].strip()") 0.49051564213846177 >>> timeit.timeit("'str1 = str2 '.split('=')[1].strip()") 0.97673281637025866 >>> timeit.timeit('import re') 0.65663786250422618 ```
Related idea: I find using graphical regular expression tool helpful when trying to figure out correct pattern: <http://kodos.sf.net>.
614,458
How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign * Case 1: `str1=str2` * Case 2: `str1 = str2` please note there can be a **space or none** between the either side of the "=" sign Mine is like this, but only works for one of the cases! ``` m=re.search('(?<=str\s\=\s)\w+','str = str2') ``` returns str2 Help! Gath
2009/03/05
[ "https://Stackoverflow.com/questions/614458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74170/" ]
``` re.search(r'=\s*(.*)', 'str = str2').group(1) ``` or if you just want a single word: ``` re.search(r'=\s*(\w+)', 'str = str2').group(1) ``` Extended to specific initial string: ``` re.search(r'\bstr\s*=\s*(\w+)', 'str=str2').group(1) ``` `\b` = word boundary, so won't match `"somestr=foo"` It would be quicker to go trough all options once, instead of searching for single options one at the time: ``` option_str = "a=b, c=d, g=h" options = dict(re.findall(r'(\w+)\s*=\s*(\w+)', option_str)) options['c'] # -> 'd' ```
Related idea: I find using graphical regular expression tool helpful when trying to figure out correct pattern: <http://kodos.sf.net>.
614,458
How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign * Case 1: `str1=str2` * Case 2: `str1 = str2` please note there can be a **space or none** between the either side of the "=" sign Mine is like this, but only works for one of the cases! ``` m=re.search('(?<=str\s\=\s)\w+','str = str2') ``` returns str2 Help! Gath
2009/03/05
[ "https://Stackoverflow.com/questions/614458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74170/" ]
If your data is fixed then you can do this without using regex. Just split it on '='. For example: ``` >>> case1 = "str1=str2" >>> case2 = "str1 = str2" >>> str2 = case1.split('=')[1].strip() >>> str2 = case2.split('=')[1].strip() ``` This `YOURCASE.split('=')[1].strip()` statement will work for any cases.
Two cases: * (case 1) if there is a single space before the '=', then there **must** also be a single space after the '=' ``` m=re.search(r'(?<=\S)(?:\s=\s|=)(\w+)','str = str2') print m.group(1) ``` * (case 2) otherwise, ``` m=re.search(r'(?<=\S)\s?=\s?(\w+)','str = str2') print m.group(1) ``` In the first case, you could also use the "(?P=…" construct for the second space or lack of it, but it still wouldn't work for a *positive lookbehind assertion*, since it wouldn't be a constant length subexpression.
614,458
How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign * Case 1: `str1=str2` * Case 2: `str1 = str2` please note there can be a **space or none** between the either side of the "=" sign Mine is like this, but only works for one of the cases! ``` m=re.search('(?<=str\s\=\s)\w+','str = str2') ``` returns str2 Help! Gath
2009/03/05
[ "https://Stackoverflow.com/questions/614458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74170/" ]
Simply use split function
Expanding on @batbrat's answer, and the other suggestions, you can use `re.split()` to separate the input string. The pattern can use `\s` (whitespace) or an explicit space. ``` >>> import re >>> c1="str1=str2" >>> c2="str1 = str2" >>> re.split(' ?= ?',c1) ['str1', 'str2'] >>> re.split(' ?= ?',c2) ['str1', 'str2'] >>> re.split(r'\s?=\s?',c1) ['str1', 'str2'] >>> re.split(r'\s?=\s?',c2) ['str1', 'str2'] >>> ```
614,458
How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign * Case 1: `str1=str2` * Case 2: `str1 = str2` please note there can be a **space or none** between the either side of the "=" sign Mine is like this, but only works for one of the cases! ``` m=re.search('(?<=str\s\=\s)\w+','str = str2') ``` returns str2 Help! Gath
2009/03/05
[ "https://Stackoverflow.com/questions/614458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74170/" ]
If your data is fixed then you can do this without using regex. Just split it on '='. For example: ``` >>> case1 = "str1=str2" >>> case2 = "str1 = str2" >>> str2 = case1.split('=')[1].strip() >>> str2 = case2.split('=')[1].strip() ``` This `YOURCASE.split('=')[1].strip()` statement will work for any cases.
Expanding on @batbrat's answer, and the other suggestions, you can use `re.split()` to separate the input string. The pattern can use `\s` (whitespace) or an explicit space. ``` >>> import re >>> c1="str1=str2" >>> c2="str1 = str2" >>> re.split(' ?= ?',c1) ['str1', 'str2'] >>> re.split(' ?= ?',c2) ['str1', 'str2'] >>> re.split(r'\s?=\s?',c1) ['str1', 'str2'] >>> re.split(r'\s?=\s?',c2) ['str1', 'str2'] >>> ```
614,458
How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign * Case 1: `str1=str2` * Case 2: `str1 = str2` please note there can be a **space or none** between the either side of the "=" sign Mine is like this, but only works for one of the cases! ``` m=re.search('(?<=str\s\=\s)\w+','str = str2') ``` returns str2 Help! Gath
2009/03/05
[ "https://Stackoverflow.com/questions/614458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74170/" ]
if you indeed have only such simple strings to parse you don't need regular expression. you can just partition on `=` and strip (or even lstrip) last element of a resulting tuple: ``` >>> case = 'str = str2' >>> case.partition('=')[2].lstrip() 'str2' ``` it'll be much faster than regexps. and just to show how fast i've made a simple test: ``` >>> timeit.timeit("'str1 = str2 '.partition('=')[2].strip()") 0.49051564213846177 >>> timeit.timeit("'str1 = str2 '.split('=')[1].strip()") 0.97673281637025866 >>> timeit.timeit('import re') 0.65663786250422618 ```
Two cases: * (case 1) if there is a single space before the '=', then there **must** also be a single space after the '=' ``` m=re.search(r'(?<=\S)(?:\s=\s|=)(\w+)','str = str2') print m.group(1) ``` * (case 2) otherwise, ``` m=re.search(r'(?<=\S)\s?=\s?(\w+)','str = str2') print m.group(1) ``` In the first case, you could also use the "(?P=…" construct for the second space or lack of it, but it still wouldn't work for a *positive lookbehind assertion*, since it wouldn't be a constant length subexpression.
614,458
How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign * Case 1: `str1=str2` * Case 2: `str1 = str2` please note there can be a **space or none** between the either side of the "=" sign Mine is like this, but only works for one of the cases! ``` m=re.search('(?<=str\s\=\s)\w+','str = str2') ``` returns str2 Help! Gath
2009/03/05
[ "https://Stackoverflow.com/questions/614458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74170/" ]
if you indeed have only such simple strings to parse you don't need regular expression. you can just partition on `=` and strip (or even lstrip) last element of a resulting tuple: ``` >>> case = 'str = str2' >>> case.partition('=')[2].lstrip() 'str2' ``` it'll be much faster than regexps. and just to show how fast i've made a simple test: ``` >>> timeit.timeit("'str1 = str2 '.partition('=')[2].strip()") 0.49051564213846177 >>> timeit.timeit("'str1 = str2 '.split('=')[1].strip()") 0.97673281637025866 >>> timeit.timeit('import re') 0.65663786250422618 ```
I think a regex is overkill if you only want to deal with the above two cases. Here's what I'd do- ``` >>> case1 = "str1=str2" >>> case2 = "str1 = str2" >>> case2.split() ['str1', '=', 'str2'] >>> ''.join(case2.split()) 'str1=str2' >>> case1[5:] 'str2' >>> ''.join(case2.split())[5:] 'str2' >>> ``` **Assumption** -------------- I assume you are looking for the specific token 'str1'. I also assume that str1 can be assigned different values. Something like what you'd have in a configuration file => propertyName = value. This is just my opinion. I knew that other ways were possible! SilentGhost gives a nice (better!) alternative. Hope this helps.
37,974,645
I recently started learning ruby, coming from a background in python. This is one of my first programs above a few lines in length, and I have made a mistake somewhere in the syntax that I cannot catch, that is causing the program to fail with the error "unexpected end-of-output, expected keyword\_end" Here is the code, many thanks for any help! It is a program that converts numbers from digit form into english. ``` def toEnglish number if number < 0 return 'Please try again, negative numbers are not allowed' end if number == 0 return 'Zero' end if number > 0 numEnglish = '' left = number.to_s.size ones = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] tens = ['ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] teens = ['eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] while left.to_i > 0 firstDigit = number.to_s[0].to_i secondDigit = number.to_s[1].to_i sum = (firstDigit.to_i * 10) + secondDigit.to_i if secondDigit != 0 if sum < 20 and sum > 10 numEnglish << teens[sum.to_i - 11] + 'hundred' elsif (sum % 10) == 0 numEnglish << tens[(sum.to_i / 10)].to_s + 'hundred' else numEnglish << tens[(firstDigit.to_i / 10) - 1] + ones[secondDigit - 1] end end numEnglish << ones[firstDigit.to_i - 1] numberRev = number.to_s.reverse number = (numberRev.to_i / 100).to_s.reverse end if left == 0 return numEnglish end end end puts toEnglish(54) puts toEnglish(447) ``` At the moment, the code runs without errors, but I am left with a blinking cursor like the one I would get from the `gets` method.
2016/06/22
[ "https://Stackoverflow.com/questions/37974645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5506705/" ]
One missing `end` after line 35, i.e. at ``` number = (numberRev / 100).reverse # HERE! there should be an `end` if left == 0 return numEnglish ``` In addition, at line 18 and 19 you are asking `number[0]` for the first non-zero digit of `Integer`, while ~~[the class](http://ruby-doc.org/core/Integer.html) does not have a member `#[]`~~ `#[]` in both [Bignum](http://ruby-doc.org/core-2.3.7/Bignum.html#method-i-5B-5D) and [Fixnum](http://ruby-doc.org/core-2.3.7/Fixnum.html#method-i-5B-5D) do not do what you mean. Try something else, for example, `number.to_s[0].to_i`. Note: it is widely accepted to indent with two spaces, not eight.
Some advice: * use two spaces. It's more common and easier to read and spot such errors. * use an editor like Sublime Text or a IDE like RubyMine. ST has several add-ons that facilitate debugging. In this case all I had to do is run a "Beautify-Ruby" on the code and it gave me this output. It looks like you are missing an `end` somewhere. I'm not sure where because there are other errors also, such as line 20 and 34. But, even after fixing these, your code runs forever. The code is surely not Ruby-like, there are far better contructs to be used. For instance, the loop where you can't exit, a `while` is seldom used, rather use an `each` or something similar: ``` def toEnglish number if number < 0 return 'Please try again, negative numbers are not allowed' end if number == 0 return 'Zero' end if number > 0 numEnglish = '' left = number.to_s.size ones = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] tens = ['ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] teens = ['eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] while left.to_i > 0 firstDigit = number[0] secondDigit = number[1] sum = (firstDigit.to_i * 10) + secondDigit+to_i if secondDigit != 0 if sum < 20 and sum > 10 numEnglish << teens[sum.to_i - 11] + 'hundred' elsif (sum % 10) == 0 numEnglish << tens[(sum.to_i / 10)].to_s + 'hundred' else numEnglish << tens[(firstDigit.to_i / 10) - 1] + ones[secondDigit - 1] end end numEnglish << ones[firstDigit.to_i - 1] numberRev = number.reverse number = (numberRev / 100).reverse if left == 0 return numEnglish end end end puts toEnglish(54) puts toEnglish(447) ``` I understand this exercise is to learn Ruby because there are already gems that do this conversion for you. See also "[Using Ruby convert numbers to words?](https://stackoverflow.com/questions/19445003/using-ruby-convert-numbers-to-words)".
70,630,205
I don't know how to get the all total price of the product that the customer bought from my system. the price of each item I can get but the price of all the item that have been choose i can't get the output. I'm using python. Below is my code: ``` #below is the price of products shopping_cart = {} option = 1 while option!= 0: option = int(input("What type of milk you want to purchased: ")) if option == 1: print("coke") qnty = int(input("Enter the quantity: ")) total = qnty*8.49 elif option == 2: print("dutch lady") qnty = int(input("Enter the quantity: ")) total = qnty*8.50 elif option == 3: print("fanta") total = qnty*3.00 elif option == 4: print("Yoghurt") qnty = int(input("Enter the quantity: ")) total = qnty*16.50 elif option == 5: print("pepsi") qnty = int(input("Enter the quantity: ")) total = qnty*18.50 elif option == 6: print("beer") qnty = int(input("Enter the quantity: ")) total = qnty*20.70 else: ("Not found") def totalcart (pr,qnty): #is my code correct here? totalcart = (pr * qny) return total print("The total price in your cart is ", (total)) break print("Come Again") ```
2022/01/08
[ "https://Stackoverflow.com/questions/70630205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Just putting `("Not found")` as a statement doesn't print anything. You need to add your item total into `total_cost` immediately after the print statement. There's no point defining a function, since you don't call the function. So, replace everything after that last "else:" with this: ``` else: total = 0 print("Not found") total_cost += total print("The total price in your cart is RM ", total_cost) print("Please Come Again") ```
You can add `total_cost += total` for every choice, So its added to the total cost when somebody choose the item and if he add another it also adds to the total cost. ```py elif option == 6: print("Foaming Milk") qnty = int(input("Enter the quantity: ")) total = qnty*12.70 print("The price is: " + str(total)) total_cost += total ```
70,630,205
I don't know how to get the all total price of the product that the customer bought from my system. the price of each item I can get but the price of all the item that have been choose i can't get the output. I'm using python. Below is my code: ``` #below is the price of products shopping_cart = {} option = 1 while option!= 0: option = int(input("What type of milk you want to purchased: ")) if option == 1: print("coke") qnty = int(input("Enter the quantity: ")) total = qnty*8.49 elif option == 2: print("dutch lady") qnty = int(input("Enter the quantity: ")) total = qnty*8.50 elif option == 3: print("fanta") total = qnty*3.00 elif option == 4: print("Yoghurt") qnty = int(input("Enter the quantity: ")) total = qnty*16.50 elif option == 5: print("pepsi") qnty = int(input("Enter the quantity: ")) total = qnty*18.50 elif option == 6: print("beer") qnty = int(input("Enter the quantity: ")) total = qnty*20.70 else: ("Not found") def totalcart (pr,qnty): #is my code correct here? totalcart = (pr * qny) return total print("The total price in your cart is ", (total)) break print("Come Again") ```
2022/01/08
[ "https://Stackoverflow.com/questions/70630205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Just putting `("Not found")` as a statement doesn't print anything. You need to add your item total into `total_cost` immediately after the print statement. There's no point defining a function, since you don't call the function. So, replace everything after that last "else:" with this: ``` else: total = 0 print("Not found") total_cost += total print("The total price in your cart is RM ", total_cost) print("Please Come Again") ```
1. You basically have the same couple lines for every option 2. You dont save your values You can try this: ``` items = { "UHT Milk" : 6.49, "Pasteurised Milk" : 5.50, "Sterilised Milk" : 4.00, "Eating and Drinking Yoghurt" : 10.50, "Full Cream Milk" : 15.50, "Foaming Milk" :12.70 } shopping_cart = {} total_cost = 0 while True: option = int(input("What type of milk you want to purchase: ")) if option == 0: break elif option == 1: milk = "UHT Milk" elif option == 2: milk = "Pasteurised Milk" elif option == 3: milk = "Sterilised Milk" elif option == 4: milk = "Eating and Drinking Yoghurt" elif option == 5: milk = "Full Cream Milk" elif option == 6: milk = "Foaming Milk" else: print("Not found") continue print(milk) qnty = int(input("Enter the quantity: ")) shopping_cart[milk] = qnty total = qnty*items[milk] total_cost += total print("The price for this product(s) is: " + str(total)) print('The total price is: %.2f' % total_cost) print("\nThe total price in your cart is %.2f " % total_cost) print("Please Come Again") ``` also you already had the dictionary with names and prices but didnt use it. just get the price from the items dictionary, but make sure that the name is the same as the option or else you get a KeyError. Since Python 3.10 you could also use match case if you like that a bit more. just replace all elif's with this: ``` match option: case 1: milk = "UHT Milk" case 2: milk = "Pasteurised Milk" case 3: milk = "Sterilised Milk" case 4: milk = "Eating and Drinking Yoghurt" case 5: milk = "Full Cream Milk" case 6: milk = "Foaming Milk" case _: print("Not found") continue ```
65,797,818
I'm trying to understand regex and i have an error message. I don't understand this message because I don't use list. If I use just print(number) it doesn't delete the [ ] of the result. The goal is to obtain only the number in the sentence as result. I use python 3.6. Below my code: ``` import re user_sentence = input(">>> : ") while user_sentence != "quit": if re.findall("[0-9]+", user_sentence): number = re.findall("[0-9]+", user_sentence) print(number.group()) user_sentence = input(">>> : ") else: print("no") user_sentence = input(">>> : ") ```
2021/01/19
[ "https://Stackoverflow.com/questions/65797818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15039238/" ]
`groups()` (with an `s`) is on the return value of a `re.match`, not a `findall`. If you're looking to print each item in the list returned by a findall, you can print use `join` to join them on a space, or loop over the list. Note that the list may include tuples though (not in your case, but in general). Example of joining them on a space: ```py import re user_sentence = input(">>> : ") while user_sentence != "quit": if re.findall("[0-9]+", user_sentence): number = re.findall("[0-9]+", user_sentence) print(" ".join(number)) user_sentence = input(">>> : ") else: print("no") user_sentence = input(">>> : ") ``` Or by looping over and printing: ```py for n in number: print(n) ```
findall returns list type by default and list does not have any such method/attribute. If you try to running print (number), you see a list as the output. But to convert the list elements into number you can add these lines after you have evaluated number ``` number = re.findall("[0-9]+", user_sentence) #add these lines for num in number : result = result + str(num) print (int(result)) ```
65,797,818
I'm trying to understand regex and i have an error message. I don't understand this message because I don't use list. If I use just print(number) it doesn't delete the [ ] of the result. The goal is to obtain only the number in the sentence as result. I use python 3.6. Below my code: ``` import re user_sentence = input(">>> : ") while user_sentence != "quit": if re.findall("[0-9]+", user_sentence): number = re.findall("[0-9]+", user_sentence) print(number.group()) user_sentence = input(">>> : ") else: print("no") user_sentence = input(">>> : ") ```
2021/01/19
[ "https://Stackoverflow.com/questions/65797818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15039238/" ]
Why are you running `re.findall` twice ? Your code should be like this: ```py import re user_sentence = input(">>> : ") while user_sentence != "quit": numbers = re.findall("[0-9]+", user_sentence) if numbers: print("found numbers " + " ".join(numbers)) user_sentence = input(">>> : ") else: print("no numbers found") user_sentence = input(">>> : ") ```
findall returns list type by default and list does not have any such method/attribute. If you try to running print (number), you see a list as the output. But to convert the list elements into number you can add these lines after you have evaluated number ``` number = re.findall("[0-9]+", user_sentence) #add these lines for num in number : result = result + str(num) print (int(result)) ```
29,802,931
I have a csv file of customer ids (`CRM_id`). I need to get their primary keys (an autoincrement int) from the customers table of the database. (I can't be assured of the integrity of the `CRM_id`s so I chose not to make that the primary key). So: ``` customers = [] with open("CRM_ids.csv", 'r', newline='') as csvfile: customerfile = csv.DictReader(csvfile, delimiter = ',', quotechar='"', skipinitialspace=True) #only one "CRM_id" field per row customers = [c for c in customerfile] ``` So far so good? I think this is the most pythonesque way of doing that (but happy to hear otherwise). Now comes the ugly code. It works, but I hate appending to the list because that has to copy and reallocate memory for each loop, right? Is there a better way (pre-allocate + enumerate to keep track of the index comes to mind, but maybe there's an even quickler/better way by being clever with the SQL so as not to do several thousand separate queries...)? ``` cnx = mysql.connector.connect(user='me', password=sys.argv[1], host="localhost", database="mydb") cursor = cnx.cursor() select_customer = ("SELECT id FROM customers WHERE CRM_id = %(CRM_id)s LIMIT 1;") c_ids = [] for row in customers: cursor.execute(select_customer, row) #note fetchone() returns a tuple, but the SELECTed set #only has a single column so we need to get this column with the [0] c_ids.extend(cursor.fetchall()) c_ids = [c[0] for c in c_ids] ``` Edit: Purpose is to get the primary keys in a list so I can use these to allocate some other data from other CSV files in linked tables (the customer id primary key is a foreign key to these other tables, and the allocation algorithm changes, so it's best to have the flexibility to do the allocation in python rather than hard coding SQL queries). I know this sounds a little backwards, but the "client" only works with spreadsheets rather than an ERP/PLM, so I have to build the "relations" for this small app myself.
2015/04/22
[ "https://Stackoverflow.com/questions/29802931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3790954/" ]
What about changing your query to get what you want? ``` crm_ids = ",".join(customers) select_customer = "SELECT UNIQUE id FROM customers WHERE CRM_id IN (%s);" % crm_ids ``` MySQL should be fine with even a multi-megabyte query, according to [the manual](http://dev.mysql.com/doc/refman/5.0/en/packet-too-large.html); if it gets to be a *really* long list, you can always break it up - two or three queries is guaranteed much faster than a few thousand.
how about storing your csv in a dict instead of a list: ``` customers = [c for c in customerfile] ``` becomes: ``` customers = {c['CRM_id']:c for c in customerfile} ``` then select the entire xref: ``` result = cursor.execute('select id, CRM_id from customers') ``` and add the new rowid as a new entry in the dict: ``` for row in result: customers[row[1]]['newid']=row[0] ```
55,351,039
There is an excel file logging a set of data. Its columns are as below, where each column is seperated by comma. ``` SampleData year,date,month,location,time,count 2019,20,Jan,Japan,22:33,1 2019,31,Jan,Japan,19:21,1 2019,1,Jan,Japan,8:00,1 2019,4,Jan,Japan,4:28,2 2019,13,Feb,Japan,6:19,1 ``` From this data, I would like to create python pandas dataframe, which looks like below. ``` DataFrame u_datetime,location,count 1547991180,Japan,1 1548930060,Japan,1 1546297200,Japan,1 1546543680,Japan,2 1550006340,Japan,1 ``` One of the DataFrame methods can be useful for this operation, but it does not take date with one digit. ``` pandas.to_datetime( DataFrame["year"].astype(str) + DataFrame["month"].astype(str) + DataFrame["date"].astype(str) + DataFrame["time"].astype(str), format="%Y%b%d%-H%M" ) ``` Could anybody give me a hand? Thank you.
2019/03/26
[ "https://Stackoverflow.com/questions/55351039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11258673/" ]
try this ``` from datetime import datetime data['datetime'] = data[['year','date','month','time']].apply(lambda x: datetime.strptime(str(x['year'])+'-'+str(x['date'])+'-'+str(x['month'])+' '+str(x['time']), "%Y-%d-%b %H:%M").timestamp(), axis=1) data[['datetime','location','count']] ``` **Output** ​ ``` datetime \ 0 1548003780.0 1 1548942660.0 2 1546309800.0 3 1546556280.0 4 1550018940.0 location \ 0 Japan 1 Japan 2 Japan 3 Japan 4 Japan count 0 1 1 1 2 1 3 2 4 1 ```
You are close, need `%Y%b%d%H:%M` format and then convert to unix time by cast to `int64` with integer division by `10**9`: ``` s = (DataFrame["year"].astype(str)+ DataFrame["month"].astype(str)+ DataFrame["date"].astype(str)+ DataFrame["time"].astype(str)) DataFrame['u_datetime'] = pd.to_datetime(s, format="%Y%b%d%H:%M").astype(np.int64) // 10**9 DataFrame = DataFrame[['u_datetime','location','count']] print (DataFrame) u_datetime location count 0 1548023580 Japan 1 1 1548962460 Japan 1 2 1546329600 Japan 1 3 1546576080 Japan 2 4 1550038740 Japan 1 ```
55,351,039
There is an excel file logging a set of data. Its columns are as below, where each column is seperated by comma. ``` SampleData year,date,month,location,time,count 2019,20,Jan,Japan,22:33,1 2019,31,Jan,Japan,19:21,1 2019,1,Jan,Japan,8:00,1 2019,4,Jan,Japan,4:28,2 2019,13,Feb,Japan,6:19,1 ``` From this data, I would like to create python pandas dataframe, which looks like below. ``` DataFrame u_datetime,location,count 1547991180,Japan,1 1548930060,Japan,1 1546297200,Japan,1 1546543680,Japan,2 1550006340,Japan,1 ``` One of the DataFrame methods can be useful for this operation, but it does not take date with one digit. ``` pandas.to_datetime( DataFrame["year"].astype(str) + DataFrame["month"].astype(str) + DataFrame["date"].astype(str) + DataFrame["time"].astype(str), format="%Y%b%d%-H%M" ) ``` Could anybody give me a hand? Thank you.
2019/03/26
[ "https://Stackoverflow.com/questions/55351039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11258673/" ]
In case you are working with csv file this can be done easily using [parse\_dates](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#csv-text-files). ``` dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S') df = pd.read_csv('/home/users/user/xxx.csv', parse_dates ={'date_time':[0,1,2,4]}) df['u_datetime'] = df['date_time'].values.astype(np.int64) // 10 ** 9 df_new = df[['u_datetime', 'location', 'count']] ```
You are close, need `%Y%b%d%H:%M` format and then convert to unix time by cast to `int64` with integer division by `10**9`: ``` s = (DataFrame["year"].astype(str)+ DataFrame["month"].astype(str)+ DataFrame["date"].astype(str)+ DataFrame["time"].astype(str)) DataFrame['u_datetime'] = pd.to_datetime(s, format="%Y%b%d%H:%M").astype(np.int64) // 10**9 DataFrame = DataFrame[['u_datetime','location','count']] print (DataFrame) u_datetime location count 0 1548023580 Japan 1 1 1548962460 Japan 1 2 1546329600 Japan 1 3 1546576080 Japan 2 4 1550038740 Japan 1 ```
5,195,295
I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg: ``` reader = csv.reader(open("file.csv", "rb")) ``` I'd like this to become an information provided by the user. Is this done using raw\_input or is there a way to do it by having the user writing something in the lines of: ``` python testfile.py --input:file.csv ``` Appreciate your help in advance!
2011/03/04
[ "https://Stackoverflow.com/questions/5195295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/644926/" ]
The simplest way is to write your script like this: ``` import sys reader = csv.reader(open(sys.argv[1], "rb")) ``` and then run it like this: ``` python testfile.py file.csv ``` You should put in some error checking, eg: ``` if len(sys.argv) < 2: print "Usage..." sys.exit(1) ``` For more power, use the bult in `optparse` / `argparse` library.
You can use [optparse](http://docs.python.org/library/optparse.html) ([argparse](http://docs.python.org/library/argparse.html#module-argparse) after 2.7) or [getopt](http://docs.python.org/library/getopt.html) to parse command line parameters. Only use getopt if you're already familiar with argument parsing in C. Otherwise argparse is the easiest to use.
5,195,295
I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg: ``` reader = csv.reader(open("file.csv", "rb")) ``` I'd like this to become an information provided by the user. Is this done using raw\_input or is there a way to do it by having the user writing something in the lines of: ``` python testfile.py --input:file.csv ``` Appreciate your help in advance!
2011/03/04
[ "https://Stackoverflow.com/questions/5195295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/644926/" ]
The simplest way is to write your script like this: ``` import sys reader = csv.reader(open(sys.argv[1], "rb")) ``` and then run it like this: ``` python testfile.py file.csv ``` You should put in some error checking, eg: ``` if len(sys.argv) < 2: print "Usage..." sys.exit(1) ``` For more power, use the bult in `optparse` / `argparse` library.
Maybe the *argparse* python module fits your depends: <http://docs.python.org/library/argparse.html> The old *optparse* is deprecated.
5,195,295
I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg: ``` reader = csv.reader(open("file.csv", "rb")) ``` I'd like this to become an information provided by the user. Is this done using raw\_input or is there a way to do it by having the user writing something in the lines of: ``` python testfile.py --input:file.csv ``` Appreciate your help in advance!
2011/03/04
[ "https://Stackoverflow.com/questions/5195295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/644926/" ]
The simplest way is to write your script like this: ``` import sys reader = csv.reader(open(sys.argv[1], "rb")) ``` and then run it like this: ``` python testfile.py file.csv ``` You should put in some error checking, eg: ``` if len(sys.argv) < 2: print "Usage..." sys.exit(1) ``` For more power, use the bult in `optparse` / `argparse` library.
You can access `sys.argv` which is an array of the inputs. But keep in mind that the first argument is the actual program itself.
5,195,295
I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg: ``` reader = csv.reader(open("file.csv", "rb")) ``` I'd like this to become an information provided by the user. Is this done using raw\_input or is there a way to do it by having the user writing something in the lines of: ``` python testfile.py --input:file.csv ``` Appreciate your help in advance!
2011/03/04
[ "https://Stackoverflow.com/questions/5195295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/644926/" ]
You can use [optparse](http://docs.python.org/library/optparse.html) ([argparse](http://docs.python.org/library/argparse.html#module-argparse) after 2.7) or [getopt](http://docs.python.org/library/getopt.html) to parse command line parameters. Only use getopt if you're already familiar with argument parsing in C. Otherwise argparse is the easiest to use.
Maybe the *argparse* python module fits your depends: <http://docs.python.org/library/argparse.html> The old *optparse* is deprecated.
5,195,295
I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg: ``` reader = csv.reader(open("file.csv", "rb")) ``` I'd like this to become an information provided by the user. Is this done using raw\_input or is there a way to do it by having the user writing something in the lines of: ``` python testfile.py --input:file.csv ``` Appreciate your help in advance!
2011/03/04
[ "https://Stackoverflow.com/questions/5195295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/644926/" ]
You can use [optparse](http://docs.python.org/library/optparse.html) ([argparse](http://docs.python.org/library/argparse.html#module-argparse) after 2.7) or [getopt](http://docs.python.org/library/getopt.html) to parse command line parameters. Only use getopt if you're already familiar with argument parsing in C. Otherwise argparse is the easiest to use.
You can access `sys.argv` which is an array of the inputs. But keep in mind that the first argument is the actual program itself.
5,195,295
I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg: ``` reader = csv.reader(open("file.csv", "rb")) ``` I'd like this to become an information provided by the user. Is this done using raw\_input or is there a way to do it by having the user writing something in the lines of: ``` python testfile.py --input:file.csv ``` Appreciate your help in advance!
2011/03/04
[ "https://Stackoverflow.com/questions/5195295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/644926/" ]
For reference the optparse (http://docs.python.org/library/optparse.html) version would look something like this. ``` import optparse parser = optparse.OptionParser() parser.add_option("-i","--input",dest="filename") (options,args) = parser.parse_args() thefile = options.filename reader = csv.reader(thefile,"rb") ``` Which would let you call either ``` python script.py -i foo.dat python script.py --input foo.dat ```
You can use [optparse](http://docs.python.org/library/optparse.html) ([argparse](http://docs.python.org/library/argparse.html#module-argparse) after 2.7) or [getopt](http://docs.python.org/library/getopt.html) to parse command line parameters. Only use getopt if you're already familiar with argument parsing in C. Otherwise argparse is the easiest to use.
5,195,295
I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg: ``` reader = csv.reader(open("file.csv", "rb")) ``` I'd like this to become an information provided by the user. Is this done using raw\_input or is there a way to do it by having the user writing something in the lines of: ``` python testfile.py --input:file.csv ``` Appreciate your help in advance!
2011/03/04
[ "https://Stackoverflow.com/questions/5195295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/644926/" ]
For reference the optparse (http://docs.python.org/library/optparse.html) version would look something like this. ``` import optparse parser = optparse.OptionParser() parser.add_option("-i","--input",dest="filename") (options,args) = parser.parse_args() thefile = options.filename reader = csv.reader(thefile,"rb") ``` Which would let you call either ``` python script.py -i foo.dat python script.py --input foo.dat ```
Maybe the *argparse* python module fits your depends: <http://docs.python.org/library/argparse.html> The old *optparse* is deprecated.
5,195,295
I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg: ``` reader = csv.reader(open("file.csv", "rb")) ``` I'd like this to become an information provided by the user. Is this done using raw\_input or is there a way to do it by having the user writing something in the lines of: ``` python testfile.py --input:file.csv ``` Appreciate your help in advance!
2011/03/04
[ "https://Stackoverflow.com/questions/5195295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/644926/" ]
For reference the optparse (http://docs.python.org/library/optparse.html) version would look something like this. ``` import optparse parser = optparse.OptionParser() parser.add_option("-i","--input",dest="filename") (options,args) = parser.parse_args() thefile = options.filename reader = csv.reader(thefile,"rb") ``` Which would let you call either ``` python script.py -i foo.dat python script.py --input foo.dat ```
You can access `sys.argv` which is an array of the inputs. But keep in mind that the first argument is the actual program itself.
11,724,779
I am trying to install a local version of ScrumDo for testing. Only then I come to the point in my installation that I have to run: > > source bin/activate > > pip install -r requirements.txt > > > I get the error: > > Downloading/unpacking django-storages > > > > > > > Cannot fetch index base URL http : //b.pypi.python.org/simple/ > > > > Could not find any downloads that satisfy the requirement django-storages > > > > > > > > > No distributions at all found for django-storages > > Storing complete log in ./pip-log.txt > > > > I googled a bit and search here and on Stack Overflow and found that I should add a --proxy= option and/or unset my http\_proxy environment variable. Yet my install does not have a proxy and the environment var is not set. I tried running > > pip install -r requirements.txt --proxy= > > > Yet the error remains the same. I also created a /root/.pip/pip.conf containing: > > [global] > > index-url = http : //b.pypi.python.org/simple > > > and checked it the server actually was online and if the package django-storages existed, this was both true. a last thing I tried, since the [install doc of ScrumDo](https://github.com/ScrumDoLLC/ScrumDo/wiki/Set-up) says so: > > pip install -U Django==1.1.4 > > > yet again no succes... the error always remains the same, any one got any Ideas? my pip-error.log shows the following (the URL works in firefox on a different machine in the same network that also uses no proxy, and I can ping it from the same machine): ``` /var/www/ScrumDo/pinax-env/bin/pip run on Mon Jul 30 10:24:08 2012 proxy): Downloading/unpacking Django==1.1.4 proxy): Getting page http://b.pypi.python.org/simple/Django proxy): Could not fetch URL http://b.pypi.python.org/simple/Django: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/Django when looking for download links for Django==1.1.4 proxy): Getting page http://b.pypi.python.org/simple/ proxy): Could not fetch URL http://b.pypi.python.org/simple/: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/ when looking for download links for Django==1.1.4 proxy): Cannot fetch index base URL http://b.pypi.python.org/simple/ proxy): URLs to search for versions for Django==1.1.4: proxy): * http://b.pypi.python.org/simple/Django/1.1.4 proxy): * http://b.pypi.python.org/simple/Django/ proxy): Getting page http://b.pypi.python.org/simple/Django/1.1.4 proxy): Getting page http://b.pypi.python.org/simple/Django/ proxy): Could not fetch URL http://b.pypi.python.org/simple/Django/1.1.4: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/Django/1.1.4 when looking for download links for Django==1.1.4 proxy): Could not fetch URL http://b.pypi.python.org/simple/Django/: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/Django/ when looking for download links for Django==1.1.4 proxy): Could not find any downloads that satisfy the requirement Django==1.1.4 No distributions at all found for Django==1.1.4 proxy): Exception information: proxy): Traceback (most recent call last): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 482, in main proxy): self.run(options, args) proxy): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 675, in run proxy): requirement_set.install_files(finder, force_root_egg_info=self.bundle) proxy): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 2422, in install_files proxy): url = finder.find_requirement(req_to_install, upgrade=self.upgrade) proxy): proxy): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 1485, in find_requirement proxy): proxy): raise DistributionNotFound('No distributions at all found for %s' % req) proxy): proxy): DistributionNotFound: No distributions at all found for Django==1.1.4 ```
2012/07/30
[ "https://Stackoverflow.com/questions/11724779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1411141/" ]
You can try installing django-storages on its own.. try this? ``` sudo pip install https://bitbucket.org/david/django-storages/get/def732408163.zip ```
Try giving the proxy settings in the command as such ``` pip --proxy=http://user:password@Proxy:PortNumber install -r requirements.txt ``` or try ``` export http_proxy=http://user:password@Proxy:PortNumber ```
11,724,779
I am trying to install a local version of ScrumDo for testing. Only then I come to the point in my installation that I have to run: > > source bin/activate > > pip install -r requirements.txt > > > I get the error: > > Downloading/unpacking django-storages > > > > > > > Cannot fetch index base URL http : //b.pypi.python.org/simple/ > > > > Could not find any downloads that satisfy the requirement django-storages > > > > > > > > > No distributions at all found for django-storages > > Storing complete log in ./pip-log.txt > > > > I googled a bit and search here and on Stack Overflow and found that I should add a --proxy= option and/or unset my http\_proxy environment variable. Yet my install does not have a proxy and the environment var is not set. I tried running > > pip install -r requirements.txt --proxy= > > > Yet the error remains the same. I also created a /root/.pip/pip.conf containing: > > [global] > > index-url = http : //b.pypi.python.org/simple > > > and checked it the server actually was online and if the package django-storages existed, this was both true. a last thing I tried, since the [install doc of ScrumDo](https://github.com/ScrumDoLLC/ScrumDo/wiki/Set-up) says so: > > pip install -U Django==1.1.4 > > > yet again no succes... the error always remains the same, any one got any Ideas? my pip-error.log shows the following (the URL works in firefox on a different machine in the same network that also uses no proxy, and I can ping it from the same machine): ``` /var/www/ScrumDo/pinax-env/bin/pip run on Mon Jul 30 10:24:08 2012 proxy): Downloading/unpacking Django==1.1.4 proxy): Getting page http://b.pypi.python.org/simple/Django proxy): Could not fetch URL http://b.pypi.python.org/simple/Django: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/Django when looking for download links for Django==1.1.4 proxy): Getting page http://b.pypi.python.org/simple/ proxy): Could not fetch URL http://b.pypi.python.org/simple/: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/ when looking for download links for Django==1.1.4 proxy): Cannot fetch index base URL http://b.pypi.python.org/simple/ proxy): URLs to search for versions for Django==1.1.4: proxy): * http://b.pypi.python.org/simple/Django/1.1.4 proxy): * http://b.pypi.python.org/simple/Django/ proxy): Getting page http://b.pypi.python.org/simple/Django/1.1.4 proxy): Getting page http://b.pypi.python.org/simple/Django/ proxy): Could not fetch URL http://b.pypi.python.org/simple/Django/1.1.4: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/Django/1.1.4 when looking for download links for Django==1.1.4 proxy): Could not fetch URL http://b.pypi.python.org/simple/Django/: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/Django/ when looking for download links for Django==1.1.4 proxy): Could not find any downloads that satisfy the requirement Django==1.1.4 No distributions at all found for Django==1.1.4 proxy): Exception information: proxy): Traceback (most recent call last): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 482, in main proxy): self.run(options, args) proxy): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 675, in run proxy): requirement_set.install_files(finder, force_root_egg_info=self.bundle) proxy): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 2422, in install_files proxy): url = finder.find_requirement(req_to_install, upgrade=self.upgrade) proxy): proxy): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 1485, in find_requirement proxy): proxy): raise DistributionNotFound('No distributions at all found for %s' % req) proxy): proxy): DistributionNotFound: No distributions at all found for Django==1.1.4 ```
2012/07/30
[ "https://Stackoverflow.com/questions/11724779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1411141/" ]
You can try installing django-storages on its own.. try this? ``` sudo pip install https://bitbucket.org/david/django-storages/get/def732408163.zip ```
This problem is most-likely caused by DNS setup: server cannot resolve the Domain Name, so cannot download the package. Solution: sudo nano /etc/network/interface add a line: dns-nameservers 8.8.8.8 save file and exit ``` sudo ifdown eth0 && sudo ifup eth0 ``` Then pip install should be working now.
11,724,779
I am trying to install a local version of ScrumDo for testing. Only then I come to the point in my installation that I have to run: > > source bin/activate > > pip install -r requirements.txt > > > I get the error: > > Downloading/unpacking django-storages > > > > > > > Cannot fetch index base URL http : //b.pypi.python.org/simple/ > > > > Could not find any downloads that satisfy the requirement django-storages > > > > > > > > > No distributions at all found for django-storages > > Storing complete log in ./pip-log.txt > > > > I googled a bit and search here and on Stack Overflow and found that I should add a --proxy= option and/or unset my http\_proxy environment variable. Yet my install does not have a proxy and the environment var is not set. I tried running > > pip install -r requirements.txt --proxy= > > > Yet the error remains the same. I also created a /root/.pip/pip.conf containing: > > [global] > > index-url = http : //b.pypi.python.org/simple > > > and checked it the server actually was online and if the package django-storages existed, this was both true. a last thing I tried, since the [install doc of ScrumDo](https://github.com/ScrumDoLLC/ScrumDo/wiki/Set-up) says so: > > pip install -U Django==1.1.4 > > > yet again no succes... the error always remains the same, any one got any Ideas? my pip-error.log shows the following (the URL works in firefox on a different machine in the same network that also uses no proxy, and I can ping it from the same machine): ``` /var/www/ScrumDo/pinax-env/bin/pip run on Mon Jul 30 10:24:08 2012 proxy): Downloading/unpacking Django==1.1.4 proxy): Getting page http://b.pypi.python.org/simple/Django proxy): Could not fetch URL http://b.pypi.python.org/simple/Django: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/Django when looking for download links for Django==1.1.4 proxy): Getting page http://b.pypi.python.org/simple/ proxy): Could not fetch URL http://b.pypi.python.org/simple/: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/ when looking for download links for Django==1.1.4 proxy): Cannot fetch index base URL http://b.pypi.python.org/simple/ proxy): URLs to search for versions for Django==1.1.4: proxy): * http://b.pypi.python.org/simple/Django/1.1.4 proxy): * http://b.pypi.python.org/simple/Django/ proxy): Getting page http://b.pypi.python.org/simple/Django/1.1.4 proxy): Getting page http://b.pypi.python.org/simple/Django/ proxy): Could not fetch URL http://b.pypi.python.org/simple/Django/1.1.4: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/Django/1.1.4 when looking for download links for Django==1.1.4 proxy): Could not fetch URL http://b.pypi.python.org/simple/Django/: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/Django/ when looking for download links for Django==1.1.4 proxy): Could not find any downloads that satisfy the requirement Django==1.1.4 No distributions at all found for Django==1.1.4 proxy): Exception information: proxy): Traceback (most recent call last): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 482, in main proxy): self.run(options, args) proxy): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 675, in run proxy): requirement_set.install_files(finder, force_root_egg_info=self.bundle) proxy): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 2422, in install_files proxy): url = finder.find_requirement(req_to_install, upgrade=self.upgrade) proxy): proxy): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 1485, in find_requirement proxy): proxy): raise DistributionNotFound('No distributions at all found for %s' % req) proxy): proxy): DistributionNotFound: No distributions at all found for Django==1.1.4 ```
2012/07/30
[ "https://Stackoverflow.com/questions/11724779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1411141/" ]
If you've tried installing a package with pip recently, you may have encountered this error: ``` Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm> Will skip URL https://pypi.python.org/simple/Django/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1)) Could not fetch URL https://pypi.python.org/simple/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm> Will skip URL https://pypi.python.org/simple/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1)) Cannot fetch index base URL https://pypi.python.org/simple/ Could not fetch URL https://pypi.python.org/simple/Django/1.5.1: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm> Will skip URL https://pypi.python.org/simple/Django/1.5.1 when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1)) Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm> Will skip URL https://pypi.python.org/simple/Django/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1)) Could not find any downloads that satisfy the requirement Django==1.5.1 (from -r requirements.txt (line 1)) No distributions at all found for Django==1.5.1 (from -r requirements.txt (line 1)) Storing complete log in /Users/paul/.pip/pip.log ``` This seems to be an issue with an old version of OpenSSL being incompatible with pip 1.3.1. If you're using a non-stock Python distribution (notably EPD 7.3), you're very likely to have a setup that isn't going to work with pip 1.3.1 without a shitload of work. The easy workaround for now, is to install pip 1.2.1, which does not require SSL: ``` curl -o https://pypi.python.org/packages/source/p/pip/pip-1.2.1.tar.gz tar xvfz pip-1.2.1.tar.gz cd pip-1.2.1 python setup.py install ``` If you are using EPD, and you're not using it for a class where things might break, you may want to consider installing the new incarnation: Enthought Canopy. I know they were aware of the issues caused by the previous version of OpenSSL, and would imagine they are using a new version now that should play nicely with pip 1.3.1.
Try giving the proxy settings in the command as such ``` pip --proxy=http://user:password@Proxy:PortNumber install -r requirements.txt ``` or try ``` export http_proxy=http://user:password@Proxy:PortNumber ```
11,724,779
I am trying to install a local version of ScrumDo for testing. Only then I come to the point in my installation that I have to run: > > source bin/activate > > pip install -r requirements.txt > > > I get the error: > > Downloading/unpacking django-storages > > > > > > > Cannot fetch index base URL http : //b.pypi.python.org/simple/ > > > > Could not find any downloads that satisfy the requirement django-storages > > > > > > > > > No distributions at all found for django-storages > > Storing complete log in ./pip-log.txt > > > > I googled a bit and search here and on Stack Overflow and found that I should add a --proxy= option and/or unset my http\_proxy environment variable. Yet my install does not have a proxy and the environment var is not set. I tried running > > pip install -r requirements.txt --proxy= > > > Yet the error remains the same. I also created a /root/.pip/pip.conf containing: > > [global] > > index-url = http : //b.pypi.python.org/simple > > > and checked it the server actually was online and if the package django-storages existed, this was both true. a last thing I tried, since the [install doc of ScrumDo](https://github.com/ScrumDoLLC/ScrumDo/wiki/Set-up) says so: > > pip install -U Django==1.1.4 > > > yet again no succes... the error always remains the same, any one got any Ideas? my pip-error.log shows the following (the URL works in firefox on a different machine in the same network that also uses no proxy, and I can ping it from the same machine): ``` /var/www/ScrumDo/pinax-env/bin/pip run on Mon Jul 30 10:24:08 2012 proxy): Downloading/unpacking Django==1.1.4 proxy): Getting page http://b.pypi.python.org/simple/Django proxy): Could not fetch URL http://b.pypi.python.org/simple/Django: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/Django when looking for download links for Django==1.1.4 proxy): Getting page http://b.pypi.python.org/simple/ proxy): Could not fetch URL http://b.pypi.python.org/simple/: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/ when looking for download links for Django==1.1.4 proxy): Cannot fetch index base URL http://b.pypi.python.org/simple/ proxy): URLs to search for versions for Django==1.1.4: proxy): * http://b.pypi.python.org/simple/Django/1.1.4 proxy): * http://b.pypi.python.org/simple/Django/ proxy): Getting page http://b.pypi.python.org/simple/Django/1.1.4 proxy): Getting page http://b.pypi.python.org/simple/Django/ proxy): Could not fetch URL http://b.pypi.python.org/simple/Django/1.1.4: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/Django/1.1.4 when looking for download links for Django==1.1.4 proxy): Could not fetch URL http://b.pypi.python.org/simple/Django/: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/Django/ when looking for download links for Django==1.1.4 proxy): Could not find any downloads that satisfy the requirement Django==1.1.4 No distributions at all found for Django==1.1.4 proxy): Exception information: proxy): Traceback (most recent call last): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 482, in main proxy): self.run(options, args) proxy): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 675, in run proxy): requirement_set.install_files(finder, force_root_egg_info=self.bundle) proxy): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 2422, in install_files proxy): url = finder.find_requirement(req_to_install, upgrade=self.upgrade) proxy): proxy): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 1485, in find_requirement proxy): proxy): raise DistributionNotFound('No distributions at all found for %s' % req) proxy): proxy): DistributionNotFound: No distributions at all found for Django==1.1.4 ```
2012/07/30
[ "https://Stackoverflow.com/questions/11724779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1411141/" ]
Try giving the proxy settings in the command as such ``` pip --proxy=http://user:password@Proxy:PortNumber install -r requirements.txt ``` or try ``` export http_proxy=http://user:password@Proxy:PortNumber ```
This problem is most-likely caused by DNS setup: server cannot resolve the Domain Name, so cannot download the package. Solution: sudo nano /etc/network/interface add a line: dns-nameservers 8.8.8.8 save file and exit ``` sudo ifdown eth0 && sudo ifup eth0 ``` Then pip install should be working now.
11,724,779
I am trying to install a local version of ScrumDo for testing. Only then I come to the point in my installation that I have to run: > > source bin/activate > > pip install -r requirements.txt > > > I get the error: > > Downloading/unpacking django-storages > > > > > > > Cannot fetch index base URL http : //b.pypi.python.org/simple/ > > > > Could not find any downloads that satisfy the requirement django-storages > > > > > > > > > No distributions at all found for django-storages > > Storing complete log in ./pip-log.txt > > > > I googled a bit and search here and on Stack Overflow and found that I should add a --proxy= option and/or unset my http\_proxy environment variable. Yet my install does not have a proxy and the environment var is not set. I tried running > > pip install -r requirements.txt --proxy= > > > Yet the error remains the same. I also created a /root/.pip/pip.conf containing: > > [global] > > index-url = http : //b.pypi.python.org/simple > > > and checked it the server actually was online and if the package django-storages existed, this was both true. a last thing I tried, since the [install doc of ScrumDo](https://github.com/ScrumDoLLC/ScrumDo/wiki/Set-up) says so: > > pip install -U Django==1.1.4 > > > yet again no succes... the error always remains the same, any one got any Ideas? my pip-error.log shows the following (the URL works in firefox on a different machine in the same network that also uses no proxy, and I can ping it from the same machine): ``` /var/www/ScrumDo/pinax-env/bin/pip run on Mon Jul 30 10:24:08 2012 proxy): Downloading/unpacking Django==1.1.4 proxy): Getting page http://b.pypi.python.org/simple/Django proxy): Could not fetch URL http://b.pypi.python.org/simple/Django: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/Django when looking for download links for Django==1.1.4 proxy): Getting page http://b.pypi.python.org/simple/ proxy): Could not fetch URL http://b.pypi.python.org/simple/: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/ when looking for download links for Django==1.1.4 proxy): Cannot fetch index base URL http://b.pypi.python.org/simple/ proxy): URLs to search for versions for Django==1.1.4: proxy): * http://b.pypi.python.org/simple/Django/1.1.4 proxy): * http://b.pypi.python.org/simple/Django/ proxy): Getting page http://b.pypi.python.org/simple/Django/1.1.4 proxy): Getting page http://b.pypi.python.org/simple/Django/ proxy): Could not fetch URL http://b.pypi.python.org/simple/Django/1.1.4: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/Django/1.1.4 when looking for download links for Django==1.1.4 proxy): Could not fetch URL http://b.pypi.python.org/simple/Django/: HTTP Error 404: Not Found proxy): Will skip URL http://b.pypi.python.org/simple/Django/ when looking for download links for Django==1.1.4 proxy): Could not find any downloads that satisfy the requirement Django==1.1.4 No distributions at all found for Django==1.1.4 proxy): Exception information: proxy): Traceback (most recent call last): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 482, in main proxy): self.run(options, args) proxy): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 675, in run proxy): requirement_set.install_files(finder, force_root_egg_info=self.bundle) proxy): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 2422, in install_files proxy): url = finder.find_requirement(req_to_install, upgrade=self.upgrade) proxy): proxy): File "/var/www/ScrumDo/pinax-env/lib/python2.6/site-packages/pip-0.6.1-py2.6.egg/pip.py", line 1485, in find_requirement proxy): proxy): raise DistributionNotFound('No distributions at all found for %s' % req) proxy): proxy): DistributionNotFound: No distributions at all found for Django==1.1.4 ```
2012/07/30
[ "https://Stackoverflow.com/questions/11724779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1411141/" ]
If you've tried installing a package with pip recently, you may have encountered this error: ``` Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm> Will skip URL https://pypi.python.org/simple/Django/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1)) Could not fetch URL https://pypi.python.org/simple/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm> Will skip URL https://pypi.python.org/simple/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1)) Cannot fetch index base URL https://pypi.python.org/simple/ Could not fetch URL https://pypi.python.org/simple/Django/1.5.1: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm> Will skip URL https://pypi.python.org/simple/Django/1.5.1 when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1)) Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm> Will skip URL https://pypi.python.org/simple/Django/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1)) Could not find any downloads that satisfy the requirement Django==1.5.1 (from -r requirements.txt (line 1)) No distributions at all found for Django==1.5.1 (from -r requirements.txt (line 1)) Storing complete log in /Users/paul/.pip/pip.log ``` This seems to be an issue with an old version of OpenSSL being incompatible with pip 1.3.1. If you're using a non-stock Python distribution (notably EPD 7.3), you're very likely to have a setup that isn't going to work with pip 1.3.1 without a shitload of work. The easy workaround for now, is to install pip 1.2.1, which does not require SSL: ``` curl -o https://pypi.python.org/packages/source/p/pip/pip-1.2.1.tar.gz tar xvfz pip-1.2.1.tar.gz cd pip-1.2.1 python setup.py install ``` If you are using EPD, and you're not using it for a class where things might break, you may want to consider installing the new incarnation: Enthought Canopy. I know they were aware of the issues caused by the previous version of OpenSSL, and would imagine they are using a new version now that should play nicely with pip 1.3.1.
This problem is most-likely caused by DNS setup: server cannot resolve the Domain Name, so cannot download the package. Solution: sudo nano /etc/network/interface add a line: dns-nameservers 8.8.8.8 save file and exit ``` sudo ifdown eth0 && sudo ifup eth0 ``` Then pip install should be working now.
53,162,325
I use google composer. I have a dag that uses the `panda.read_csv()` function to read a `.csv.gz` file. The DAG keeps trying without showing any errors. Here is the airflow log: ``` *** Reading remote log from gs://us-central1-data-airflo-dxxxxx-bucket/logs/youtubetv_gcpbucket_to_bq_daily_v2_csv/file_transfer_gcp_to_bq/2018-11-04T20:00:00/1.log. [2018-11-05 21:03:58,123] {cli.py:374} INFO - Running on host airflow-worker-77846bb966-vgrbz [2018-11-05 21:03:58,239] {models.py:1196} INFO - Dependencies all met for <TaskInstance: youtubetv_gcpbucket_to_bq_daily_v2_csv.file_transfer_gcp_to_bq 2018-11-04 20:00:00 [queued]> [2018-11-05 21:03:58,297] {models.py:1196} INFO - Dependencies all met for <TaskInstance: youtubetv_gcpbucket_to_bq_daily_v2_csv.file_transfer_gcp_to_bq 2018-11-04 20:00:00 [queued]> [2018-11-05 21:03:58,298] {models.py:1406} INFO - ---------------------------------------------------------------------- --------- Starting attempt 1 of ---------------------------------------------------------------------- --------- [2018-11-05 21:03:58,337] {models.py:1427} INFO - Executing <Task(BranchPythonOperator): file_transfer_gcp_to_bq> on 2018-11-04 20:00:00 [2018-11-05 21:03:58,338] {base_task_runner.py:115} INFO - Running: ['bash', '-c', u'airflow run youtubetv_gcpbucket_to_bq_daily_v2_csv file_transfer_gcp_to_bq 2018-11-04T20:00:00 --job_id 15096 --raw -sd DAGS_FOLDER/dags/testdags/youtubetv_gcp_to_bq_v2.py'] ``` python code in DAG: ``` from datetime import datetime,timedelta from airflow import DAG from airflow import models import os import io,logging, sys import pandas as pd from io import BytesIO, StringIO from airflow.operators.dummy_operator import DummyOperator from airflow.operators.subdag_operator import SubDagOperator from airflow.operators.python_operator import BranchPythonOperator from airflow.operators.bash_operator import BashOperator #GCP from google.cloud import storage import google.cloud from google.cloud import bigquery from google.oauth2 import service_account from airflow.operators.slack_operator import SlackAPIPostOperator from airflow.models import Connection from airflow.utils.db import provide_session from airflow.utils.trigger_rule import TriggerRule def readCSV(checked_date,file_name, **kwargs): subDir=checked_date.replace('-','/') fileobj = get_byte_fileobj(BQ_PROJECT_NAME, YOUTUBETV_BUCKET, subDir+"/"+file_name) df_chunks = pd.read_csv(fileobj, compression='gzip',memory_map=True, chunksize=1000000) # return TextFileReader print ("done reaCSV") return df_chunks ``` DAG: ``` file_transfer_gcp_to_bq = BranchPythonOperator( task_id='file_transfer_gcp_to_bq', provide_context=True, python_callable=readCSV, op_kwargs={'checked_date': '2018-11-03', 'file_name':'daily_events_xxxxx_partner_report.csv.gz'} ) ``` The DAG is successfully run on my local airflow version. ``` def readCSV(checked_date,file_name, **kwargs): subDir=checked_date.replace('-','/') fileobj = get_byte_fileobj(BQ_PROJECT_NAME, YOUTUBETV_BUCKET, subDir+"/"+file_name) df = pd.read_csv(fileobj, compression='gzip',memory_map=True) return df ``` tested get\_byte\_fileobj and it works as a stand alone function.
2018/11/05
[ "https://Stackoverflow.com/questions/53162325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2183883/" ]
Based on this discussion [airflow google composer group](https://groups.google.com/forum/#!topic/cloud-composer-discuss/alnKzMjEj8Q) it is a known issue. One of the reason can be because of overkilling all the composer resources (in my case memory)
I have a [similar issue](https://groups.google.com/forum/#!topic/cloud-composer-discuss/lKsy7X1fy00) recently. In my case it's beacause the kubernetes worker overload. You can watch the worker performance on kubernetes dashboard too see whether your case is cluster overloadding issue. If yes, you can try set the value of an airflow configuration `celeryd_concurrency` lower to reduce the parallism in a worker and see whether the cluster loads goes down [![enter image description here](https://i.stack.imgur.com/KGoOk.png)](https://i.stack.imgur.com/KGoOk.png)
57,602,726
I'm wondering why we can have Tensorflow [run in a multi-thread fashion](https://www.tensorflow.org/guide/performance/overview#optimizing_for_cpu) while python can only execute one thread at a time due to [GIL](https://wiki.python.org/moin/GlobalInterpreterLock)?
2019/08/22
[ "https://Stackoverflow.com/questions/57602726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7850499/" ]
The GIL's restriction is slightly more subtle: only one thread at a time can be *executing Python bytecode*. Extensions using Python's C API (like `tensorflow`) can release the GIL if they don't need it. I/O operations like using files or sockets also tend to release the GIL because they generally involve lots of waiting. So threads executing extensions or waiting for I/O can run while another thread is executing Python bytecode.
Most of the `tensorflow` core is written in `C++` and the python APIs are just the wrappers around it. While running the `C++` code regular python restrictions do not apply.
4,631,377
I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04. I want to be able to use the file odbchelper.py, which is located in the directory `/Desktop/Python_Tutorials/diveintopython/py` Here is my example.py file that I'm working on in my PyDev/Eclipse project: ``` import sys sys.path.append("~/Desktop/Python_Tutorials/diveintopython/py") ``` This works fine, but then I want the next line of my code to be: ``` import odbchelper ``` and this causes an unresolved import error every time. I have added `__init__.py` files to just about every directory possible and it doesn't help anything. I've tried adding `__init__.py` files one at a time to the various levels of directories between the project location and the odbchelper.py file, and I've also tried adding the `__init__.py` files to all of the directories in between simultaneously. Neither works. All I want to do is have a project somewhere in some other directory, say `/Desktop/MyStuff/Project`, in which I have example.py ... and then from example.py I want to import odbchelper.py from `/Desktop/Python_Tutorials/diveintopython/py/` Every message board response I can find just saying to use the `sys.path.append()` function to add this directory to my path, and then import it ... but that is precisely what I am doing in my code and it's not working. I have also tried the `Ctrl`-`1` trick to suppress the error message, but the program is still not functioning correctly. I get an error, `ImportError: No module named odbchelper`. So it's clearly not getting the path added, or there is some problem that all of my many permutations of adding `__init__.py` files has missed. It's very frustrating that something this simple... calling things from some file that exists somewhere else on my machine... requires this much effort.
2011/01/07
[ "https://Stackoverflow.com/questions/4631377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567620/" ]
I am using eclipse kepler 4.3, PyDev 3.9.2 and on my ubuntu 14.04 I encountered with the same problem. I tried and spent hours, with all the above most of the options but in vain. Then I tried the following which was great: * Select **Project**-> RightClick-> **PyDev**-> **Remove PyDev Project Config** * file-> **restart** And I was using Python 2.7 as an interpreter, although it doesn’t effect, I think.
Following, in my opinion will solve the problem 1. Adding the **init**.py to your "~/Desktop/Python\_Tutorials/diveintopython/py" folder 2. Go to Window --> Preferences --> PyDev --> Interpreters --> Python Interpreter to remove your Python Interpreter setting (reason being is because PyDev unable to auto refresh any updates made to any System PythonPath) 3. Add in the Interpreter with the same details as before (this will refresh your Python Interpreter setting with updates made to your PythonPath) 4. Finally since your "~/Desktop/Python\_Tutorials/diveintopython/py" folder not a standard PythonPath, you will need to add it in. There are two ways to do it a. As per what David German suggested. However this only applicable for the particular projects you are in b. Add in "~/Desktop/Python\_Tutorials/diveintopython/py" into a new PythonPath under Window --> Preferences --> PyDev --> Interpreters --> Python Interpreter --> Libraries subtab --> NewFolder Hope it helps.
4,631,377
I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04. I want to be able to use the file odbchelper.py, which is located in the directory `/Desktop/Python_Tutorials/diveintopython/py` Here is my example.py file that I'm working on in my PyDev/Eclipse project: ``` import sys sys.path.append("~/Desktop/Python_Tutorials/diveintopython/py") ``` This works fine, but then I want the next line of my code to be: ``` import odbchelper ``` and this causes an unresolved import error every time. I have added `__init__.py` files to just about every directory possible and it doesn't help anything. I've tried adding `__init__.py` files one at a time to the various levels of directories between the project location and the odbchelper.py file, and I've also tried adding the `__init__.py` files to all of the directories in between simultaneously. Neither works. All I want to do is have a project somewhere in some other directory, say `/Desktop/MyStuff/Project`, in which I have example.py ... and then from example.py I want to import odbchelper.py from `/Desktop/Python_Tutorials/diveintopython/py/` Every message board response I can find just saying to use the `sys.path.append()` function to add this directory to my path, and then import it ... but that is precisely what I am doing in my code and it's not working. I have also tried the `Ctrl`-`1` trick to suppress the error message, but the program is still not functioning correctly. I get an error, `ImportError: No module named odbchelper`. So it's clearly not getting the path added, or there is some problem that all of my many permutations of adding `__init__.py` files has missed. It's very frustrating that something this simple... calling things from some file that exists somewhere else on my machine... requires this much effort.
2011/01/07
[ "https://Stackoverflow.com/questions/4631377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567620/" ]
I am using eclipse kepler 4.3, PyDev 3.9.2 and on my ubuntu 14.04 I encountered with the same problem. I tried and spent hours, with all the above most of the options but in vain. Then I tried the following which was great: * Select **Project**-> RightClick-> **PyDev**-> **Remove PyDev Project Config** * file-> **restart** And I was using Python 2.7 as an interpreter, although it doesn’t effect, I think.
``` KD.py class A: a=10; KD2.py from com.jbk.KD import A; class B: b=120; aa=A(); print(aa.a) ``` THIS works perfectly file for me Another example is ``` main.py ======= from com.jbk.scenarios.objectcreation.settings import _init from com.jbk.scenarios.objectcreation.subfile import stuff _init(); stuff(); settings.py ========== def _init(): print("kiran") subfile.py ========== def stuff(): print("asasas") ```
4,631,377
I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04. I want to be able to use the file odbchelper.py, which is located in the directory `/Desktop/Python_Tutorials/diveintopython/py` Here is my example.py file that I'm working on in my PyDev/Eclipse project: ``` import sys sys.path.append("~/Desktop/Python_Tutorials/diveintopython/py") ``` This works fine, but then I want the next line of my code to be: ``` import odbchelper ``` and this causes an unresolved import error every time. I have added `__init__.py` files to just about every directory possible and it doesn't help anything. I've tried adding `__init__.py` files one at a time to the various levels of directories between the project location and the odbchelper.py file, and I've also tried adding the `__init__.py` files to all of the directories in between simultaneously. Neither works. All I want to do is have a project somewhere in some other directory, say `/Desktop/MyStuff/Project`, in which I have example.py ... and then from example.py I want to import odbchelper.py from `/Desktop/Python_Tutorials/diveintopython/py/` Every message board response I can find just saying to use the `sys.path.append()` function to add this directory to my path, and then import it ... but that is precisely what I am doing in my code and it's not working. I have also tried the `Ctrl`-`1` trick to suppress the error message, but the program is still not functioning correctly. I get an error, `ImportError: No module named odbchelper`. So it's clearly not getting the path added, or there is some problem that all of my many permutations of adding `__init__.py` files has missed. It's very frustrating that something this simple... calling things from some file that exists somewhere else on my machine... requires this much effort.
2011/01/07
[ "https://Stackoverflow.com/questions/4631377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567620/" ]
I am using eclipse kepler 4.3, PyDev 3.9.2 and on my ubuntu 14.04 I encountered with the same problem. I tried and spent hours, with all the above most of the options but in vain. Then I tried the following which was great: * Select **Project**-> RightClick-> **PyDev**-> **Remove PyDev Project Config** * file-> **restart** And I was using Python 2.7 as an interpreter, although it doesn’t effect, I think.
There are two ways of solving this issue: * Delete the Python interpreter from "Python interpreters" and add it again. * Or just add the folder with the libraries in the interpreter you are using in your project, in my case I was using "bottle" and the folder I added was "c:\Python33\Lib\site-packages\bottle-0.11.6-py3.3.egg" Now I don't see the error anymore, and the code completion feature works as well with "bottle".
4,631,377
I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04. I want to be able to use the file odbchelper.py, which is located in the directory `/Desktop/Python_Tutorials/diveintopython/py` Here is my example.py file that I'm working on in my PyDev/Eclipse project: ``` import sys sys.path.append("~/Desktop/Python_Tutorials/diveintopython/py") ``` This works fine, but then I want the next line of my code to be: ``` import odbchelper ``` and this causes an unresolved import error every time. I have added `__init__.py` files to just about every directory possible and it doesn't help anything. I've tried adding `__init__.py` files one at a time to the various levels of directories between the project location and the odbchelper.py file, and I've also tried adding the `__init__.py` files to all of the directories in between simultaneously. Neither works. All I want to do is have a project somewhere in some other directory, say `/Desktop/MyStuff/Project`, in which I have example.py ... and then from example.py I want to import odbchelper.py from `/Desktop/Python_Tutorials/diveintopython/py/` Every message board response I can find just saying to use the `sys.path.append()` function to add this directory to my path, and then import it ... but that is precisely what I am doing in my code and it's not working. I have also tried the `Ctrl`-`1` trick to suppress the error message, but the program is still not functioning correctly. I get an error, `ImportError: No module named odbchelper`. So it's clearly not getting the path added, or there is some problem that all of my many permutations of adding `__init__.py` files has missed. It's very frustrating that something this simple... calling things from some file that exists somewhere else on my machine... requires this much effort.
2011/01/07
[ "https://Stackoverflow.com/questions/4631377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567620/" ]
I just upgraded a WXWindows project to Python 2.7 and had no end of trouble getting Pydev to recognize the new interpreter. Did the same thing as above configuring the interpreter, made a fresh install of Eclipse and Pydev. Thought some part of python must have been corrupt, so I re-installed everything again. Arghh! Closed and reopened the project, and restarted Eclipse between all of these changes. FINALLY noticed you can 'remove the PyDev project config' by right clicking on project. Then it can be made into a PyDev project again, now it is good as gold!
Here is what worked for me (sugested by soulBit): ``` 1) Restart using restart from the file menu 2) Once it started again, manually close and open it. ``` This is the simplest solution ever and it completely removes the annoying thing.
4,631,377
I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04. I want to be able to use the file odbchelper.py, which is located in the directory `/Desktop/Python_Tutorials/diveintopython/py` Here is my example.py file that I'm working on in my PyDev/Eclipse project: ``` import sys sys.path.append("~/Desktop/Python_Tutorials/diveintopython/py") ``` This works fine, but then I want the next line of my code to be: ``` import odbchelper ``` and this causes an unresolved import error every time. I have added `__init__.py` files to just about every directory possible and it doesn't help anything. I've tried adding `__init__.py` files one at a time to the various levels of directories between the project location and the odbchelper.py file, and I've also tried adding the `__init__.py` files to all of the directories in between simultaneously. Neither works. All I want to do is have a project somewhere in some other directory, say `/Desktop/MyStuff/Project`, in which I have example.py ... and then from example.py I want to import odbchelper.py from `/Desktop/Python_Tutorials/diveintopython/py/` Every message board response I can find just saying to use the `sys.path.append()` function to add this directory to my path, and then import it ... but that is precisely what I am doing in my code and it's not working. I have also tried the `Ctrl`-`1` trick to suppress the error message, but the program is still not functioning correctly. I get an error, `ImportError: No module named odbchelper`. So it's clearly not getting the path added, or there is some problem that all of my many permutations of adding `__init__.py` files has missed. It's very frustrating that something this simple... calling things from some file that exists somewhere else on my machine... requires this much effort.
2011/01/07
[ "https://Stackoverflow.com/questions/4631377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567620/" ]
I am using eclipse kepler 4.3, PyDev 3.9.2 and on my ubuntu 14.04 I encountered with the same problem. I tried and spent hours, with all the above most of the options but in vain. Then I tried the following which was great: * Select **Project**-> RightClick-> **PyDev**-> **Remove PyDev Project Config** * file-> **restart** And I was using Python 2.7 as an interpreter, although it doesn’t effect, I think.
I'm running Eclipse 4.2.0 (Juno) and PyDev 2.8.1, and ran into this problem with a lib installed to my site-packages path. According to this SO question: [Pydev and \*.pyc Files](https://stackoverflow.com/questions/13967342/pydev-and-pyc-files) ...there is an issue with PyDev and pyc files. In the case of the particular lib I tried to reference, all that is delivered is pyc files. Here's what I did to address this: 1. Install uncompyle2 from <https://github.com/Mysterie/uncompyle2> 2. Run uncompyle2 against the \*.pyc files in the site-packages lib. Example: uncompyle2 -r -o /tmp /path/to/site-packages/lib 3. Rename the resulting \*.pyc\_dis files produced from uncompyle2 to \*.py 4. Move / copy these \*.py files to the site-packages path 5. In Eclipse, select File > Restart The unresolved import error relating to .pyc files should now disappear.
4,631,377
I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04. I want to be able to use the file odbchelper.py, which is located in the directory `/Desktop/Python_Tutorials/diveintopython/py` Here is my example.py file that I'm working on in my PyDev/Eclipse project: ``` import sys sys.path.append("~/Desktop/Python_Tutorials/diveintopython/py") ``` This works fine, but then I want the next line of my code to be: ``` import odbchelper ``` and this causes an unresolved import error every time. I have added `__init__.py` files to just about every directory possible and it doesn't help anything. I've tried adding `__init__.py` files one at a time to the various levels of directories between the project location and the odbchelper.py file, and I've also tried adding the `__init__.py` files to all of the directories in between simultaneously. Neither works. All I want to do is have a project somewhere in some other directory, say `/Desktop/MyStuff/Project`, in which I have example.py ... and then from example.py I want to import odbchelper.py from `/Desktop/Python_Tutorials/diveintopython/py/` Every message board response I can find just saying to use the `sys.path.append()` function to add this directory to my path, and then import it ... but that is precisely what I am doing in my code and it's not working. I have also tried the `Ctrl`-`1` trick to suppress the error message, but the program is still not functioning correctly. I get an error, `ImportError: No module named odbchelper`. So it's clearly not getting the path added, or there is some problem that all of my many permutations of adding `__init__.py` files has missed. It's very frustrating that something this simple... calling things from some file that exists somewhere else on my machine... requires this much effort.
2011/01/07
[ "https://Stackoverflow.com/questions/4631377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567620/" ]
**project-->properties-->pydev-pythonpath-->external libraries --> add** source folder, add the PARENT FOLDER of the project. Then restart eclipse.
``` KD.py class A: a=10; KD2.py from com.jbk.KD import A; class B: b=120; aa=A(); print(aa.a) ``` THIS works perfectly file for me Another example is ``` main.py ======= from com.jbk.scenarios.objectcreation.settings import _init from com.jbk.scenarios.objectcreation.subfile import stuff _init(); stuff(); settings.py ========== def _init(): print("kiran") subfile.py ========== def stuff(): print("asasas") ```
4,631,377
I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04. I want to be able to use the file odbchelper.py, which is located in the directory `/Desktop/Python_Tutorials/diveintopython/py` Here is my example.py file that I'm working on in my PyDev/Eclipse project: ``` import sys sys.path.append("~/Desktop/Python_Tutorials/diveintopython/py") ``` This works fine, but then I want the next line of my code to be: ``` import odbchelper ``` and this causes an unresolved import error every time. I have added `__init__.py` files to just about every directory possible and it doesn't help anything. I've tried adding `__init__.py` files one at a time to the various levels of directories between the project location and the odbchelper.py file, and I've also tried adding the `__init__.py` files to all of the directories in between simultaneously. Neither works. All I want to do is have a project somewhere in some other directory, say `/Desktop/MyStuff/Project`, in which I have example.py ... and then from example.py I want to import odbchelper.py from `/Desktop/Python_Tutorials/diveintopython/py/` Every message board response I can find just saying to use the `sys.path.append()` function to add this directory to my path, and then import it ... but that is precisely what I am doing in my code and it's not working. I have also tried the `Ctrl`-`1` trick to suppress the error message, but the program is still not functioning correctly. I get an error, `ImportError: No module named odbchelper`. So it's clearly not getting the path added, or there is some problem that all of my many permutations of adding `__init__.py` files has missed. It's very frustrating that something this simple... calling things from some file that exists somewhere else on my machine... requires this much effort.
2011/01/07
[ "https://Stackoverflow.com/questions/4631377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567620/" ]
I had some issues importing additional libraries, after trying to resolve the problem, by understanding PYTHONPATH, Interpreter, and Grammar I found that I did everything write but the problems continue. After that, **I just add a new empty line in the files that had the import errors and saved them and the error was resolved**.
``` KD.py class A: a=10; KD2.py from com.jbk.KD import A; class B: b=120; aa=A(); print(aa.a) ``` THIS works perfectly file for me Another example is ``` main.py ======= from com.jbk.scenarios.objectcreation.settings import _init from com.jbk.scenarios.objectcreation.subfile import stuff _init(); stuff(); settings.py ========== def _init(): print("kiran") subfile.py ========== def stuff(): print("asasas") ```
4,631,377
I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04. I want to be able to use the file odbchelper.py, which is located in the directory `/Desktop/Python_Tutorials/diveintopython/py` Here is my example.py file that I'm working on in my PyDev/Eclipse project: ``` import sys sys.path.append("~/Desktop/Python_Tutorials/diveintopython/py") ``` This works fine, but then I want the next line of my code to be: ``` import odbchelper ``` and this causes an unresolved import error every time. I have added `__init__.py` files to just about every directory possible and it doesn't help anything. I've tried adding `__init__.py` files one at a time to the various levels of directories between the project location and the odbchelper.py file, and I've also tried adding the `__init__.py` files to all of the directories in between simultaneously. Neither works. All I want to do is have a project somewhere in some other directory, say `/Desktop/MyStuff/Project`, in which I have example.py ... and then from example.py I want to import odbchelper.py from `/Desktop/Python_Tutorials/diveintopython/py/` Every message board response I can find just saying to use the `sys.path.append()` function to add this directory to my path, and then import it ... but that is precisely what I am doing in my code and it's not working. I have also tried the `Ctrl`-`1` trick to suppress the error message, but the program is still not functioning correctly. I get an error, `ImportError: No module named odbchelper`. So it's clearly not getting the path added, or there is some problem that all of my many permutations of adding `__init__.py` files has missed. It's very frustrating that something this simple... calling things from some file that exists somewhere else on my machine... requires this much effort.
2011/01/07
[ "https://Stackoverflow.com/questions/4631377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567620/" ]
I fixed my pythonpath and everything was dandy when I imported stuff through the console, but all these previously unresolved imports were still marked as errors in my code, no matter how many times I restarted eclipse or refreshed/cleaned the project. I right clicked the project->Pydev->Remove error markers and it got rid of that problem. Don't worry, if your code contains actual errors they will be re-marked.
I had some issues importing additional libraries, after trying to resolve the problem, by understanding PYTHONPATH, Interpreter, and Grammar I found that I did everything write but the problems continue. After that, **I just add a new empty line in the files that had the import errors and saved them and the error was resolved**.
4,631,377
I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04. I want to be able to use the file odbchelper.py, which is located in the directory `/Desktop/Python_Tutorials/diveintopython/py` Here is my example.py file that I'm working on in my PyDev/Eclipse project: ``` import sys sys.path.append("~/Desktop/Python_Tutorials/diveintopython/py") ``` This works fine, but then I want the next line of my code to be: ``` import odbchelper ``` and this causes an unresolved import error every time. I have added `__init__.py` files to just about every directory possible and it doesn't help anything. I've tried adding `__init__.py` files one at a time to the various levels of directories between the project location and the odbchelper.py file, and I've also tried adding the `__init__.py` files to all of the directories in between simultaneously. Neither works. All I want to do is have a project somewhere in some other directory, say `/Desktop/MyStuff/Project`, in which I have example.py ... and then from example.py I want to import odbchelper.py from `/Desktop/Python_Tutorials/diveintopython/py/` Every message board response I can find just saying to use the `sys.path.append()` function to add this directory to my path, and then import it ... but that is precisely what I am doing in my code and it's not working. I have also tried the `Ctrl`-`1` trick to suppress the error message, but the program is still not functioning correctly. I get an error, `ImportError: No module named odbchelper`. So it's clearly not getting the path added, or there is some problem that all of my many permutations of adding `__init__.py` files has missed. It's very frustrating that something this simple... calling things from some file that exists somewhere else on my machine... requires this much effort.
2011/01/07
[ "https://Stackoverflow.com/questions/4631377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567620/" ]
I just upgraded a WXWindows project to Python 2.7 and had no end of trouble getting Pydev to recognize the new interpreter. Did the same thing as above configuring the interpreter, made a fresh install of Eclipse and Pydev. Thought some part of python must have been corrupt, so I re-installed everything again. Arghh! Closed and reopened the project, and restarted Eclipse between all of these changes. FINALLY noticed you can 'remove the PyDev project config' by right clicking on project. Then it can be made into a PyDev project again, now it is good as gold!
**project-->properties-->pydev-pythonpath-->external libraries --> add** source folder, add the PARENT FOLDER of the project. Then restart eclipse.
4,631,377
I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that's just becoming exceedingly annoying. I am using Ubuntu Linux 10.04. I want to be able to use the file odbchelper.py, which is located in the directory `/Desktop/Python_Tutorials/diveintopython/py` Here is my example.py file that I'm working on in my PyDev/Eclipse project: ``` import sys sys.path.append("~/Desktop/Python_Tutorials/diveintopython/py") ``` This works fine, but then I want the next line of my code to be: ``` import odbchelper ``` and this causes an unresolved import error every time. I have added `__init__.py` files to just about every directory possible and it doesn't help anything. I've tried adding `__init__.py` files one at a time to the various levels of directories between the project location and the odbchelper.py file, and I've also tried adding the `__init__.py` files to all of the directories in between simultaneously. Neither works. All I want to do is have a project somewhere in some other directory, say `/Desktop/MyStuff/Project`, in which I have example.py ... and then from example.py I want to import odbchelper.py from `/Desktop/Python_Tutorials/diveintopython/py/` Every message board response I can find just saying to use the `sys.path.append()` function to add this directory to my path, and then import it ... but that is precisely what I am doing in my code and it's not working. I have also tried the `Ctrl`-`1` trick to suppress the error message, but the program is still not functioning correctly. I get an error, `ImportError: No module named odbchelper`. So it's clearly not getting the path added, or there is some problem that all of my many permutations of adding `__init__.py` files has missed. It's very frustrating that something this simple... calling things from some file that exists somewhere else on my machine... requires this much effort.
2011/01/07
[ "https://Stackoverflow.com/questions/4631377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567620/" ]
I'm running Eclipse 4.2.0 (Juno) and PyDev 2.8.1, and ran into this problem with a lib installed to my site-packages path. According to this SO question: [Pydev and \*.pyc Files](https://stackoverflow.com/questions/13967342/pydev-and-pyc-files) ...there is an issue with PyDev and pyc files. In the case of the particular lib I tried to reference, all that is delivered is pyc files. Here's what I did to address this: 1. Install uncompyle2 from <https://github.com/Mysterie/uncompyle2> 2. Run uncompyle2 against the \*.pyc files in the site-packages lib. Example: uncompyle2 -r -o /tmp /path/to/site-packages/lib 3. Rename the resulting \*.pyc\_dis files produced from uncompyle2 to \*.py 4. Move / copy these \*.py files to the site-packages path 5. In Eclipse, select File > Restart The unresolved import error relating to .pyc files should now disappear.
``` KD.py class A: a=10; KD2.py from com.jbk.KD import A; class B: b=120; aa=A(); print(aa.a) ``` THIS works perfectly file for me Another example is ``` main.py ======= from com.jbk.scenarios.objectcreation.settings import _init from com.jbk.scenarios.objectcreation.subfile import stuff _init(); stuff(); settings.py ========== def _init(): print("kiran") subfile.py ========== def stuff(): print("asasas") ```
62,504,019
I am calling the Giphy API using another [wrapper API](https://github.com/Giphy/giphy-python-client) which returns a **list of dictionaries**. I am having hard times to serialize the data to return it to AJAX. The data is returned as `InlineResponse200` with three [properties](https://github.com/Giphy/giphy-python-client/blob/master/docs/InlineResponse200.md). ([docu](https://github.com/Giphy/giphy-python-client/blob/master/docs/Gif.md)) The problem is that my view is not able to return the JSON properly: ``` # Traceback [2020-06-23 14:58:54,086] log: ERROR - Internal Server Error: /get_gifs/ Traceback (most recent call last): File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Jonas\Desktop\finsphere\finsphere\blog\views.py", line 234, in get_gifs return JsonResponse(api_response.data[0]) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\http\response.py", line 554, in __init__ raise TypeError( TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False. [23/Jun/2020 14:58:54] "POST /get_gifs/ HTTP/1.1" 500 17874 ``` If I add `safe=False` it returns `TypeError: Object of type Gif is not JSON serializable` I don't get this since `api_response.data[0]` is a cristal clear dictionary. **Desired outcome:** Get the Giphy object logged in the success function of Ajax. **AJAX** ``` (function($) { $('#btnSearch').on('click', function(e) { var query = $('#search').val(); console.log(query); e.preventDefault(); $.ajax({ type: 'post', async: true, url: '/get_gifs/', data: { 'query': query, 'csrfmiddlewaretoken': window.CSRF_TOKEN // from blog.html }, success: function(response) { }, error: function(xhr, status, error) { // shit happens friends! } }); }); }(jQuery)); ``` (Inserted my original -free- API key for reproduction) **Views.py** ``` def get_gifs(request): # create an instance of the API class api_instance = giphy_client.DefaultApi() # API Key api_key = 'NGSKWrBqtIq1rFU1Ka11D879Y1u4Igia' # Search term q = request.POST.get('query') print(q) # Query parameters limit = 2 offset = 0 rating = 'g' lang = 'en' fmt = 'json' try: # Search Endpoint api_response = api_instance.gifs_search_get(api_key, q, limit=limit, offset=offset, rating=rating, lang=lang, fmt=fmt) pprint(api_response) except ApiException as e: print("Exception when calling DefaultApi->gifs_search_get: %s\n" % e) return JsonResponse(api_response.data[0]) ``` **API fetched object (pprint api\_response)** ``` {'data': [{'bitly_gif_url': 'https://gph.is/g/EJWjdvN', 'bitly_url': 'https://gph.is/g/EJWjdvN', 'content_url': '', 'create_datetime': None, 'embed_url': 'https://giphy.com/embed/J0JGg6doLfmV0yZmIB', 'featured_tags': None, 'id': 'J0JGg6doLfmV0yZmIB', 'images': {'downsized': {'height': '250', 'size': '350582', 'url': 'https://media3.giphy.com/media/J0JGg6doLfmV0yZmIB/giphy.gif?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy.gif', 'width': '478'}, 'downsized_large': {'height': '250', 'size': '350582', 'url': 'https://media3.giphy.com/media/J0JGg6doLfmV0yZmIB/giphy.gif?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy.gif', 'width': '478'}, 'preview_gif': {'height': '134', 'size': '49623', 'url': 'https://media3.giphy.com/media/J0JGg6doLfmV0yZmIB/giphy-preview.gif?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy-preview.gif', 'width': '256'}}, 'import_datetime': '2020-06-15 10:01:39', 'is_anonymous': None, 'is_community': None, 'is_featured': None, 'is_hidden': None, 'is_indexable': None, 'is_realtime': None, 'is_removed': None, 'is_sticker': False, 'rating': 'g', 'slug': 'MITEF-mitefarab-asc2020-J0JGg6doLfmV0yZmIB', 'source': 'www.mitefarab.org', 'source_post_url': 'www.mitefarab.org', 'source_tld': '', 'tags': None, 'trending_datetime': '0000-00-00 00:00:00', 'type': 'gif', 'update_datetime': None, 'url': 'https://giphy.com/gifs/MITEF-mitefarab-asc2020-J0JGg6doLfmV0yZmIB', 'user': {'avatar_url': 'https://media2.giphy.com/avatars/MITEF/8FTlysEjtXzx.jpg', 'banner_url': '', 'display_name': 'MITEF Pan Arab', 'profile_url': 'https://giphy.com/MITEF/', 'twitter': None, 'username': 'MITEF'}, 'username': 'MITEF'}, {'bitly_gif_url': 'https://gph.is/g/ZdxQQpP', 'bitly_url': 'https://gph.is/g/ZdxQQpP', 'content_url': '', 'create_datetime': None, 'embed_url': 'https://giphy.com/embed/hTJF0O4vDkJsUi1h8Q', 'featured_tags': None, 'id': 'hTJF0O4vDkJsUi1h8Q', 'images': {'downsized': {'height': '480', 'size': '310971', 'url': 'https://media3.giphy.com/media/hTJF0O4vDkJsUi1h8Q/giphy.gif?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy.gif', 'width': '480'}, 'preview': {'height': '480', 'mp4': 'https://media3.giphy.com/media/hTJF0O4vDkJsUi1h8Q/giphy-preview.mp4?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy-preview.mp4', 'mp4_size': '15536', 'width': '480'}, 'preview_gif': {'height': '480', 'size': '22387', 'url': 'https://media3.giphy.com/media/hTJF0O4vDkJsUi1h8Q/giphy-preview.gif?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy-preview.gif', 'width': '480'}}, 'import_datetime': '2019-07-19 22:27:40', 'is_anonymous': None, 'is_community': None, 'is_featured': None, 'is_hidden': None, 'is_indexable': None, 'is_realtime': None, 'is_removed': None, 'is_sticker': False, 'rating': 'g', 'slug': 'RecargaPay-cashback-recargapay-paguetudopelocelular-hTJF0O4vDkJsUi1h8Q', 'source': 'www.recargapay.com.br', 'source_post_url': 'www.recargapay.com.br', 'source_tld': '', 'tags': None, 'trending_datetime': '0000-00-00 00:00:00', 'type': 'gif', 'update_datetime': None, 'url': 'https://giphy.com/gifs/RecargaPay-cashback-recargapay-paguetudopelocelular-hTJF0O4vDkJsUi1h8Q', 'user': {'avatar_url': 'https://media0.giphy.com/avatars/RecargaPay/msKTiPaVkvqd.png', 'banner_url': 'https://media0.giphy.com/headers/RecargaPay/kg023vdaAaWA.gif', 'display_name': 'RecargaPay', 'profile_url': 'https://giphy.com/RecargaPay/', 'twitter': None, 'username': 'RecargaPay'}, 'username': 'RecargaPay'}], 'meta': {'msg': 'OK', 'response_id': '65bc1664c2b17e3e4b60d88c736d0c6b5a39d682', 'status': 200}, 'pagination': {'count': 2, 'offset': 0, 'total_count': 10}} ```
2020/06/21
[ "https://Stackoverflow.com/questions/62504019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12001122/" ]
``` render(request, template_name, context=None, content_type=None, status=None, using=None) ``` > > `render()` Combines a given template with a given context dictionary > and returns an HttpResponse object with that rendered text. > > > You can either use Django defaults `JsonResponse` class or Django REST framework `Response` class to return JSON responses. ``` from django.http import JsonResponse return JsonResponse(data=api_response.data) from rest_framework.response import Response return Response(data=api_response.data) ``` tried it on the ipython shell and it works just fine. ``` In [15]: response = Response(api_response.data[0]) In [16]: response Out[16]: <Response status_code=200, "text/html; charset=utf-8"> ``` `response.data` gives me the serialized response.
Python has a built in function for converting dicts to json. ``` import json data = api_response.data return render(request, json.dumps(data)) ``` If you use that in your return statement it should return json.
62,504,019
I am calling the Giphy API using another [wrapper API](https://github.com/Giphy/giphy-python-client) which returns a **list of dictionaries**. I am having hard times to serialize the data to return it to AJAX. The data is returned as `InlineResponse200` with three [properties](https://github.com/Giphy/giphy-python-client/blob/master/docs/InlineResponse200.md). ([docu](https://github.com/Giphy/giphy-python-client/blob/master/docs/Gif.md)) The problem is that my view is not able to return the JSON properly: ``` # Traceback [2020-06-23 14:58:54,086] log: ERROR - Internal Server Error: /get_gifs/ Traceback (most recent call last): File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Jonas\Desktop\finsphere\finsphere\blog\views.py", line 234, in get_gifs return JsonResponse(api_response.data[0]) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\http\response.py", line 554, in __init__ raise TypeError( TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False. [23/Jun/2020 14:58:54] "POST /get_gifs/ HTTP/1.1" 500 17874 ``` If I add `safe=False` it returns `TypeError: Object of type Gif is not JSON serializable` I don't get this since `api_response.data[0]` is a cristal clear dictionary. **Desired outcome:** Get the Giphy object logged in the success function of Ajax. **AJAX** ``` (function($) { $('#btnSearch').on('click', function(e) { var query = $('#search').val(); console.log(query); e.preventDefault(); $.ajax({ type: 'post', async: true, url: '/get_gifs/', data: { 'query': query, 'csrfmiddlewaretoken': window.CSRF_TOKEN // from blog.html }, success: function(response) { }, error: function(xhr, status, error) { // shit happens friends! } }); }); }(jQuery)); ``` (Inserted my original -free- API key for reproduction) **Views.py** ``` def get_gifs(request): # create an instance of the API class api_instance = giphy_client.DefaultApi() # API Key api_key = 'NGSKWrBqtIq1rFU1Ka11D879Y1u4Igia' # Search term q = request.POST.get('query') print(q) # Query parameters limit = 2 offset = 0 rating = 'g' lang = 'en' fmt = 'json' try: # Search Endpoint api_response = api_instance.gifs_search_get(api_key, q, limit=limit, offset=offset, rating=rating, lang=lang, fmt=fmt) pprint(api_response) except ApiException as e: print("Exception when calling DefaultApi->gifs_search_get: %s\n" % e) return JsonResponse(api_response.data[0]) ``` **API fetched object (pprint api\_response)** ``` {'data': [{'bitly_gif_url': 'https://gph.is/g/EJWjdvN', 'bitly_url': 'https://gph.is/g/EJWjdvN', 'content_url': '', 'create_datetime': None, 'embed_url': 'https://giphy.com/embed/J0JGg6doLfmV0yZmIB', 'featured_tags': None, 'id': 'J0JGg6doLfmV0yZmIB', 'images': {'downsized': {'height': '250', 'size': '350582', 'url': 'https://media3.giphy.com/media/J0JGg6doLfmV0yZmIB/giphy.gif?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy.gif', 'width': '478'}, 'downsized_large': {'height': '250', 'size': '350582', 'url': 'https://media3.giphy.com/media/J0JGg6doLfmV0yZmIB/giphy.gif?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy.gif', 'width': '478'}, 'preview_gif': {'height': '134', 'size': '49623', 'url': 'https://media3.giphy.com/media/J0JGg6doLfmV0yZmIB/giphy-preview.gif?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy-preview.gif', 'width': '256'}}, 'import_datetime': '2020-06-15 10:01:39', 'is_anonymous': None, 'is_community': None, 'is_featured': None, 'is_hidden': None, 'is_indexable': None, 'is_realtime': None, 'is_removed': None, 'is_sticker': False, 'rating': 'g', 'slug': 'MITEF-mitefarab-asc2020-J0JGg6doLfmV0yZmIB', 'source': 'www.mitefarab.org', 'source_post_url': 'www.mitefarab.org', 'source_tld': '', 'tags': None, 'trending_datetime': '0000-00-00 00:00:00', 'type': 'gif', 'update_datetime': None, 'url': 'https://giphy.com/gifs/MITEF-mitefarab-asc2020-J0JGg6doLfmV0yZmIB', 'user': {'avatar_url': 'https://media2.giphy.com/avatars/MITEF/8FTlysEjtXzx.jpg', 'banner_url': '', 'display_name': 'MITEF Pan Arab', 'profile_url': 'https://giphy.com/MITEF/', 'twitter': None, 'username': 'MITEF'}, 'username': 'MITEF'}, {'bitly_gif_url': 'https://gph.is/g/ZdxQQpP', 'bitly_url': 'https://gph.is/g/ZdxQQpP', 'content_url': '', 'create_datetime': None, 'embed_url': 'https://giphy.com/embed/hTJF0O4vDkJsUi1h8Q', 'featured_tags': None, 'id': 'hTJF0O4vDkJsUi1h8Q', 'images': {'downsized': {'height': '480', 'size': '310971', 'url': 'https://media3.giphy.com/media/hTJF0O4vDkJsUi1h8Q/giphy.gif?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy.gif', 'width': '480'}, 'preview': {'height': '480', 'mp4': 'https://media3.giphy.com/media/hTJF0O4vDkJsUi1h8Q/giphy-preview.mp4?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy-preview.mp4', 'mp4_size': '15536', 'width': '480'}, 'preview_gif': {'height': '480', 'size': '22387', 'url': 'https://media3.giphy.com/media/hTJF0O4vDkJsUi1h8Q/giphy-preview.gif?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy-preview.gif', 'width': '480'}}, 'import_datetime': '2019-07-19 22:27:40', 'is_anonymous': None, 'is_community': None, 'is_featured': None, 'is_hidden': None, 'is_indexable': None, 'is_realtime': None, 'is_removed': None, 'is_sticker': False, 'rating': 'g', 'slug': 'RecargaPay-cashback-recargapay-paguetudopelocelular-hTJF0O4vDkJsUi1h8Q', 'source': 'www.recargapay.com.br', 'source_post_url': 'www.recargapay.com.br', 'source_tld': '', 'tags': None, 'trending_datetime': '0000-00-00 00:00:00', 'type': 'gif', 'update_datetime': None, 'url': 'https://giphy.com/gifs/RecargaPay-cashback-recargapay-paguetudopelocelular-hTJF0O4vDkJsUi1h8Q', 'user': {'avatar_url': 'https://media0.giphy.com/avatars/RecargaPay/msKTiPaVkvqd.png', 'banner_url': 'https://media0.giphy.com/headers/RecargaPay/kg023vdaAaWA.gif', 'display_name': 'RecargaPay', 'profile_url': 'https://giphy.com/RecargaPay/', 'twitter': None, 'username': 'RecargaPay'}, 'username': 'RecargaPay'}], 'meta': {'msg': 'OK', 'response_id': '65bc1664c2b17e3e4b60d88c736d0c6b5a39d682', 'status': 200}, 'pagination': {'count': 2, 'offset': 0, 'total_count': 10}} ```
2020/06/21
[ "https://Stackoverflow.com/questions/62504019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12001122/" ]
I go though your code everything is correct except `return JsonResponse(api_response.data[0])` in your views **JsonResponse**: The **first parameter, data, should be a dict instance.** If the **safe parameter is set to False**, it can be any JSON-serializable object. [official documentation link](https://docs.djangoproject.com/en/3.0/ref/request-response/#jsonresponse-objects) When you say **1.** `safe=True` ``` return JsonResponse(api_response.data[0]) TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False. ``` The error is obvious `api_response.data[0]` is not dict, see point 2 error **2** `safe=False` ``` return JsonResponse(api_response.data[0], safe=False) TypeError: Object of type Gif is not JSON serializable ``` The data **api\_response.data[0]** you provide to JsonResponse **is not a dict type object actually**, that's why you got error for first point. when you say `safe=False` JsonResponse is trying to serialize object but that object is not json serializable, you can trace-back error ``` File "....\Python\Python38\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Gif is not JSON serializable ``` Can be followed the [link](https://docs.python.org/3/library/json.html) to see which object can be Json serializable Coming back to your error. *I don't get this since `api_response.data[0]` is a cristal clear dictionary.* type of `api_response` and `api_response.data[0]` ``` type(api_response) <class 'giphy_client.models.inline_response_200.InlineResponse200'> type(api_response.data[0]) <class 'giphy_client.models.gif.Gif'> ``` You can follow for giphy\_client [documentation link](https://github.com/Giphy/giphy-python-client#documentation-for-models) for more-details **Solution**: ``` result = api_response.data[0].to_dict() ## NOTE to_dict function of giphy_client.models.gif.Gif return JsonResponse(result) ```
Python has a built in function for converting dicts to json. ``` import json data = api_response.data return render(request, json.dumps(data)) ``` If you use that in your return statement it should return json.
62,504,019
I am calling the Giphy API using another [wrapper API](https://github.com/Giphy/giphy-python-client) which returns a **list of dictionaries**. I am having hard times to serialize the data to return it to AJAX. The data is returned as `InlineResponse200` with three [properties](https://github.com/Giphy/giphy-python-client/blob/master/docs/InlineResponse200.md). ([docu](https://github.com/Giphy/giphy-python-client/blob/master/docs/Gif.md)) The problem is that my view is not able to return the JSON properly: ``` # Traceback [2020-06-23 14:58:54,086] log: ERROR - Internal Server Error: /get_gifs/ Traceback (most recent call last): File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Jonas\Desktop\finsphere\finsphere\blog\views.py", line 234, in get_gifs return JsonResponse(api_response.data[0]) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\http\response.py", line 554, in __init__ raise TypeError( TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False. [23/Jun/2020 14:58:54] "POST /get_gifs/ HTTP/1.1" 500 17874 ``` If I add `safe=False` it returns `TypeError: Object of type Gif is not JSON serializable` I don't get this since `api_response.data[0]` is a cristal clear dictionary. **Desired outcome:** Get the Giphy object logged in the success function of Ajax. **AJAX** ``` (function($) { $('#btnSearch').on('click', function(e) { var query = $('#search').val(); console.log(query); e.preventDefault(); $.ajax({ type: 'post', async: true, url: '/get_gifs/', data: { 'query': query, 'csrfmiddlewaretoken': window.CSRF_TOKEN // from blog.html }, success: function(response) { }, error: function(xhr, status, error) { // shit happens friends! } }); }); }(jQuery)); ``` (Inserted my original -free- API key for reproduction) **Views.py** ``` def get_gifs(request): # create an instance of the API class api_instance = giphy_client.DefaultApi() # API Key api_key = 'NGSKWrBqtIq1rFU1Ka11D879Y1u4Igia' # Search term q = request.POST.get('query') print(q) # Query parameters limit = 2 offset = 0 rating = 'g' lang = 'en' fmt = 'json' try: # Search Endpoint api_response = api_instance.gifs_search_get(api_key, q, limit=limit, offset=offset, rating=rating, lang=lang, fmt=fmt) pprint(api_response) except ApiException as e: print("Exception when calling DefaultApi->gifs_search_get: %s\n" % e) return JsonResponse(api_response.data[0]) ``` **API fetched object (pprint api\_response)** ``` {'data': [{'bitly_gif_url': 'https://gph.is/g/EJWjdvN', 'bitly_url': 'https://gph.is/g/EJWjdvN', 'content_url': '', 'create_datetime': None, 'embed_url': 'https://giphy.com/embed/J0JGg6doLfmV0yZmIB', 'featured_tags': None, 'id': 'J0JGg6doLfmV0yZmIB', 'images': {'downsized': {'height': '250', 'size': '350582', 'url': 'https://media3.giphy.com/media/J0JGg6doLfmV0yZmIB/giphy.gif?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy.gif', 'width': '478'}, 'downsized_large': {'height': '250', 'size': '350582', 'url': 'https://media3.giphy.com/media/J0JGg6doLfmV0yZmIB/giphy.gif?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy.gif', 'width': '478'}, 'preview_gif': {'height': '134', 'size': '49623', 'url': 'https://media3.giphy.com/media/J0JGg6doLfmV0yZmIB/giphy-preview.gif?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy-preview.gif', 'width': '256'}}, 'import_datetime': '2020-06-15 10:01:39', 'is_anonymous': None, 'is_community': None, 'is_featured': None, 'is_hidden': None, 'is_indexable': None, 'is_realtime': None, 'is_removed': None, 'is_sticker': False, 'rating': 'g', 'slug': 'MITEF-mitefarab-asc2020-J0JGg6doLfmV0yZmIB', 'source': 'www.mitefarab.org', 'source_post_url': 'www.mitefarab.org', 'source_tld': '', 'tags': None, 'trending_datetime': '0000-00-00 00:00:00', 'type': 'gif', 'update_datetime': None, 'url': 'https://giphy.com/gifs/MITEF-mitefarab-asc2020-J0JGg6doLfmV0yZmIB', 'user': {'avatar_url': 'https://media2.giphy.com/avatars/MITEF/8FTlysEjtXzx.jpg', 'banner_url': '', 'display_name': 'MITEF Pan Arab', 'profile_url': 'https://giphy.com/MITEF/', 'twitter': None, 'username': 'MITEF'}, 'username': 'MITEF'}, {'bitly_gif_url': 'https://gph.is/g/ZdxQQpP', 'bitly_url': 'https://gph.is/g/ZdxQQpP', 'content_url': '', 'create_datetime': None, 'embed_url': 'https://giphy.com/embed/hTJF0O4vDkJsUi1h8Q', 'featured_tags': None, 'id': 'hTJF0O4vDkJsUi1h8Q', 'images': {'downsized': {'height': '480', 'size': '310971', 'url': 'https://media3.giphy.com/media/hTJF0O4vDkJsUi1h8Q/giphy.gif?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy.gif', 'width': '480'}, 'preview': {'height': '480', 'mp4': 'https://media3.giphy.com/media/hTJF0O4vDkJsUi1h8Q/giphy-preview.mp4?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy-preview.mp4', 'mp4_size': '15536', 'width': '480'}, 'preview_gif': {'height': '480', 'size': '22387', 'url': 'https://media3.giphy.com/media/hTJF0O4vDkJsUi1h8Q/giphy-preview.gif?cid=ecefd82565bc1664c2b17e3e4b60d88c736d0c6b5a39d682&rid=giphy-preview.gif', 'width': '480'}}, 'import_datetime': '2019-07-19 22:27:40', 'is_anonymous': None, 'is_community': None, 'is_featured': None, 'is_hidden': None, 'is_indexable': None, 'is_realtime': None, 'is_removed': None, 'is_sticker': False, 'rating': 'g', 'slug': 'RecargaPay-cashback-recargapay-paguetudopelocelular-hTJF0O4vDkJsUi1h8Q', 'source': 'www.recargapay.com.br', 'source_post_url': 'www.recargapay.com.br', 'source_tld': '', 'tags': None, 'trending_datetime': '0000-00-00 00:00:00', 'type': 'gif', 'update_datetime': None, 'url': 'https://giphy.com/gifs/RecargaPay-cashback-recargapay-paguetudopelocelular-hTJF0O4vDkJsUi1h8Q', 'user': {'avatar_url': 'https://media0.giphy.com/avatars/RecargaPay/msKTiPaVkvqd.png', 'banner_url': 'https://media0.giphy.com/headers/RecargaPay/kg023vdaAaWA.gif', 'display_name': 'RecargaPay', 'profile_url': 'https://giphy.com/RecargaPay/', 'twitter': None, 'username': 'RecargaPay'}, 'username': 'RecargaPay'}], 'meta': {'msg': 'OK', 'response_id': '65bc1664c2b17e3e4b60d88c736d0c6b5a39d682', 'status': 200}, 'pagination': {'count': 2, 'offset': 0, 'total_count': 10}} ```
2020/06/21
[ "https://Stackoverflow.com/questions/62504019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12001122/" ]
I go though your code everything is correct except `return JsonResponse(api_response.data[0])` in your views **JsonResponse**: The **first parameter, data, should be a dict instance.** If the **safe parameter is set to False**, it can be any JSON-serializable object. [official documentation link](https://docs.djangoproject.com/en/3.0/ref/request-response/#jsonresponse-objects) When you say **1.** `safe=True` ``` return JsonResponse(api_response.data[0]) TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False. ``` The error is obvious `api_response.data[0]` is not dict, see point 2 error **2** `safe=False` ``` return JsonResponse(api_response.data[0], safe=False) TypeError: Object of type Gif is not JSON serializable ``` The data **api\_response.data[0]** you provide to JsonResponse **is not a dict type object actually**, that's why you got error for first point. when you say `safe=False` JsonResponse is trying to serialize object but that object is not json serializable, you can trace-back error ``` File "....\Python\Python38\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Gif is not JSON serializable ``` Can be followed the [link](https://docs.python.org/3/library/json.html) to see which object can be Json serializable Coming back to your error. *I don't get this since `api_response.data[0]` is a cristal clear dictionary.* type of `api_response` and `api_response.data[0]` ``` type(api_response) <class 'giphy_client.models.inline_response_200.InlineResponse200'> type(api_response.data[0]) <class 'giphy_client.models.gif.Gif'> ``` You can follow for giphy\_client [documentation link](https://github.com/Giphy/giphy-python-client#documentation-for-models) for more-details **Solution**: ``` result = api_response.data[0].to_dict() ## NOTE to_dict function of giphy_client.models.gif.Gif return JsonResponse(result) ```
``` render(request, template_name, context=None, content_type=None, status=None, using=None) ``` > > `render()` Combines a given template with a given context dictionary > and returns an HttpResponse object with that rendered text. > > > You can either use Django defaults `JsonResponse` class or Django REST framework `Response` class to return JSON responses. ``` from django.http import JsonResponse return JsonResponse(data=api_response.data) from rest_framework.response import Response return Response(data=api_response.data) ``` tried it on the ipython shell and it works just fine. ``` In [15]: response = Response(api_response.data[0]) In [16]: response Out[16]: <Response status_code=200, "text/html; charset=utf-8"> ``` `response.data` gives me the serialized response.
16,518,142
I'm trying out threads in python. I want a spinning cursor to display while another method runs (for 5-10 mins). I've done out some code but am wondering is this how you would do it? i don't like to use globals, so I assume there is a better way? ``` c = True def b(): for j in itertools.cycle('/-\|'): if (c == True): sys.stdout.write(j) sys.stdout.flush() time.sleep(0.1) sys.stdout.write('\b') else: return def a(): global c #code does stuff here for 5-10 minutes #simulate with sleep time.sleep(2) c = False Thread(target = a).start() Thread(target = b).start() ``` EDIT: Another issue now is that when the processing ends the last element of the spinning cursor is still on screen. so something like `\` is printed.
2013/05/13
[ "https://Stackoverflow.com/questions/16518142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1803007/" ]
You could use events: <http://docs.python.org/2/library/threading.html> I tested this and it works. It also keeps everything in sync. You should avoid changing/reading the same variables in different threads without synchronizing them. ``` #!/usr/bin/python from threading import Thread from threading import Event import time import itertools import sys def b(event): for j in itertools.cycle('/-\|'): if not event.is_set(): sys.stdout.write(j) sys.stdout.flush() time.sleep(0.1) sys.stdout.write('\b') else: return def a(event): #code does stuff here for 5-10 minutes #simulate with sleep time.sleep(2) event.set() def main(): c = Event() Thread(target = a, kwargs = {'event': c}).start() Thread(target = b, kwargs = {'event': c}).start() if __name__ == "__main__": main() ``` Related to 'kwargs', from Python docs (URL in the beginning of the post): ``` class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}) ... kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}. ```
This is not properly synchronized. But I will not try to explain it all to you right now because it's a whole lot of knowledge. Try to read this: <http://effbot.org/zone/thread-synchronization.htm> But in your case it's not that bad that things aren't synchronized correctyl. The only thing that could happen, is that the spining bar spins a few ms longer than the background task actually needs.
16,518,142
I'm trying out threads in python. I want a spinning cursor to display while another method runs (for 5-10 mins). I've done out some code but am wondering is this how you would do it? i don't like to use globals, so I assume there is a better way? ``` c = True def b(): for j in itertools.cycle('/-\|'): if (c == True): sys.stdout.write(j) sys.stdout.flush() time.sleep(0.1) sys.stdout.write('\b') else: return def a(): global c #code does stuff here for 5-10 minutes #simulate with sleep time.sleep(2) c = False Thread(target = a).start() Thread(target = b).start() ``` EDIT: Another issue now is that when the processing ends the last element of the spinning cursor is still on screen. so something like `\` is printed.
2013/05/13
[ "https://Stackoverflow.com/questions/16518142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1803007/" ]
You're on the right track mostly, except for the global variable. Normally you'd needed to coordinate access to shared data like that with a lock or semaphore, but in this special case you can take a short-cut and just use whether one of the threads is running or not instead. This is what I mean: ``` from threading import Thread from threading import Event import time import itertools import sys def monitor_thread(watched_thread): chars = itertools.cycle('/-\|') while watched_thread.is_alive(): sys.stdout.write(chars.next()) sys.stdout.flush() time.sleep(0.1) sys.stdout.write('\b') def worker_thread(): # code does stuff here - simulated with sleep time.sleep(2) if __name__ == "__main__": watched_thread = Thread(target=worker_thread) watched_thread.start() Thread(target=monitor_thread, args=(watched_thread,)).start() ```
This is not properly synchronized. But I will not try to explain it all to you right now because it's a whole lot of knowledge. Try to read this: <http://effbot.org/zone/thread-synchronization.htm> But in your case it's not that bad that things aren't synchronized correctyl. The only thing that could happen, is that the spining bar spins a few ms longer than the background task actually needs.
3,076,798
I'm trying to start a text editor (nano) from inside Python, have the user enter text, and then capture the text once they writeout (Control-O). I haven't worked with the `subprocess` module before, nor pipes, so I don't know what to try next. So far I have this code: ``` a = subprocess.Popen('nano', stdout=subprocess.PIPE, shell=True) ``` Where `a` should capture the output. This code, however, doesn't bring up nano, and instead makes the python terminal behave strangely. Up and down keys (history) stop working and the backspace key becomes dysfunctional. Can someone point me in the right direction to solve this issue? I realize that I may need to read up on pipes in Python, but the only info I can find is the `pipes` module and it doesn't help much.
2010/06/19
[ "https://Stackoverflow.com/questions/3076798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104297/" ]
Control-O in Nano writes to **the file being edited**, i.e., *not* to standard output -- so, forego the attempt to capture stdout and just read the file once the user writes it out and exits Nano. E.g., on my Mac: ``` >>> import tempfile >>> f = tempfile.NamedTemporaryFile(mode='w+t', delete=False) >>> n = f.name >>> f.close() >>> import subprocess >>> subprocess.call(['nano', n]) ``` Here, I write "Hello world!" then hit control-O Return control-X , and: ``` 0 >>> with open(n) as f: print f.read() ... Hello world! >>> ```
I'm not sure you can capture what the user has entered into `nano`. After all, that's nano's job. What you can (and I think should do) to get user input from an editor is to spawn it off with a [temporary file](http://docs.python.org/library/tempfile.html). Then when the user has entered what he wants, he saves and quits. Your program reads the content from the file and then deletes it. Just spawn the editor using `os.system`. Your terminal is behaving funny because nano is a full screen program and will use terminal escape sequences (probably via. curses) the manipulate the screen and cursor. If you spawn it unattached to a terminal, it will misbehave. Also, you should consider opening `$EDITOR` if it's defined rather than nano. That's what people would expect.
61,109,903
I'm new to python and programing and I'm trying to make a code to display an image with some data from a `.fits` file. I'm first trying to make this example I found from this site: <https://docs.astropy.org/en/stable/generated/examples/io/plot_fits-image.html#sphx-glr-download-generated-examples-io-plot-fits-image-py>. When I run it, it shows everything it should, except the figure, which is the most important part. How do I make the figure show up? The code is the following: ```py import matplotlib.pyplot as plt from astropy.visualization import astropy_mpl_style plt.style.use(astropy_mpl_style) from astropy.utils.data import get_pkg_data_filename from astropy.io import fits image_file = get_pkg_data_filename('tutorials/FITS-images/HorseHead.fits') fits.info(image_file) image_data = fits.getdata(image_file, ext=0) print(image_data.shape) plt.figure() plt.imshow(image_data, cmap='gray') plt.colorbar() ```
2020/04/08
[ "https://Stackoverflow.com/questions/61109903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13263274/" ]
Do you like it better that way? ``` if ( !(profile.name.hasError || profile.crn.hasError || profile.employeesNbr.hasError || profile.phoneNumber.hasError || profile.userRole.hasError) && profile.personCheck.hasError ) { showModal.modal.error = true; } ``` or if you prefer something more fancy: ``` if ( (Object.entries(state.profile) .filter(prop => prop[1].hasError).length === 1) && // there is exactly one error state.profile.personCheck.hasError // personCheck has error ) ```
It would be easy to simplify it into a loop if you were doing the same check for all properties in the profile. Doing a different check for `personCheck` makes it hard to reduce it like that. You can use an array for all the properties that you want the same check on. ``` if (profile.personCheck.hasError && ["name", "crn", "employeesNbr", "phoneNumber", "userRole"].every(prop => !profile[prop].hasError)) { showModal.modal.error = true; } ```
61,109,903
I'm new to python and programing and I'm trying to make a code to display an image with some data from a `.fits` file. I'm first trying to make this example I found from this site: <https://docs.astropy.org/en/stable/generated/examples/io/plot_fits-image.html#sphx-glr-download-generated-examples-io-plot-fits-image-py>. When I run it, it shows everything it should, except the figure, which is the most important part. How do I make the figure show up? The code is the following: ```py import matplotlib.pyplot as plt from astropy.visualization import astropy_mpl_style plt.style.use(astropy_mpl_style) from astropy.utils.data import get_pkg_data_filename from astropy.io import fits image_file = get_pkg_data_filename('tutorials/FITS-images/HorseHead.fits') fits.info(image_file) image_data = fits.getdata(image_file, ext=0) print(image_data.shape) plt.figure() plt.imshow(image_data, cmap='gray') plt.colorbar() ```
2020/04/08
[ "https://Stackoverflow.com/questions/61109903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13263274/" ]
In the following way it would be optimized since as soon as one of the `profile.*` props has `hasError` to `true` would "returns" (due the **or** instead of **and**): the **and** (`&&`) needs to evaluate all the conditions where the **or** `||` it stops as soon as one is `true`. You can also probably remove the `if` statement: ``` showModal.modal.error = profile.personCheck.hasError && !( profile.name.hasError || profile.crn.hasError || profile.employeesNbr.hasError || profile.phoneNumber.hasError || profile.userRole.hasError) ```
Do you like it better that way? ``` if ( !(profile.name.hasError || profile.crn.hasError || profile.employeesNbr.hasError || profile.phoneNumber.hasError || profile.userRole.hasError) && profile.personCheck.hasError ) { showModal.modal.error = true; } ``` or if you prefer something more fancy: ``` if ( (Object.entries(state.profile) .filter(prop => prop[1].hasError).length === 1) && // there is exactly one error state.profile.personCheck.hasError // personCheck has error ) ```
61,109,903
I'm new to python and programing and I'm trying to make a code to display an image with some data from a `.fits` file. I'm first trying to make this example I found from this site: <https://docs.astropy.org/en/stable/generated/examples/io/plot_fits-image.html#sphx-glr-download-generated-examples-io-plot-fits-image-py>. When I run it, it shows everything it should, except the figure, which is the most important part. How do I make the figure show up? The code is the following: ```py import matplotlib.pyplot as plt from astropy.visualization import astropy_mpl_style plt.style.use(astropy_mpl_style) from astropy.utils.data import get_pkg_data_filename from astropy.io import fits image_file = get_pkg_data_filename('tutorials/FITS-images/HorseHead.fits') fits.info(image_file) image_data = fits.getdata(image_file, ext=0) print(image_data.shape) plt.figure() plt.imshow(image_data, cmap='gray') plt.colorbar() ```
2020/04/08
[ "https://Stackoverflow.com/questions/61109903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13263274/" ]
In the following way it would be optimized since as soon as one of the `profile.*` props has `hasError` to `true` would "returns" (due the **or** instead of **and**): the **and** (`&&`) needs to evaluate all the conditions where the **or** `||` it stops as soon as one is `true`. You can also probably remove the `if` statement: ``` showModal.modal.error = profile.personCheck.hasError && !( profile.name.hasError || profile.crn.hasError || profile.employeesNbr.hasError || profile.phoneNumber.hasError || profile.userRole.hasError) ```
It would be easy to simplify it into a loop if you were doing the same check for all properties in the profile. Doing a different check for `personCheck` makes it hard to reduce it like that. You can use an array for all the properties that you want the same check on. ``` if (profile.personCheck.hasError && ["name", "crn", "employeesNbr", "phoneNumber", "userRole"].every(prop => !profile[prop].hasError)) { showModal.modal.error = true; } ```
65,183,558
Let's say I want to implement some **list class** in python with extra structure, like a new constructor. I wrote: ``` import random class Lis(list): def __init__(self, n): self = [] for i in range(n): self.append(random.randint(0, 30)) ``` Now doing `Lis(3)` gives me an empty list. I don't know where I did it wrong.
2020/12/07
[ "https://Stackoverflow.com/questions/65183558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4821555/" ]
You are overriding the object with `self = []` try the following ``` import random class Lis(list): def __init__(self, n): for i in range(n): self.append(random.randint(0, 30)) ```
if you want to return a list from object call ```py class MyClass(object): def __init__(self): print "never called in this case" def __new__(cls): return [1,2,3] obj = MyClass() print(obj) ``` [How to return a value from \_\_init\_\_ in Python?](https://stackoverflow.com/questions/2491819/how-to-return-a-value-from-init-in-python) or if you want an modified object try: ```py class MyClass: def __getitem__(self, key): not_self = [] for i in range(n): not_self.append(random.randint(0, 30)) return not_self myobj = MyClass() myobj[3] #Output: 6 ``` [How to override the [] operator in Python?](https://stackoverflow.com/questions/1957780/how-to-override-the-operator-in-python) I am not sure if using self like you did is healthy.
12,454,675
I made a simple server and a simple client with `socket` module in python. server: ``` # server.py import socket s = socket.socket() host = socket.gethostname() port = 1234 s.bind((host, port)) s.listen(5) while True: c, addr = s.accept() print('Got connection from', addr) c.send(b'Thank you for your connecting') c.close() ``` and client: ``` #client.py import socket s = socket.socket() host = socket.gethostname() port = 1234 s.connect((host, port)) print(s.recv(1024)) ``` I started the server and then started 4 clients and got output in server's console as below: ```none Got connection from ('192.168.0.99', 49170) Got connection from ('192.168.0.99', 49171) Got connection from ('192.168.0.99', 49172) Got connection from ('192.168.0.99', 49173) ``` what is the second part in the tuple?
2012/09/17
[ "https://Stackoverflow.com/questions/12454675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1477871/" ]
From the [`socket` documentation](http://docs.python.org/library/socket.html): > > A pair (host, port) is used for the AF\_INET address family, where host is a string representing either a hostname in Internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer. > > > So the second value is the port number used by the client side for the connection. When a TCP/IP connection is established, the client picks an outgoing port number to communicate with the server; the server return packets are to be addressed to that port number.
Quote from [python documentation](http://docs.python.org/library/socket.html#socket.socket.accept): > > `socket.accept()` > > > Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair `(conn, address)` where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection. > > > What `address` is you can find in same doc [from words "Socket addresses are represented as follows"](http://docs.python.org/library/socket.html#module-socket).
54,730,763
I am trying to understand how RxPy works, I am getting this error > > type object 'ObservableBase' has no attribute 'create' > > > I am using python 3.6 and my code is ``` from rx import Observable stocks = [ {'TCKR': 'APPL', 'PRICE': 200}, {'TCKR': 'GOOG', 'PRICE': 90}, {'TCKR': 'TSLA', 'PRICE': 120}, {'TCKR': 'MSFT', 'PRICE': 150}, {'TCKR': 'INTL', 'PRICE': 70}, {'TCKR': 'ELLT', 'PRICE': 0} ] def buy_stock_events(observer): for stock in stocks: if (stock['PRICE'] > 100): observer.on_next(stock['TCKR']) elif (stock['PRICE'] <= 0): observer.on_error(stock['TCKR']) observer.on_completed() source = Observable.create(buy_stock_events) source.subscribe(on_next=lambda value: print("Received Instruction to buy {0}".format(value)), on_completed=lambda: print("Completed trades"), on_error=lambda e: print(e)) ```
2019/02/17
[ "https://Stackoverflow.com/questions/54730763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291507/" ]
They have updated RxPy module. Install 1.6.1, it will solve the problem. Thanks
I have found the solution, change the code from ``` from rx import Observable source = Observable.create(buy_stock_events) ``` to ``` import rx source = rx.Observable.create(buy_stock_events) ``` and it's working
54,417,893
I have a business problem, I have run the regression model in python to predict my target value. When validating it with my test set I came to know that my predicted variable is very far from my actual value. Now the thing I want to extract from this model is that, which feature played the role to deviate my predicted value from actual value (let say difference is in some threshold value)? I want to rank the features impact wise so that I could address to my client. Thanks
2019/01/29
[ "https://Stackoverflow.com/questions/54417893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4634959/" ]
It depends on the estimator you chose, linear models often have a coef\_ method you can call to get the coef used for each feature, given they are normalized this tells you what you want to know. As told above for tree model you have the feature importance. You can also use libraries like treeinterpreter described here: [Interpreting Random Forest](http://blog.datadive.net/interpreting-random-forests/) [examples](http://blog.datadive.net/random-forest-interpretation-with-scikit-learn/)
You can have a look at this - [Feature selection](https://scikit-learn.org/stable/modules/feature_selection.html)
54,417,893
I have a business problem, I have run the regression model in python to predict my target value. When validating it with my test set I came to know that my predicted variable is very far from my actual value. Now the thing I want to extract from this model is that, which feature played the role to deviate my predicted value from actual value (let say difference is in some threshold value)? I want to rank the features impact wise so that I could address to my client. Thanks
2019/01/29
[ "https://Stackoverflow.com/questions/54417893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4634959/" ]
It depends on the estimator you chose, linear models often have a coef\_ method you can call to get the coef used for each feature, given they are normalized this tells you what you want to know. As told above for tree model you have the feature importance. You can also use libraries like treeinterpreter described here: [Interpreting Random Forest](http://blog.datadive.net/interpreting-random-forests/) [examples](http://blog.datadive.net/random-forest-interpretation-with-scikit-learn/)
Check the Random [Forest Regressor](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html) - for performing Regression. ```py # Example from sklearn.ensemble import RandomForestRegressor from sklearn.datasets import make_regression X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) regr = RandomForestRegressor(max_depth=2, random_state=0, n_estimators=100) regr.fit(X, y) print(regr.feature_importances_) print(regr.predict([[0, 0, 0, 0]])) ``` Check `regr.feature_importances_` for getting the higher, more important features. Further information on [FeatureImportance](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html#sklearn.ensemble.RandomForestRegressor.feature_importances_) **Edit-1:** As pointed out in user (@blacksite) comment, only `feature_importance` does not provide complete interpretation of Random forest. For further analysis of results and responsible Features. Please refer to following blogs * <https://medium.com/usf-msds/intuitive-interpretation-of-random-forest-2238687cae45> (**preferred** as it provides multiple techniques ) * <https://blog.datadive.net/interpreting-random-forests/> (**focuses** on 1 technique but also provides python library - [treeinterpreter](https://github.com/andosa/treeinterpreter)) **More on feature\_importance:** * If you simply use the feature\_importances\_ attribute to select the features with the highest importance score. [Feature selection using feature importances](https://datascience.stackexchange.com/q/6683/9638) * Feature importance also depends on the criteria used for splitting and calculating importance [Interpreting Decision Tree in context of feature importances](https://datascience.stackexchange.com/a/37571/9638)
58,558,135
I'm writing a wrapper or pipeline to create a tfrecords dataset to which I would like to supply a function to apply to the dataset. I would like to make it possible for the user to inject a function defined in another python file which is called in my script to transform the data. Why? The only thing the user has to do is write the function which brings his data into the right format, then the existing code does the rest. I'm aware of the fact that I could have the user write the function in the same file and call it, or to have an import statement etc. So as a minimal example, I would like to have file y.py ```py def main(argv): # Parse args etc, let's assume it is there. dataset = tf.data.TFRecordDataset(args.filename) dataset = dataset.map(args.function) # Continue with doing stuff that is independent from actual content ``` So what I'd like to be able to do is something like this ``` python y.py --func x.py my_func ``` And use the function defined in x.py my\_func in dataset.map(...) Is there a way to do this in python and if yes, which is the best way to do it?
2019/10/25
[ "https://Stackoverflow.com/questions/58558135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6489953/" ]
1. Pass the name of the file as an argument to your script (and function name) 2. Read the file into a string, possibly extracting the given function 3. use Python [exec()](https://www.programiz.com/python-programming/methods/built-in/exec) to execute the code An example: ``` file = "def fun(*args): \n return args" func = "fun(1,2,3)" def execute(func, file): program = file + "\nresult = " + func local = {} exec(program, local) return local['result'] r = execute(func, file) print(r) ``` Similar to [here](https://stackoverflow.com/questions/23917776/how-do-i-get-the-return-value-when-using-python-exec-on-the-code-object-of-a-fun) however we must use `locals()` as we are not calling `exec` in global scope. Note: the use of `exec` is somewhat dangerous, you should be sure that the function is safe - if you are using it then its fine! Hope this helps.
Ok so I have composed the answer myself now using the information from comments and [this answer](https://stackoverflow.com/a/58558215/6489953). ```py import importlib, inspect, sys, os # path is given path to file, funcion_name is name of function and args are the function arguments # Create package and module name from path package = os.path.dirname(path).replace(os.path.sep,'.') module_name = os.path.basename(path).split('.')[0] # Import module and get members module = importlib.import_module(module_name, package) members = inspect.getmembers(module) # Find matching function function = [t[1] for t in members if t[0] == function_name][0] function(args) ``` This exactly solves the question, since I get a callable function object which I can call, pass around, use it as a normal function.
45,346,418
I am trying to generate word vectors using PySpark. Using gensim I can see the words and the closest words as below: ```python sentences = open(os.getcwd() + "/tweets.txt").read().splitlines() w2v_input=[] for i in sentences: tokenised=i.split() w2v_input.append(tokenised) model = word2vec.Word2Vec(w2v_input) for key in model.wv.vocab.keys(): print key print model.most_similar(positive=[key]) ``` Using PySpark ```python inp = sc.textFile("tweet.txt").map(lambda row: row.split(" ")) word2vec = Word2Vec() model = word2vec.fit(inp) ``` How can I generate the words from the vector space in model? That is the pyspark equivalent of the gensim `model.wv.vocab.keys()`? Background: I need to store the words and the synonyms from the model in a map so I can use them later for finding the sentiment of a tweet. I cannot reuse the word-vector model in the map functions in pyspark as the model belongs to the spark context (error pasted below). I want the pyspark word2vec version instead of gensim because it provides better synonyms for certain test words. ```python Exception: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation.SparkContext can only be used on the driver, not in code that it run on workers. ``` Any alternative solution is also welcome.
2017/07/27
[ "https://Stackoverflow.com/questions/45346418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6071445/" ]
The equivalent command in Spark is `model.getVectors()`, which again returns a dictionary. Here is a quick toy example with only 3 words (`alpha, beta, charlie`), adapted from the [documentation](https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.feature.Word2Vec): ```python sc.version # u'2.1.1' from pyspark.mllib.feature import Word2Vec sentence = "alpha beta " * 100 + "alpha charlie " * 10 localDoc = [sentence, sentence] doc = sc.parallelize(localDoc).map(lambda line: line.split(" ")) word2vec = Word2Vec() model = word2vec.fit(doc) model.getVectors().keys() # [u'alpha', u'beta', u'charlie'] ``` Regarding finding synonyms, you may find [another answer of mine](https://stackoverflow.com/questions/34172242/spark-word2vec-vector-mathematics/34298583#34298583) useful. Regarding the error you mention and a possible workaround, have a look at [this answer](https://stackoverflow.com/questions/41046843/how-to-load-a-word2vec-model-and-call-its-function-into-the-mapper/41190031#41190031) of mine.
And as suggested [here](https://stackoverflow.com/questions/48062278/would-model-getvectors-keys-return-all-the-keys-from-a-model), if you want to include all the words in your document set the MinCount parameter accordingly (default=5): ``` word2vec = Word2Vec() word2vec.setMinCount(1) ```
68,821,867
I'm trying to install `pyinstaller 3.5` in `python 3.4.3` but i get this error: ``` ERROR: Command "python setup.py egg_info" failed with error code 1 in C:\Users\DTI~1.DES\AppData\Local\Temp\pip-install-_dyh3r_g\pefile\ ``` The command i use is this: ``` pip install pyinstaller==3.5 ``` I'm using the latest version that `3.4.3` can use of pip, setuptools and wheel. ``` pip 19.1.1 setuptools 43.0.0 wheel 0.33.6 ``` I appreciate all the help. this is the full log: ``` pip install pyinstaller=="3.5" DEPRECATION: Python 3.4 support has been deprecated. pip 19.1 will be the last one supporting it. Please upgrade your Python as Python 3.4 won't be maintained after March 2019 (cf PEP 429). Collecting pyinstaller==3.5 Using cached https://files.pythonhosted.org/packages/e2/c9/0b44b2ea87ba36395483a672fddd07e6a9cb2b8d3c4a28d7ae76c7e7e1e5/PyInstaller-3.5.tar.gz Installing build dependencies ... done Getting requirements to build wheel ... done Preparing wheel metadata ... done Collecting pywin32-ctypes>=0.2.0 (from pyinstaller==3.5) Using cached https://files.pythonhosted.org/packages/9e/4b/3ab2720f1fa4b4bc924ef1932b842edf10007e4547ea8157b0b9fc78599a/pywin32_ctypes-0.2.0-py2.py3-none-any.whl Requirement already satisfied: setuptools in c:\python34\lib\site-packages (from pyinstaller==3.5) (43.0.0) Collecting altgraph (from pyinstaller==3.5) Using cached https://files.pythonhosted.org/packages/ee/3d/bfca21174b162f6ce674953f1b7a640c1498357fa6184776029557c25399/altgraph-0.17-py2.py3-none-any.whl Collecting pefile>=2017.8.1 (from pyinstaller==3.5) Using cached https://files.pythonhosted.org/packages/f9/1e/fc4fac0169d16a98577809400bbcfac8ad1900fa792184327b360ea51fc6/pefile-2021.5.13.tar.gz ERROR: Complete output from command python setup.py egg_info: ERROR: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\DTI~1.DES\AppData\Local\Temp\pip-install-3rgqa38b\pefile\setup.py", line 86, in <module> long_description = "\n".join(_read_doc().split('\n')), File "C:\Users\DTI~1.DES\AppData\Local\Temp\pip-install-3rgqa38b\pefile\setup.py", line 33, in _read_doc tree = ast.parse(f.read()) File "c:\python34\lib\ast.py", line 35, in parse return compile(source, filename, mode, PyCF_ONLY_AST) File "<unknown>", line 3789 f'Export directory contains more than 10 repeated entries ' ^ SyntaxError: invalid syntax ---------------------------------------- ERROR: Command "python setup.py egg_info" failed with error code 1 in C:\Users\DTI~1.DES\AppData\Local\Temp\pip-install-3rgqa38b\pefile\ ```
2021/08/17
[ "https://Stackoverflow.com/questions/68821867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15496915/" ]
`pefile` (one of the PyInstaller dependencies) [requires python >= 3.6.0](https://github.com/erocarrera/pefile/blob/master/setup.py#L89)
Try `pip install pyinstaller` This should work or If you wanted the specific version you can do that by `pip install pyinstaller == "3.5"`
8,011,087
Disclaimer: I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option. This application was developed time ago and several developers have worked on it, Having said that, the problem is this; In the api for mobile of this site (just views than returns json data), the code is looking for a token but does in the headers of request: ``` token = request.META.get('HTTP_TOKEN') ``` When I test this api locally, works fine, but in production doesn't, so, I try to figure out whats going on and found this: django converts headers, even custom headers to keys in request.META, I use urllib2 and [requests](http://readthedocs.org/docs/requests/en/latest/) for test the api and the problem in production is that in production server the request.META never has a key called HTTP\_TOKEN, so, doing a little of debug I seriously think the problem is the way we serve the django application. We are using django1.3, nginx, gunicorn, virtualenvwrapper, python2.7. My prime suspect is nginx, I think, in someway nginx receive the header but don' forward it to django, I try to do some research about this, but I only found infor about security headers and custom headers from nginx, but I dont find doc or something about how to tell nginx that allows that header and don't remove it. I need help here, the first thing is test if nginx receives the header, but I just know a little about nginx and I don't know how to tell it to log the headers of requests. Thanks **Update** [nginx conf file](http://dpaste.com/hold/652805/)
2011/11/04
[ "https://Stackoverflow.com/questions/8011087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150647/" ]
In your nginx configuration file (f.e. **mysite\_nginx.conf**) in the **server** section add this parameter: `uwsgi_pass_request_headers on;`. For example: ``` server { # the port your site will be served on listen 8000; ... underscores_in_headers on; } ``` And if access to Django goes through **uwsgi\_pass**, you need to add this one parameter `uwsgi_pass_request_headers on;` in **location** section. For example: ``` location / { include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed uwsgi_pass_request_headers on; uwsgi_pass django; } ```
The answers above are enough for us to figure out the way. But there is still an annoying point we need to know. Yes, it is very annoying. ``` proxy_set_header X_FORWARDED_FOR # oops it never works. 1.16.1 on centos7 proxy_set_header X-FORWARDED-FOR # this will do the job ``` So you get it. Underscore could never appear in the customized variable name. Use a hyphen instead. Maybe `Nginx` uses underscores in some grammar cases. Someone pointed out the official reference will be appreciated.
8,011,087
Disclaimer: I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option. This application was developed time ago and several developers have worked on it, Having said that, the problem is this; In the api for mobile of this site (just views than returns json data), the code is looking for a token but does in the headers of request: ``` token = request.META.get('HTTP_TOKEN') ``` When I test this api locally, works fine, but in production doesn't, so, I try to figure out whats going on and found this: django converts headers, even custom headers to keys in request.META, I use urllib2 and [requests](http://readthedocs.org/docs/requests/en/latest/) for test the api and the problem in production is that in production server the request.META never has a key called HTTP\_TOKEN, so, doing a little of debug I seriously think the problem is the way we serve the django application. We are using django1.3, nginx, gunicorn, virtualenvwrapper, python2.7. My prime suspect is nginx, I think, in someway nginx receive the header but don' forward it to django, I try to do some research about this, but I only found infor about security headers and custom headers from nginx, but I dont find doc or something about how to tell nginx that allows that header and don't remove it. I need help here, the first thing is test if nginx receives the header, but I just know a little about nginx and I don't know how to tell it to log the headers of requests. Thanks **Update** [nginx conf file](http://dpaste.com/hold/652805/)
2011/11/04
[ "https://Stackoverflow.com/questions/8011087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150647/" ]
If Django is accessed using uwsgi\_pass, then in the appropriate location(s) ... ``` # All request headers should be passed on by default # Make sure "Token" response header is passed to user uwsgi_pass_header Token; ``` If Django is accessed using fastcgi\_pass, then in the appropriate location(s) ... ``` # All request headers should be passed on by default # Make sure "Token" response header is passed to user fastcgi_pass_header Token; ``` If Django is accessed using proxy\_pass, then in the appropriate location(s) ... ``` # All request headers should be passed on by default # but we can make sure "Token" request header is passed to Django proxy_set_header Token $http_token; # Make sure "Token" response header is passed to user proxy_pass_header Token; ``` These should help eliminate the possibility that Nginx is not passing things along from your issue.
In your nginx configuration file (f.e. **mysite\_nginx.conf**) in the **server** section add this parameter: `uwsgi_pass_request_headers on;`. For example: ``` server { # the port your site will be served on listen 8000; ... underscores_in_headers on; } ``` And if access to Django goes through **uwsgi\_pass**, you need to add this one parameter `uwsgi_pass_request_headers on;` in **location** section. For example: ``` location / { include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed uwsgi_pass_request_headers on; uwsgi_pass django; } ```
8,011,087
Disclaimer: I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option. This application was developed time ago and several developers have worked on it, Having said that, the problem is this; In the api for mobile of this site (just views than returns json data), the code is looking for a token but does in the headers of request: ``` token = request.META.get('HTTP_TOKEN') ``` When I test this api locally, works fine, but in production doesn't, so, I try to figure out whats going on and found this: django converts headers, even custom headers to keys in request.META, I use urllib2 and [requests](http://readthedocs.org/docs/requests/en/latest/) for test the api and the problem in production is that in production server the request.META never has a key called HTTP\_TOKEN, so, doing a little of debug I seriously think the problem is the way we serve the django application. We are using django1.3, nginx, gunicorn, virtualenvwrapper, python2.7. My prime suspect is nginx, I think, in someway nginx receive the header but don' forward it to django, I try to do some research about this, but I only found infor about security headers and custom headers from nginx, but I dont find doc or something about how to tell nginx that allows that header and don't remove it. I need help here, the first thing is test if nginx receives the header, but I just know a little about nginx and I don't know how to tell it to log the headers of requests. Thanks **Update** [nginx conf file](http://dpaste.com/hold/652805/)
2011/11/04
[ "https://Stackoverflow.com/questions/8011087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150647/" ]
If Django is accessed using uwsgi\_pass, then in the appropriate location(s) ... ``` # All request headers should be passed on by default # Make sure "Token" response header is passed to user uwsgi_pass_header Token; ``` If Django is accessed using fastcgi\_pass, then in the appropriate location(s) ... ``` # All request headers should be passed on by default # Make sure "Token" response header is passed to user fastcgi_pass_header Token; ``` If Django is accessed using proxy\_pass, then in the appropriate location(s) ... ``` # All request headers should be passed on by default # but we can make sure "Token" request header is passed to Django proxy_set_header Token $http_token; # Make sure "Token" response header is passed to user proxy_pass_header Token; ``` These should help eliminate the possibility that Nginx is not passing things along from your issue.
I think this is what you need: ``` log_format combined '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" "$http_http_token" "$upstream_http_http_token"' ``` to log what is happening. You might look deeper into the proxy\_set\_header section on the upstream proxy module to see how to pass on the headers you need. You can find the documentation here: * <http://wiki.nginx.org/HttpLogModule> * <http://wiki.nginx.org/NginxHttpUpstreamModule> * <http://wiki.nginx.org/NginxHttpProxyModule#proxy_set_header> * <http://wiki.nginx.org/HttpProxyModule#proxy_pass_request_headers> The last entry seems to indicate that nginx passes most headers by default
8,011,087
Disclaimer: I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option. This application was developed time ago and several developers have worked on it, Having said that, the problem is this; In the api for mobile of this site (just views than returns json data), the code is looking for a token but does in the headers of request: ``` token = request.META.get('HTTP_TOKEN') ``` When I test this api locally, works fine, but in production doesn't, so, I try to figure out whats going on and found this: django converts headers, even custom headers to keys in request.META, I use urllib2 and [requests](http://readthedocs.org/docs/requests/en/latest/) for test the api and the problem in production is that in production server the request.META never has a key called HTTP\_TOKEN, so, doing a little of debug I seriously think the problem is the way we serve the django application. We are using django1.3, nginx, gunicorn, virtualenvwrapper, python2.7. My prime suspect is nginx, I think, in someway nginx receive the header but don' forward it to django, I try to do some research about this, but I only found infor about security headers and custom headers from nginx, but I dont find doc or something about how to tell nginx that allows that header and don't remove it. I need help here, the first thing is test if nginx receives the header, but I just know a little about nginx and I don't know how to tell it to log the headers of requests. Thanks **Update** [nginx conf file](http://dpaste.com/hold/652805/)
2011/11/04
[ "https://Stackoverflow.com/questions/8011087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150647/" ]
I didn't find a **real** answer, but was able to make a workaround. I was having the same problem with RFC standard headers if-none-match and if-modified-since, so my solution is tested for those headers. Added to my nginx config: ``` uwsgi_param HTTP_IF_NONE_MATCH $http_if_none_match; uwsgi_param HTTP_IF_MODIFIED_SINCE $http_if_modified_since; ``` I cannot explain why nginx refuses to pass these headers to uwsgi by default. This config forces it. Pages generate 304s as appropriate now. For the original question about the non-standard "token" header, this should do the trick: ``` uwsgi_param HTTP_TOKEN $http_token; ```
The answers above are enough for us to figure out the way. But there is still an annoying point we need to know. Yes, it is very annoying. ``` proxy_set_header X_FORWARDED_FOR # oops it never works. 1.16.1 on centos7 proxy_set_header X-FORWARDED-FOR # this will do the job ``` So you get it. Underscore could never appear in the customized variable name. Use a hyphen instead. Maybe `Nginx` uses underscores in some grammar cases. Someone pointed out the official reference will be appreciated.
8,011,087
Disclaimer: I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option. This application was developed time ago and several developers have worked on it, Having said that, the problem is this; In the api for mobile of this site (just views than returns json data), the code is looking for a token but does in the headers of request: ``` token = request.META.get('HTTP_TOKEN') ``` When I test this api locally, works fine, but in production doesn't, so, I try to figure out whats going on and found this: django converts headers, even custom headers to keys in request.META, I use urllib2 and [requests](http://readthedocs.org/docs/requests/en/latest/) for test the api and the problem in production is that in production server the request.META never has a key called HTTP\_TOKEN, so, doing a little of debug I seriously think the problem is the way we serve the django application. We are using django1.3, nginx, gunicorn, virtualenvwrapper, python2.7. My prime suspect is nginx, I think, in someway nginx receive the header but don' forward it to django, I try to do some research about this, but I only found infor about security headers and custom headers from nginx, but I dont find doc or something about how to tell nginx that allows that header and don't remove it. I need help here, the first thing is test if nginx receives the header, but I just know a little about nginx and I don't know how to tell it to log the headers of requests. Thanks **Update** [nginx conf file](http://dpaste.com/hold/652805/)
2011/11/04
[ "https://Stackoverflow.com/questions/8011087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150647/" ]
If Django is accessed using uwsgi\_pass, then in the appropriate location(s) ... ``` # All request headers should be passed on by default # Make sure "Token" response header is passed to user uwsgi_pass_header Token; ``` If Django is accessed using fastcgi\_pass, then in the appropriate location(s) ... ``` # All request headers should be passed on by default # Make sure "Token" response header is passed to user fastcgi_pass_header Token; ``` If Django is accessed using proxy\_pass, then in the appropriate location(s) ... ``` # All request headers should be passed on by default # but we can make sure "Token" request header is passed to Django proxy_set_header Token $http_token; # Make sure "Token" response header is passed to user proxy_pass_header Token; ``` These should help eliminate the possibility that Nginx is not passing things along from your issue.
I didn't find a **real** answer, but was able to make a workaround. I was having the same problem with RFC standard headers if-none-match and if-modified-since, so my solution is tested for those headers. Added to my nginx config: ``` uwsgi_param HTTP_IF_NONE_MATCH $http_if_none_match; uwsgi_param HTTP_IF_MODIFIED_SINCE $http_if_modified_since; ``` I cannot explain why nginx refuses to pass these headers to uwsgi by default. This config forces it. Pages generate 304s as appropriate now. For the original question about the non-standard "token" header, this should do the trick: ``` uwsgi_param HTTP_TOKEN $http_token; ```
8,011,087
Disclaimer: I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option. This application was developed time ago and several developers have worked on it, Having said that, the problem is this; In the api for mobile of this site (just views than returns json data), the code is looking for a token but does in the headers of request: ``` token = request.META.get('HTTP_TOKEN') ``` When I test this api locally, works fine, but in production doesn't, so, I try to figure out whats going on and found this: django converts headers, even custom headers to keys in request.META, I use urllib2 and [requests](http://readthedocs.org/docs/requests/en/latest/) for test the api and the problem in production is that in production server the request.META never has a key called HTTP\_TOKEN, so, doing a little of debug I seriously think the problem is the way we serve the django application. We are using django1.3, nginx, gunicorn, virtualenvwrapper, python2.7. My prime suspect is nginx, I think, in someway nginx receive the header but don' forward it to django, I try to do some research about this, but I only found infor about security headers and custom headers from nginx, but I dont find doc or something about how to tell nginx that allows that header and don't remove it. I need help here, the first thing is test if nginx receives the header, but I just know a little about nginx and I don't know how to tell it to log the headers of requests. Thanks **Update** [nginx conf file](http://dpaste.com/hold/652805/)
2011/11/04
[ "https://Stackoverflow.com/questions/8011087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150647/" ]
I think this is what you need: ``` log_format combined '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" "$http_http_token" "$upstream_http_http_token"' ``` to log what is happening. You might look deeper into the proxy\_set\_header section on the upstream proxy module to see how to pass on the headers you need. You can find the documentation here: * <http://wiki.nginx.org/HttpLogModule> * <http://wiki.nginx.org/NginxHttpUpstreamModule> * <http://wiki.nginx.org/NginxHttpProxyModule#proxy_set_header> * <http://wiki.nginx.org/HttpProxyModule#proxy_pass_request_headers> The last entry seems to indicate that nginx passes most headers by default
It depends on how the custom header is named. My was in format "SomethingLike.this", it contains a dot. It was not possible to rename the header in the request, because it is not our code. So writing this would not work: ``` proxy_set_header SomethingLike.this $http_somethinglike.this; proxy_pass_header SomethingLike.this; ``` Also this would not work: ``` underscores_in_headers on; ``` because I would need `dots_in_headers` directive which does not exist. But I found I can pass ALL headers simply by adding: ``` ignore_invalid_headers off; ``` It may be insecure to pass all headers, please use with caution.
8,011,087
Disclaimer: I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option. This application was developed time ago and several developers have worked on it, Having said that, the problem is this; In the api for mobile of this site (just views than returns json data), the code is looking for a token but does in the headers of request: ``` token = request.META.get('HTTP_TOKEN') ``` When I test this api locally, works fine, but in production doesn't, so, I try to figure out whats going on and found this: django converts headers, even custom headers to keys in request.META, I use urllib2 and [requests](http://readthedocs.org/docs/requests/en/latest/) for test the api and the problem in production is that in production server the request.META never has a key called HTTP\_TOKEN, so, doing a little of debug I seriously think the problem is the way we serve the django application. We are using django1.3, nginx, gunicorn, virtualenvwrapper, python2.7. My prime suspect is nginx, I think, in someway nginx receive the header but don' forward it to django, I try to do some research about this, but I only found infor about security headers and custom headers from nginx, but I dont find doc or something about how to tell nginx that allows that header and don't remove it. I need help here, the first thing is test if nginx receives the header, but I just know a little about nginx and I don't know how to tell it to log the headers of requests. Thanks **Update** [nginx conf file](http://dpaste.com/hold/652805/)
2011/11/04
[ "https://Stackoverflow.com/questions/8011087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150647/" ]
I think this is what you need: ``` log_format combined '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" "$http_http_token" "$upstream_http_http_token"' ``` to log what is happening. You might look deeper into the proxy\_set\_header section on the upstream proxy module to see how to pass on the headers you need. You can find the documentation here: * <http://wiki.nginx.org/HttpLogModule> * <http://wiki.nginx.org/NginxHttpUpstreamModule> * <http://wiki.nginx.org/NginxHttpProxyModule#proxy_set_header> * <http://wiki.nginx.org/HttpProxyModule#proxy_pass_request_headers> The last entry seems to indicate that nginx passes most headers by default
The answers above are enough for us to figure out the way. But there is still an annoying point we need to know. Yes, it is very annoying. ``` proxy_set_header X_FORWARDED_FOR # oops it never works. 1.16.1 on centos7 proxy_set_header X-FORWARDED-FOR # this will do the job ``` So you get it. Underscore could never appear in the customized variable name. Use a hyphen instead. Maybe `Nginx` uses underscores in some grammar cases. Someone pointed out the official reference will be appreciated.
8,011,087
Disclaimer: I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option. This application was developed time ago and several developers have worked on it, Having said that, the problem is this; In the api for mobile of this site (just views than returns json data), the code is looking for a token but does in the headers of request: ``` token = request.META.get('HTTP_TOKEN') ``` When I test this api locally, works fine, but in production doesn't, so, I try to figure out whats going on and found this: django converts headers, even custom headers to keys in request.META, I use urllib2 and [requests](http://readthedocs.org/docs/requests/en/latest/) for test the api and the problem in production is that in production server the request.META never has a key called HTTP\_TOKEN, so, doing a little of debug I seriously think the problem is the way we serve the django application. We are using django1.3, nginx, gunicorn, virtualenvwrapper, python2.7. My prime suspect is nginx, I think, in someway nginx receive the header but don' forward it to django, I try to do some research about this, but I only found infor about security headers and custom headers from nginx, but I dont find doc or something about how to tell nginx that allows that header and don't remove it. I need help here, the first thing is test if nginx receives the header, but I just know a little about nginx and I don't know how to tell it to log the headers of requests. Thanks **Update** [nginx conf file](http://dpaste.com/hold/652805/)
2011/11/04
[ "https://Stackoverflow.com/questions/8011087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150647/" ]
If Django is accessed using uwsgi\_pass, then in the appropriate location(s) ... ``` # All request headers should be passed on by default # Make sure "Token" response header is passed to user uwsgi_pass_header Token; ``` If Django is accessed using fastcgi\_pass, then in the appropriate location(s) ... ``` # All request headers should be passed on by default # Make sure "Token" response header is passed to user fastcgi_pass_header Token; ``` If Django is accessed using proxy\_pass, then in the appropriate location(s) ... ``` # All request headers should be passed on by default # but we can make sure "Token" request header is passed to Django proxy_set_header Token $http_token; # Make sure "Token" response header is passed to user proxy_pass_header Token; ``` These should help eliminate the possibility that Nginx is not passing things along from your issue.
It depends on how the custom header is named. My was in format "SomethingLike.this", it contains a dot. It was not possible to rename the header in the request, because it is not our code. So writing this would not work: ``` proxy_set_header SomethingLike.this $http_somethinglike.this; proxy_pass_header SomethingLike.this; ``` Also this would not work: ``` underscores_in_headers on; ``` because I would need `dots_in_headers` directive which does not exist. But I found I can pass ALL headers simply by adding: ``` ignore_invalid_headers off; ``` It may be insecure to pass all headers, please use with caution.
8,011,087
Disclaimer: I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option. This application was developed time ago and several developers have worked on it, Having said that, the problem is this; In the api for mobile of this site (just views than returns json data), the code is looking for a token but does in the headers of request: ``` token = request.META.get('HTTP_TOKEN') ``` When I test this api locally, works fine, but in production doesn't, so, I try to figure out whats going on and found this: django converts headers, even custom headers to keys in request.META, I use urllib2 and [requests](http://readthedocs.org/docs/requests/en/latest/) for test the api and the problem in production is that in production server the request.META never has a key called HTTP\_TOKEN, so, doing a little of debug I seriously think the problem is the way we serve the django application. We are using django1.3, nginx, gunicorn, virtualenvwrapper, python2.7. My prime suspect is nginx, I think, in someway nginx receive the header but don' forward it to django, I try to do some research about this, but I only found infor about security headers and custom headers from nginx, but I dont find doc or something about how to tell nginx that allows that header and don't remove it. I need help here, the first thing is test if nginx receives the header, but I just know a little about nginx and I don't know how to tell it to log the headers of requests. Thanks **Update** [nginx conf file](http://dpaste.com/hold/652805/)
2011/11/04
[ "https://Stackoverflow.com/questions/8011087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150647/" ]
I didn't find a **real** answer, but was able to make a workaround. I was having the same problem with RFC standard headers if-none-match and if-modified-since, so my solution is tested for those headers. Added to my nginx config: ``` uwsgi_param HTTP_IF_NONE_MATCH $http_if_none_match; uwsgi_param HTTP_IF_MODIFIED_SINCE $http_if_modified_since; ``` I cannot explain why nginx refuses to pass these headers to uwsgi by default. This config forces it. Pages generate 304s as appropriate now. For the original question about the non-standard "token" header, this should do the trick: ``` uwsgi_param HTTP_TOKEN $http_token; ```
It depends on how the custom header is named. My was in format "SomethingLike.this", it contains a dot. It was not possible to rename the header in the request, because it is not our code. So writing this would not work: ``` proxy_set_header SomethingLike.this $http_somethinglike.this; proxy_pass_header SomethingLike.this; ``` Also this would not work: ``` underscores_in_headers on; ``` because I would need `dots_in_headers` directive which does not exist. But I found I can pass ALL headers simply by adding: ``` ignore_invalid_headers off; ``` It may be insecure to pass all headers, please use with caution.
8,011,087
Disclaimer: I'm working in a project where exist an "huge" webapp that have an api for mobiles, so change the api is not an option. This application was developed time ago and several developers have worked on it, Having said that, the problem is this; In the api for mobile of this site (just views than returns json data), the code is looking for a token but does in the headers of request: ``` token = request.META.get('HTTP_TOKEN') ``` When I test this api locally, works fine, but in production doesn't, so, I try to figure out whats going on and found this: django converts headers, even custom headers to keys in request.META, I use urllib2 and [requests](http://readthedocs.org/docs/requests/en/latest/) for test the api and the problem in production is that in production server the request.META never has a key called HTTP\_TOKEN, so, doing a little of debug I seriously think the problem is the way we serve the django application. We are using django1.3, nginx, gunicorn, virtualenvwrapper, python2.7. My prime suspect is nginx, I think, in someway nginx receive the header but don' forward it to django, I try to do some research about this, but I only found infor about security headers and custom headers from nginx, but I dont find doc or something about how to tell nginx that allows that header and don't remove it. I need help here, the first thing is test if nginx receives the header, but I just know a little about nginx and I don't know how to tell it to log the headers of requests. Thanks **Update** [nginx conf file](http://dpaste.com/hold/652805/)
2011/11/04
[ "https://Stackoverflow.com/questions/8011087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150647/" ]
In your nginx configuration file (f.e. **mysite\_nginx.conf**) in the **server** section add this parameter: `uwsgi_pass_request_headers on;`. For example: ``` server { # the port your site will be served on listen 8000; ... underscores_in_headers on; } ``` And if access to Django goes through **uwsgi\_pass**, you need to add this one parameter `uwsgi_pass_request_headers on;` in **location** section. For example: ``` location / { include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed uwsgi_pass_request_headers on; uwsgi_pass django; } ```
It depends on how the custom header is named. My was in format "SomethingLike.this", it contains a dot. It was not possible to rename the header in the request, because it is not our code. So writing this would not work: ``` proxy_set_header SomethingLike.this $http_somethinglike.this; proxy_pass_header SomethingLike.this; ``` Also this would not work: ``` underscores_in_headers on; ``` because I would need `dots_in_headers` directive which does not exist. But I found I can pass ALL headers simply by adding: ``` ignore_invalid_headers off; ``` It may be insecure to pass all headers, please use with caution.
62,187,893
I am new to python and I would like to print different words from the sentence. Below is the text file ``` Test.txt 1. As more than one social media historian has reminded few people, the Stonewall uprising was a rio-— more pointedly, a riot against police brutality, in response to an NYPD raid of Greenwich Village’s Stonewall Inn, in the early morning of June 29, 1969. 2. As more than one social media historian has reminded majority people, the Stonewall uprising was a riot — more pointedly, a riot against police brutality, in response to an NYPD raid of Greenwich Village’s Stonewall Inn, in the evening of July 12, 1979. ``` From the above text file, I want 10th word(few), 11th word(people), 39th word(morning), 43rd word (1969), from the first line. And for the second line also 10th word(majority), 11th word (people), 39th word (evening), 43rd (1979). Note: In the Test.txt 1. means line one and 2. means line 2 For this, I tried using the split function. ``` with open('Test.txt', 'r') as file: for line in file: print (line.split('reminded',1)[1]) ``` This is the output that I got ``` few people, the Stonewall uprising was a riot - more pointedly, a riot against police brutality, in response to an NYPD raid of Greenwich Villagers Stonewall Inn, in the early morning of June 29, 1969. majority people, the Stonewall uprising was a riot — more pointedly, a riot against police brutality, in response to an NYPD raid of Greenwich Village’s Stonewall Inn, in the evening of July 12, 1979. ``` How do I print only one word after using split function? I am pretty that I still need to improve this code. Any help would be appreciated. Thanks in advance.
2020/06/04
[ "https://Stackoverflow.com/questions/62187893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11144691/" ]
here is your code: ``` datalist = ['few','people','morning','1969','majority','people','evening','1979'] with open('file.txt', 'r') as file: data = file.read().replace('\n', ' ') outputlist = data.replace('.','').split(" ") for data in outputlist: if data in datalist: print(data) ```
Using split("reminded"), you splitted your sentence into two pieces addressable using indexes 0 and 1, but if you want to separate the words of the second part you can do another split on space. For example: ``` line.split('reminded',1)[1].split(" ") ``` In this way you will have a list of string which contains the single words of the second part of your sentence. After this you can think about clean these words from special characters, punctuation, ecc. Follow this in order to do it: [Remove all special characters, punctuation and spaces from string](https://stackoverflow.com/questions/5843518/remove-all-special-characters-punctuation-and-spaces-from-string)
62,187,893
I am new to python and I would like to print different words from the sentence. Below is the text file ``` Test.txt 1. As more than one social media historian has reminded few people, the Stonewall uprising was a rio-— more pointedly, a riot against police brutality, in response to an NYPD raid of Greenwich Village’s Stonewall Inn, in the early morning of June 29, 1969. 2. As more than one social media historian has reminded majority people, the Stonewall uprising was a riot — more pointedly, a riot against police brutality, in response to an NYPD raid of Greenwich Village’s Stonewall Inn, in the evening of July 12, 1979. ``` From the above text file, I want 10th word(few), 11th word(people), 39th word(morning), 43rd word (1969), from the first line. And for the second line also 10th word(majority), 11th word (people), 39th word (evening), 43rd (1979). Note: In the Test.txt 1. means line one and 2. means line 2 For this, I tried using the split function. ``` with open('Test.txt', 'r') as file: for line in file: print (line.split('reminded',1)[1]) ``` This is the output that I got ``` few people, the Stonewall uprising was a riot - more pointedly, a riot against police brutality, in response to an NYPD raid of Greenwich Villagers Stonewall Inn, in the early morning of June 29, 1969. majority people, the Stonewall uprising was a riot — more pointedly, a riot against police brutality, in response to an NYPD raid of Greenwich Village’s Stonewall Inn, in the evening of July 12, 1979. ``` How do I print only one word after using split function? I am pretty that I still need to improve this code. Any help would be appreciated. Thanks in advance.
2020/06/04
[ "https://Stackoverflow.com/questions/62187893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11144691/" ]
here is your code: ``` datalist = ['few','people','morning','1969','majority','people','evening','1979'] with open('file.txt', 'r') as file: data = file.read().replace('\n', ' ') outputlist = data.replace('.','').split(" ") for data in outputlist: if data in datalist: print(data) ```
``` text = "1. This is something abc Yes I like to swim No My Hair is real.\n2. i like to bike uphill and smile" split_text = text.split("\n", 1) #split on new line SomeWordFirstHalf = split_text[0].split() SomeWordSecondHalf = split_text[1].split() print(SomeWordFirstHalf[3]) print(SomeWordSecondHalf[5]) ```
7,538,628
So, once again, I make a nice python program which makes my life ever the more easier and saves a lot of time. Ofcourse, this involves a virtualenv, made with the `mkvirtualenv` function of virtualenvwrapper. The project has a requirements.txt file with a few required libraries (requests too :D) and the program won't run without these libraries. I am trying to add a `bin/run-app` executable shell script which would be in my path (symlink actually). Now, inside this script, I need to switch to the virtualenv before I can run this program. So I put this in ``` #!/bin/bash # cd into the project directory workon "$(cat .venv)" python main.py ``` A file `.venv` contains the virtualenv name. But when I run this script, I get `workon: command not found` error. Of course, I have the virtualenvwrapper.sh sourced in my bashrc but it doesn't seem to be available in this shell script. So, how can I access those virtualenvwrapper functions here? Or am I doing this the wrong way? How do you launch your python tools, each of which has its own virtualenv!?
2011/09/24
[ "https://Stackoverflow.com/questions/7538628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151048/" ]
I can't find the way to trigger the commands of `virtualenvwrapper` in shell. But this trick can help: assume your env. name is `myenv`, then put following lines at the beginning of scripts: ``` ENV=myenv source $WORKON_HOME/$ENV/bin/activate ```
add these lines to your .bashrc or .bash\_profile ``` export WORKON_HOME=~/Envs source /usr/local/bin/virtualenvwrapper.sh ``` and reopen your terminal and try
7,538,628
So, once again, I make a nice python program which makes my life ever the more easier and saves a lot of time. Ofcourse, this involves a virtualenv, made with the `mkvirtualenv` function of virtualenvwrapper. The project has a requirements.txt file with a few required libraries (requests too :D) and the program won't run without these libraries. I am trying to add a `bin/run-app` executable shell script which would be in my path (symlink actually). Now, inside this script, I need to switch to the virtualenv before I can run this program. So I put this in ``` #!/bin/bash # cd into the project directory workon "$(cat .venv)" python main.py ``` A file `.venv` contains the virtualenv name. But when I run this script, I get `workon: command not found` error. Of course, I have the virtualenvwrapper.sh sourced in my bashrc but it doesn't seem to be available in this shell script. So, how can I access those virtualenvwrapper functions here? Or am I doing this the wrong way? How do you launch your python tools, each of which has its own virtualenv!?
2011/09/24
[ "https://Stackoverflow.com/questions/7538628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151048/" ]
I can't find the way to trigger the commands of `virtualenvwrapper` in shell. But this trick can help: assume your env. name is `myenv`, then put following lines at the beginning of scripts: ``` ENV=myenv source $WORKON_HOME/$ENV/bin/activate ```
Apparently, I was doing this the wrong way. Instead of saving the virtualenv's name in the .venv file, I should be putting the virtualenv's directory path. ``` (cdvirtualenv && pwd) > .venv ``` and in the `bin/run-app`, I put ``` source "$(cat .venv)/bin/activate" python main.py ``` And yay!
7,538,628
So, once again, I make a nice python program which makes my life ever the more easier and saves a lot of time. Ofcourse, this involves a virtualenv, made with the `mkvirtualenv` function of virtualenvwrapper. The project has a requirements.txt file with a few required libraries (requests too :D) and the program won't run without these libraries. I am trying to add a `bin/run-app` executable shell script which would be in my path (symlink actually). Now, inside this script, I need to switch to the virtualenv before I can run this program. So I put this in ``` #!/bin/bash # cd into the project directory workon "$(cat .venv)" python main.py ``` A file `.venv` contains the virtualenv name. But when I run this script, I get `workon: command not found` error. Of course, I have the virtualenvwrapper.sh sourced in my bashrc but it doesn't seem to be available in this shell script. So, how can I access those virtualenvwrapper functions here? Or am I doing this the wrong way? How do you launch your python tools, each of which has its own virtualenv!?
2011/09/24
[ "https://Stackoverflow.com/questions/7538628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151048/" ]
It's a [known issue](https://bitbucket.org/dhellmann/virtualenvwrapper/issue/219/cant-deactivate-active-virtualenv-from). As a workaround, you can make the content of the script a function and place it in either `~/.bashrc` or `~/.profile` ``` function run-app() { workon "$(cat .venv)" python main.py } ```
add these lines to your .bashrc or .bash\_profile ``` export WORKON_HOME=~/Envs source /usr/local/bin/virtualenvwrapper.sh ``` and reopen your terminal and try
7,538,628
So, once again, I make a nice python program which makes my life ever the more easier and saves a lot of time. Ofcourse, this involves a virtualenv, made with the `mkvirtualenv` function of virtualenvwrapper. The project has a requirements.txt file with a few required libraries (requests too :D) and the program won't run without these libraries. I am trying to add a `bin/run-app` executable shell script which would be in my path (symlink actually). Now, inside this script, I need to switch to the virtualenv before I can run this program. So I put this in ``` #!/bin/bash # cd into the project directory workon "$(cat .venv)" python main.py ``` A file `.venv` contains the virtualenv name. But when I run this script, I get `workon: command not found` error. Of course, I have the virtualenvwrapper.sh sourced in my bashrc but it doesn't seem to be available in this shell script. So, how can I access those virtualenvwrapper functions here? Or am I doing this the wrong way? How do you launch your python tools, each of which has its own virtualenv!?
2011/09/24
[ "https://Stackoverflow.com/questions/7538628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151048/" ]
It's a [known issue](https://bitbucket.org/dhellmann/virtualenvwrapper/issue/219/cant-deactivate-active-virtualenv-from). As a workaround, you can make the content of the script a function and place it in either `~/.bashrc` or `~/.profile` ``` function run-app() { workon "$(cat .venv)" python main.py } ```
If your Python script requires a particular virtualenv then put/install it in virtualenv's `bin` directory. If you need access to that script outside of the environment then you could make a symlink. main.py from virtualenv's `bin`: ``` #!/path/to/virtualenv/bin/python import yourmodule if __name__=="__main__": yourmodule.main() ``` Symlink in your PATH: ``` pymain -> /path/to/virtualenv/bin/main.py ``` In bin/run-app: ``` #!/bin/sh # cd into the project directory pymain arg1 arg2 ... ```
7,538,628
So, once again, I make a nice python program which makes my life ever the more easier and saves a lot of time. Ofcourse, this involves a virtualenv, made with the `mkvirtualenv` function of virtualenvwrapper. The project has a requirements.txt file with a few required libraries (requests too :D) and the program won't run without these libraries. I am trying to add a `bin/run-app` executable shell script which would be in my path (symlink actually). Now, inside this script, I need to switch to the virtualenv before I can run this program. So I put this in ``` #!/bin/bash # cd into the project directory workon "$(cat .venv)" python main.py ``` A file `.venv` contains the virtualenv name. But when I run this script, I get `workon: command not found` error. Of course, I have the virtualenvwrapper.sh sourced in my bashrc but it doesn't seem to be available in this shell script. So, how can I access those virtualenvwrapper functions here? Or am I doing this the wrong way? How do you launch your python tools, each of which has its own virtualenv!?
2011/09/24
[ "https://Stackoverflow.com/questions/7538628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151048/" ]
Just source the `virtualenvwrapper.sh` script in your script to import the virtualenvwrapper's functions. You should then be able to use the `workon` function in your script. And maybe better, you could create a shell script (you could name it `venv-run.sh` for example) to run any Python script into a given virtualenv, and place it in `/usr/bin`, `/usr/local/bin`, or any directory which is in your `PATH`. Such a script could look like this: ``` #!/bin/sh # if virtualenvwrapper.sh is in your PATH (i.e. installed with pip) source `which virtualenvwrapper.sh` #source /path/to/virtualenvwrapper.sh # if it's not in your PATH workon $1 python $2 deactivate ``` And could be used simply like `venv-run.sh my_virtualenv /path/to/script.py`
It's a [known issue](https://bitbucket.org/dhellmann/virtualenvwrapper/issue/219/cant-deactivate-active-virtualenv-from). As a workaround, you can make the content of the script a function and place it in either `~/.bashrc` or `~/.profile` ``` function run-app() { workon "$(cat .venv)" python main.py } ```