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
49,510,289
I have a gigantic excel workbook with a lot of personal data. Each person has a unique numeric identifier, but has multiple rows of information. I want to filter all the content through that identifier, and then copy the resulting rows to a template excel workbook and save the results. I'm trying to do this with Python and openpyxl. I thought that applying an AutoFilter and then copying the results would solve the problem. But it seems that openpyxl can only apply the AutoFilter and [not do the actual filtering?](https://openpyxl.readthedocs.io/en/2.5/filters.html) I tried to follow the answer to [this question](https://stackoverflow.com/questions/47918217/python3-openpyxl-copying-data-from-row-that-contains-certain-value-to-new-sheet), but it won't do anything. I want to filter the number in column D (4). ``` import openpyxl, os from openpyxl.utils import range_boundaries #Intitializes workbooks print('Opening data file...') min_col, min_row, max_col, max_row = range_boundaries("A:AG") wb = openpyxl.load_workbook('Data.xlsx') ws = wb.active template = openpyxl.load_workbook('Template.xlsx') templatews = template.active #Asks for numeric identifier print('Done! Now introduce identifier:') filterNumber = input() #Does the actual thing for row in ws.iter_rows(): if row[3].value == str(filterNumber): templatews.append((cell.value for cell in row[min_col-1:max_col])) #Saves the results template.save('templatesave.xlsx') print('All done! Have fun!') ``` Any insight on this will be appreciated. Thanks! EDIT: corrected column number according to @alexis suggestion, although it has not solved the issue. SOLVED: it turns out that the IF statement asks for an integer, not a string. Using **int()** solved the problem. ``` for row in ws.iter_rows(): if row[3].value == int(filterNumber): templatews.append((cell.value for cell in row[min_col-1:max_col])) ```
2018/03/27
[ "https://Stackoverflow.com/questions/49510289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9553462/" ]
When int is defined the memory would be allocated based on compiler option ( it can be 4 to 8 bytes). The number assigned to int is stored as is. e.g int a = 86; The number 86 would be stored at memory allocated for a. When char is defined , there are numbers assigned to each character. When these character needs to be printed the same would print but when its stored in memory it would stored as number. These are called ASCII character, there are some more. The allocation to store is 1Byte because with 1Byte you can represent 2^8 symbols.
> > if a number is stored as a character it will contain 1 byte per character of the number(not 4 bytes)? for example if I make an int variable of the number 8 and a char variable of '8' the int variable will have consumed more memory? > > > Yes, since it is guaranteed that (assuming 8-bit bytes): ``` sizeof(char) == 1 sizeof(int) >= 2 ``` --- > > if I create an int variable as the number 12345 and a character array of "12345" the character array will have consumed more memory? > > > Correct. See the different between: ``` strlen("12345") == 5 sizeof(12345) >= 2 ``` Of course, for small numbers like `7`, it is not true: ``` strlen("7") == 1 sizeof(7) >= 2 ``` --- > > in text files if numbers are stored are they considered as integers or characters? > > > To read any data (be it in a file or in a clay tablet!) you need to know its [encoding](https://en.wikipedia.org/wiki/Code). If it is a *text* file, then *typically* the numbers will be encoded using characters, possibly in their decimal representation. If it is a *binary* file, then you *may* find them written as they are stored in memory for a particular computer. In short, it depends.
57,230,353
I am working on a Python program for displaying photos on the Raspberry Pi (Model B Revision 2.0 with 512MB RAM). It uses Tk for displaying the images. The program is mostly finished, but I ran into an issue where the program is terminated by the kernel because of low memory. This seems to happen randomly. I do not understand why this happens. I have noticed that during image switching, the CPU spikes up significantly (up to 90%). I therefore thought that it might be an issue with the CPU not keeping up between two images and then falling behind and running out of memory. To test this I increased the timeout between showing images to 1 minute, but that did not help. My question is, whether I am doing something wrong/inefficiently in the code (see below)? If not: I am considering switching to PyQt, because it seems to accelerate graphics with OpenGL (from what I read). Is this true and/or do you think that this might help with the issue I am facing? This is my current Python code: ``` # From: https://stackoverflow.com/questions/19838972/how-to-update-an-image-on-a-canvas import os from pathlib import Path from tkinter import * from PIL import Image, ExifTags, ImageTk import ipdb class MainWindow(): def __init__(self, main): self.my_images = [] self._imageDirectory = str(Path.home().joinpath("./Pictures/rpictureframe")) self.main = main w, h = main.winfo_screenwidth(), root.winfo_screenheight() self.w, self.h = w, h main.attributes("-fullscreen", True) # REF: https://stackoverflow.com/questions/45136287/python-tkinter-toggle-quit-fullscreen-image-with-double-mouse-click main.focus_set() self.canvas = Canvas(main, width=w, height=h) self.canvas.configure(background="black", highlightthickness=0) self.canvas.pack() self.firstCall = True # set first image on canvas self.image_on_canvas = self.canvas.create_image(w/2, h/2, image = self.getNextImage()) ### replacing getNextImage instead of getNextImageV1 here fails @property def imageDirectory(self): return self._imageDirectory @imageDirectory.setter def setImageDirectory(self,imageDirectory): self._imageDirectory = imageDirectory def getNextImage(self): if self.my_images == []: self.my_images = os.listdir(self.imageDirectory) currentImagePath = self.imageDirectory + "/" + self.my_images.pop() self.currentImage = self.readImage(currentImagePath, self.w, self.h) return self.currentImage def readImage(self,imagePath,w,h): pilImage = Image.open(imagePath) pilImage = self.rotateImage(pilImage) pilImage = self.resizeImage(pilImage,w,h) return ImageTk.PhotoImage(pilImage) def rotateImage(self,image): # REF: https://stackoverflow.com/a/26928142/653770 try: for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation]=='Orientation': break exif=dict(image._getexif().items()) if exif[orientation] == 3: image=image.rotate(180, expand=True) elif exif[orientation] == 6: image=image.rotate(270, expand=True) elif exif[orientation] == 8: image=image.rotate(90, expand=True) except (AttributeError, KeyError, IndexError): # cases: image don't have getexif pass return image def resizeImage(self,pilImage,w,h): imgWidth, imgHeight = pilImage.size if imgWidth > w or imgHeight > h: ratio = min(w/imgWidth, h/imgHeight) imgWidth = int(imgWidth*ratio) imgHeight = int(imgHeight*ratio) pilImage = pilImage.resize((imgWidth,imgHeight), Image.ANTIALIAS) return pilImage def update_image(self): # REF: https://stackoverflow.com/questions/7573031/when-i-use-update-with-tkinter-my-label-writes-another-line-instead-of-rewriti/7582458# self.canvas.itemconfig(self.image_on_canvas, image = self.getNextImage()) ### replacing getNextImage instead of getNextImageV1 here fails self.main.after(5000, self.update_image) root = Tk() app = MainWindow(root) app.update_image() root.mainloop() ``` **UPDATE:** Below you will find the current code that still produces the out-of-memory issue. You can find the dmesg out-of-memory error here: <https://pastebin.com/feTFLSxq> Furthermore this is the periodic (every second) output from `top`: <https://pastebin.com/PX99VqX0> I have plotted the columns 6 and 7 (memory usage) of the `top` output: [![Plot top memory usage.](https://i.stack.imgur.com/2OEF2.png)](https://i.stack.imgur.com/2OEF2.png) As you can see, there does not appear to be a continues increase in memory usage as I would expect from a memory leak. This is my current code: ``` # From: https://stackoverflow.com/questions/19838972/how-to-update-an-image-on-a-canvas import glob from pathlib import Path from tkinter import * from PIL import Image, ExifTags, ImageTk class MainWindow(): def __init__(self, main): self.my_images = [] self._imageDirectory = str(Path.home().joinpath("Pictures/rpictureframe")) self.main = main w, h = main.winfo_screenwidth(), root.winfo_screenheight() self.w, self.h = w, h # main.attributes("-fullscreen", True) # REF: https://stackoverflow.com/questions/45136287/python-tkinter-toggle-quit-fullscreen-image-with-double-mouse-click main.focus_set() self.canvas = Canvas(main, width=w, height=h) self.canvas.configure(background="black", highlightthickness=0) self.canvas.pack() # set first image on canvas self.image_on_canvas = self.canvas.create_image(w / 2, h / 2, image=self.getNextImage()) ### replacing getNextImage instead of getNextImageV1 here fails @property def imageDirectory(self): return self._imageDirectory @imageDirectory.setter def setImageDirectory(self, imageDirectory): self._imageDirectory = imageDirectory def getNextImage(self): if self.my_images == []: # self.my_images = os.listdir(self.imageDirectory) self.my_images = glob.glob(f"{self.imageDirectory}/*.jpg") currentImagePath = self.my_images.pop() self.currentImage = self.readImage(currentImagePath, self.w, self.h) return self.currentImage def readImage(self, imagePath, w, h): with Image.open(imagePath) as pilImage: pilImage = self.rotateImage(pilImage) pilImage = self.resizeImage(pilImage, w, h) return ImageTk.PhotoImage(pilImage) def rotateImage(self, image): # REF: https://stackoverflow.com/a/26928142/653770 try: for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == 'Orientation': break exif = dict(image._getexif().items()) if exif[orientation] == 3: image = image.rotate(180, expand=True) elif exif[orientation] == 6: image = image.rotate(270, expand=True) elif exif[orientation] == 8: image = image.rotate(90, expand=True) except (AttributeError, KeyError, IndexError): # cases: image don't have getexif pass return image def resizeImage(self, pilImage, w, h): imgWidth, imgHeight = pilImage.size if imgWidth > w or imgHeight > h: ratio = min(w / imgWidth, h / imgHeight) imgWidth = int(imgWidth * ratio) imgHeight = int(imgHeight * ratio) pilImage = pilImage.resize((imgWidth, imgHeight), Image.ANTIALIAS) return pilImage def update_image(self): # REF: https://stackoverflow.com/questions/7573031/when-i-use-update-with-tkinter-my-label-writes-another-line-instead-of-rewriti/7582458# self.canvas.itemconfig(self.image_on_canvas, image=self.getNextImage()) ### replacing getNextImage instead of getNextImageV1 here fails self.main.after(30000, self.update_image) root = Tk() app = MainWindow(root) app.update_image() root.mainloop() ```
2019/07/27
[ "https://Stackoverflow.com/questions/57230353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/653770/" ]
I believe there is a memory leak when you open the image files with PIL and don't close them. To avoid it, you must call `Image.close()`, or better yet consider using the `with` syntax. ``` def readImage(self,imagePath,w,h): with Image.open(imagePath) as pilImage: pilImage = self.rotateImage(pilImage) pilImage = self.resizeImage(pilImage,w,h) return ImageTk.PhotoImage(pilImage) ```
I run the code on my machine and I noticed similiar spikes. After some memory adjustments on a virtual machine I had a system without swap (turned of to get the crash "faster") and approximately 250Mb free memory. While base memory usage was somewhere around 120Mb, the image change was between 190Mb and 200Mb (using images with a file size of 6,6Mb and 5184x3456 pixel) similiar to your plot. Then I copied a bigger (panorama) image (8,1Mb with 20707x2406 pixel) to the folder - and voila the machine got stuck. I could see that the memory usage of the process reached 315Mb and the system became unusable (after 1 minute I "pulled the plug" on the VM). So I think your problem has nothing todo with the actual code, but with the pictures you are trying to load (and the limited amount of RAM/Swap from your system). Maybe skipping the rotate and resize functions might mitigate your problem...
20,578,798
I'm new to python dictionaries as well as nesting. Here's what I'm trying to find - I have objects that all have the same attributes: color and height. I need to compare all the attributes and make of list of all the ones that match. ``` matchList = [] dict = {obj1:{'color': (1,0,0), 'height': 10.6}, obj2:{'color': (1,0.5,0), 'height': 5}, obj3:{'color': (1,0.5,0), 'height': 5}, obj4:{'color': (1,0,0), 'height': 10.6}} ``` I need to find a way to compare each of the objs to one another and create a nested list of all the ones that match. So if obj1 and obj4 match, and obj2 & 3 match, I want this is my result: ``` matchList = [[obj1, obj4], [obj2, obj3]] ``` How would I go about doing this?
2013/12/14
[ "https://Stackoverflow.com/questions/20578798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3101267/" ]
**Update:** Found this great article from [Matt Gaunt](https://plus.google.com/+MattGaunt/posts) (a Google Employee) on adding a Translucent theme to Android apps. It is very thorough and addresses some of the issues many people seem to be having while implementing this style: [Translucent Theme in Android](http://blog.gauntface.co.uk/2014/01/10/translucent-theme-in-android/) Just add the following to your custom style. This prevents the shifting of the content behind the ActionBar and up to the top of the window, not sure about the bottom of the screen though. ``` <item name="android:fitsSystemWindows">true</item> ``` Credit: [Transparent Status Bar System UI on Kit-Kat](https://stackoverflow.com/questions/20167755/transparent-status-bar-system-ui-on-4-4-kit-kat)
It looks like all you need to do is add this element to the themes you want a translucent status bar on: ``` <item name="android:windowTranslucentStatus">true</item> ```
20,578,798
I'm new to python dictionaries as well as nesting. Here's what I'm trying to find - I have objects that all have the same attributes: color and height. I need to compare all the attributes and make of list of all the ones that match. ``` matchList = [] dict = {obj1:{'color': (1,0,0), 'height': 10.6}, obj2:{'color': (1,0.5,0), 'height': 5}, obj3:{'color': (1,0.5,0), 'height': 5}, obj4:{'color': (1,0,0), 'height': 10.6}} ``` I need to find a way to compare each of the objs to one another and create a nested list of all the ones that match. So if obj1 and obj4 match, and obj2 & 3 match, I want this is my result: ``` matchList = [[obj1, obj4], [obj2, obj3]] ``` How would I go about doing this?
2013/12/14
[ "https://Stackoverflow.com/questions/20578798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3101267/" ]
It looks like all you need to do is add this element to the themes you want a translucent status bar on: ``` <item name="android:windowTranslucentStatus">true</item> ```
You're very close you just need to update your view background colors: ``` <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffd060" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/background_light" <!-- your stuff here --> </LinearLayout> </FrameLayout> ``` Specifying a global background color in your AppBaseTheme would also work but would likely cause a mess as it would end up been the default background color for everything.
20,578,798
I'm new to python dictionaries as well as nesting. Here's what I'm trying to find - I have objects that all have the same attributes: color and height. I need to compare all the attributes and make of list of all the ones that match. ``` matchList = [] dict = {obj1:{'color': (1,0,0), 'height': 10.6}, obj2:{'color': (1,0.5,0), 'height': 5}, obj3:{'color': (1,0.5,0), 'height': 5}, obj4:{'color': (1,0,0), 'height': 10.6}} ``` I need to find a way to compare each of the objs to one another and create a nested list of all the ones that match. So if obj1 and obj4 match, and obj2 & 3 match, I want this is my result: ``` matchList = [[obj1, obj4], [obj2, obj3]] ``` How would I go about doing this?
2013/12/14
[ "https://Stackoverflow.com/questions/20578798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3101267/" ]
It looks like all you need to do is add this element to the themes you want a translucent status bar on: ``` <item name="android:windowTranslucentStatus">true</item> ```
To change the color of the status bar to windowBackground ``` <item name="android:windowBackground">@color/window_bg</item> ``` To add the translucent effect to status and navigation bar ``` <item name="android:windowTranslucentStatus">true</item> <item name="android:windowTranslucentNavigation">true</item> ```
20,578,798
I'm new to python dictionaries as well as nesting. Here's what I'm trying to find - I have objects that all have the same attributes: color and height. I need to compare all the attributes and make of list of all the ones that match. ``` matchList = [] dict = {obj1:{'color': (1,0,0), 'height': 10.6}, obj2:{'color': (1,0.5,0), 'height': 5}, obj3:{'color': (1,0.5,0), 'height': 5}, obj4:{'color': (1,0,0), 'height': 10.6}} ``` I need to find a way to compare each of the objs to one another and create a nested list of all the ones that match. So if obj1 and obj4 match, and obj2 & 3 match, I want this is my result: ``` matchList = [[obj1, obj4], [obj2, obj3]] ``` How would I go about doing this?
2013/12/14
[ "https://Stackoverflow.com/questions/20578798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3101267/" ]
**Update:** Found this great article from [Matt Gaunt](https://plus.google.com/+MattGaunt/posts) (a Google Employee) on adding a Translucent theme to Android apps. It is very thorough and addresses some of the issues many people seem to be having while implementing this style: [Translucent Theme in Android](http://blog.gauntface.co.uk/2014/01/10/translucent-theme-in-android/) Just add the following to your custom style. This prevents the shifting of the content behind the ActionBar and up to the top of the window, not sure about the bottom of the screen though. ``` <item name="android:fitsSystemWindows">true</item> ``` Credit: [Transparent Status Bar System UI on Kit-Kat](https://stackoverflow.com/questions/20167755/transparent-status-bar-system-ui-on-4-4-kit-kat)
You're very close you just need to update your view background colors: ``` <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffd060" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/background_light" <!-- your stuff here --> </LinearLayout> </FrameLayout> ``` Specifying a global background color in your AppBaseTheme would also work but would likely cause a mess as it would end up been the default background color for everything.
20,578,798
I'm new to python dictionaries as well as nesting. Here's what I'm trying to find - I have objects that all have the same attributes: color and height. I need to compare all the attributes and make of list of all the ones that match. ``` matchList = [] dict = {obj1:{'color': (1,0,0), 'height': 10.6}, obj2:{'color': (1,0.5,0), 'height': 5}, obj3:{'color': (1,0.5,0), 'height': 5}, obj4:{'color': (1,0,0), 'height': 10.6}} ``` I need to find a way to compare each of the objs to one another and create a nested list of all the ones that match. So if obj1 and obj4 match, and obj2 & 3 match, I want this is my result: ``` matchList = [[obj1, obj4], [obj2, obj3]] ``` How would I go about doing this?
2013/12/14
[ "https://Stackoverflow.com/questions/20578798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3101267/" ]
**Update:** Found this great article from [Matt Gaunt](https://plus.google.com/+MattGaunt/posts) (a Google Employee) on adding a Translucent theme to Android apps. It is very thorough and addresses some of the issues many people seem to be having while implementing this style: [Translucent Theme in Android](http://blog.gauntface.co.uk/2014/01/10/translucent-theme-in-android/) Just add the following to your custom style. This prevents the shifting of the content behind the ActionBar and up to the top of the window, not sure about the bottom of the screen though. ``` <item name="android:fitsSystemWindows">true</item> ``` Credit: [Transparent Status Bar System UI on Kit-Kat](https://stackoverflow.com/questions/20167755/transparent-status-bar-system-ui-on-4-4-kit-kat)
Add these lines in your main theme ``` <style name="AppTheme" parent="android:Theme.Holo.Light"> <item name="android:windowTranslucentStatus">true</item> <item name="android:windowTranslucentNavigation">true</item> <item name="android:fitsSystemWindows">true</item> </style> ```
20,578,798
I'm new to python dictionaries as well as nesting. Here's what I'm trying to find - I have objects that all have the same attributes: color and height. I need to compare all the attributes and make of list of all the ones that match. ``` matchList = [] dict = {obj1:{'color': (1,0,0), 'height': 10.6}, obj2:{'color': (1,0.5,0), 'height': 5}, obj3:{'color': (1,0.5,0), 'height': 5}, obj4:{'color': (1,0,0), 'height': 10.6}} ``` I need to find a way to compare each of the objs to one another and create a nested list of all the ones that match. So if obj1 and obj4 match, and obj2 & 3 match, I want this is my result: ``` matchList = [[obj1, obj4], [obj2, obj3]] ``` How would I go about doing this?
2013/12/14
[ "https://Stackoverflow.com/questions/20578798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3101267/" ]
**Update:** Found this great article from [Matt Gaunt](https://plus.google.com/+MattGaunt/posts) (a Google Employee) on adding a Translucent theme to Android apps. It is very thorough and addresses some of the issues many people seem to be having while implementing this style: [Translucent Theme in Android](http://blog.gauntface.co.uk/2014/01/10/translucent-theme-in-android/) Just add the following to your custom style. This prevents the shifting of the content behind the ActionBar and up to the top of the window, not sure about the bottom of the screen though. ``` <item name="android:fitsSystemWindows">true</item> ``` Credit: [Transparent Status Bar System UI on Kit-Kat](https://stackoverflow.com/questions/20167755/transparent-status-bar-system-ui-on-4-4-kit-kat)
To change the color of the status bar to windowBackground ``` <item name="android:windowBackground">@color/window_bg</item> ``` To add the translucent effect to status and navigation bar ``` <item name="android:windowTranslucentStatus">true</item> <item name="android:windowTranslucentNavigation">true</item> ```
20,578,798
I'm new to python dictionaries as well as nesting. Here's what I'm trying to find - I have objects that all have the same attributes: color and height. I need to compare all the attributes and make of list of all the ones that match. ``` matchList = [] dict = {obj1:{'color': (1,0,0), 'height': 10.6}, obj2:{'color': (1,0.5,0), 'height': 5}, obj3:{'color': (1,0.5,0), 'height': 5}, obj4:{'color': (1,0,0), 'height': 10.6}} ``` I need to find a way to compare each of the objs to one another and create a nested list of all the ones that match. So if obj1 and obj4 match, and obj2 & 3 match, I want this is my result: ``` matchList = [[obj1, obj4], [obj2, obj3]] ``` How would I go about doing this?
2013/12/14
[ "https://Stackoverflow.com/questions/20578798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3101267/" ]
Add these lines in your main theme ``` <style name="AppTheme" parent="android:Theme.Holo.Light"> <item name="android:windowTranslucentStatus">true</item> <item name="android:windowTranslucentNavigation">true</item> <item name="android:fitsSystemWindows">true</item> </style> ```
You're very close you just need to update your view background colors: ``` <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffd060" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/background_light" <!-- your stuff here --> </LinearLayout> </FrameLayout> ``` Specifying a global background color in your AppBaseTheme would also work but would likely cause a mess as it would end up been the default background color for everything.
20,578,798
I'm new to python dictionaries as well as nesting. Here's what I'm trying to find - I have objects that all have the same attributes: color and height. I need to compare all the attributes and make of list of all the ones that match. ``` matchList = [] dict = {obj1:{'color': (1,0,0), 'height': 10.6}, obj2:{'color': (1,0.5,0), 'height': 5}, obj3:{'color': (1,0.5,0), 'height': 5}, obj4:{'color': (1,0,0), 'height': 10.6}} ``` I need to find a way to compare each of the objs to one another and create a nested list of all the ones that match. So if obj1 and obj4 match, and obj2 & 3 match, I want this is my result: ``` matchList = [[obj1, obj4], [obj2, obj3]] ``` How would I go about doing this?
2013/12/14
[ "https://Stackoverflow.com/questions/20578798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3101267/" ]
Add these lines in your main theme ``` <style name="AppTheme" parent="android:Theme.Holo.Light"> <item name="android:windowTranslucentStatus">true</item> <item name="android:windowTranslucentNavigation">true</item> <item name="android:fitsSystemWindows">true</item> </style> ```
To change the color of the status bar to windowBackground ``` <item name="android:windowBackground">@color/window_bg</item> ``` To add the translucent effect to status and navigation bar ``` <item name="android:windowTranslucentStatus">true</item> <item name="android:windowTranslucentNavigation">true</item> ```
48,921,068
I am using `python 3` and `django 1.11` got the following data in a `.sql` file: How do I use `DecimalField` and `DateField` components to represent the fields correctly. I was thinking of doing something like this: e.g `per_diem = models.DecimalField(max_digits=12, decimal_places=2,null=False)` `` ``` CREATE TABLE employee_per_diem ( employee_per_diem_id serial primary key, employee_month_id integer references employee_month not gs, travel_date date not null, return_date date not null, days_travelled integer not null, per_diem float default 0 not null, cash_paid float default 0 not null, tax_amount float default 0 not null, full_amount float default 0 not null, ); ``` Am I adding the `null` correctly?
2018/02/22
[ "https://Stackoverflow.com/questions/48921068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8342189/" ]
The first one is from the apache servlet API for status codes from Interface HttpServletResponse found [here](https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServletResponse.html) > > SC\_NOT\_FOUND - Status code (404) indicating that the requested > resource is not available. > > > The second one is from spring framework http status codes constants from [here](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/HttpStatus.html) > > NOT\_FOUND 404 Not Found. > > > For spring Framework (& spring boot) the second one is used widely.
There is no difference, it is same status code for HTTP from different libraries.
30,578,381
I am trying to compile opencv on Slackware 4.1. However I encountered the following error each time. ``` In file included from /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:29:0, from /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:65: /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:35:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererStreamInfoClass; /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:83:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererContainerInfoClass; /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:104:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererAudioInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:129:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererVideoInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:159:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererSubtitleInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:202:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererInfoClass; ^ In file included from /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:65:0: /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:47:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstEncodingProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:66:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingContainerProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:85:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingVideoProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:104:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingAudioProfileClass; ^ /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp: In member function 'virtual bool CvCapture_GStreamer::grabFrame()': /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:232:57: error: 'gst_app_sink_pull_sample' was not declared in this scope sample = gst_app_sink_pull_sample(GST_APP_SINK(sink)); ^ make[2]: *** [modules/highgui/CMakeFiles/opencv_highgui.dir/src/cap_gstreamer.cpp.o] Error 1 ``` The configuration report for the compilation is as follows: ``` -- General configuration for OpenCV 2.4.11 ===================================== -- Version control: unknown -- -- Platform: -- Host: Linux 3.10.17 i686 -- CMake: 2.8.12 -- CMake generator: Unix Makefiles -- CMake build tool: /usr/bin/gmake -- Configuration: Release -- -- C/C++: -- Built as dynamic libs?: YES -- C++ Compiler: /usr/bin/c++ (ver 4.8.2) -- C++ flags (Release): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -O2 -DNDEBUG -DNDEBUG -- C++ flags (Debug): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -g -O0 -DDEBUG -D_DEBUG -- C Compiler: /usr/bin/cc -- C flags (Release): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -O2 -DNDEBUG -DNDEBUG -- C flags (Debug): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -g -O0 -DDEBUG -D_DEBUG -- Linker flags (Release): -- Linker flags (Debug): -- Precompiled headers: NO -- -- OpenCV modules: -- To be built: core flann imgproc highgui features2d calib3d ml video legacy objdetect photo gpu ocl nonfree contrib stitching superres ts videostab -- Disabled: world -- Disabled by dependency: - -- Unavailable: androidcamera dynamicuda java python viz -- -- GUI: -- QT 4.x: YES (ver 4.8.5 EDITION = OpenSource) -- QT OpenGL support: NO -- OpenGL support: NO -- VTK support: NO -- -- Media I/O: -- ZLib: /usr/lib/libz.so (ver 1.2.8) -- JPEG: /usr/lib/libjpeg.so (ver 80) -- PNG: /usr/lib/libpng.so (ver 1.4.12) -- TIFF: /usr/lib/libtiff.so (ver 42 - 3.9.7) -- JPEG 2000: build (ver 1.900.1) -- OpenEXR: build (ver 1.7.1) -- -- Video I/O: -- DC1394 1.x: NO -- DC1394 2.x: YES (ver 2.2.2) -- FFMPEG: NO -- codec: NO -- format: NO -- util: NO -- swscale: NO -- gentoo-style: NO -- GStreamer: -- base: YES (ver 0.10.36) -- video: YES (ver 0.10.36) -- app: YES (ver 0.10.36) -- riff: YES (ver 0.10.36) -- pbutils: YES (ver 0.10.36) -- OpenNI: NO -- OpenNI PrimeSensor Modules: NO -- PvAPI: NO -- GigEVisionSDK: NO -- UniCap: NO -- UniCap ucil: NO -- V4L/V4L2: Using libv4l1 (ver 0.9.5) / libv4l2 (ver 0.9.5) -- XIMEA: NO -- Xine: NO -- -- Other third-party libraries: -- Use IPP: NO -- Use Eigen: NO -- Use TBB: NO -- Use OpenMP: NO -- Use GCD NO -- Use Concurrency NO -- Use C=: NO -- Use Cuda: NO -- Use OpenCL: YES -- -- OpenCL: -- Version: dynamic -- Include path: /tmp/SBo/opencv-2.4.11/3rdparty/include/opencl/1.2 -- Use AMD FFT: NO -- Use AMD BLAS: NO -- -- Python: -- Interpreter: /usr/bin/python2 (ver 2.7.5) -- -- Java: -- ant: NO -- JNI: /usr/lib/java/include /usr/lib/java/include/linux /usr/lib/java/include -- Java tests: NO -- -- Documentation: -- Build Documentation: NO -- Sphinx: NO -- PdfLaTeX compiler: /usr/share/texmf/bin/pdflatex -- Doxygen: YES (/usr/bin/doxygen) -- -- Tests and samples: -- Tests: YES -- Performance tests: YES -- C/C++ Examples: NO -- -- Install path: /usr -- -- cvconfig.h is in: /tmp/SBo/opencv-2.4.11/build ``` I looked through the opencv requirement from below link <http://docs.opencv.org/doc/tutorials/introduction/linux_install/linux_install.html#linux-installation> That I need ffmpeg or libav packages, which I cannot find under standard slackware 14.1 packages. But I installed gstreamer completely instead (gstreamer, gst-pluigns-base, and good) and the error I encountered above definitely has something to do with gstreamer.
2015/06/01
[ "https://Stackoverflow.com/questions/30578381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4962063/" ]
It worked for me after I set WITH\_GSTREAMER\_0\_10 to ON
I am using Ubuntu 12.04 but got the same error. This can be avoided by using the **-D WITH\_GSTREAMER=OFF** parameter. As advised [here](http://code.opencv.org/issues/3953) and [here](https://stackoverflow.com/questions/23669638/installing-opencv-on-ubuntu-12-04). Then [here](https://gist.github.com/melvincabatuan/c8a95cf4beef39614ce0) they advise to update gstreamer, but this didn't fix it for me. I still want to verify this with a fresh installation.
30,578,381
I am trying to compile opencv on Slackware 4.1. However I encountered the following error each time. ``` In file included from /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:29:0, from /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:65: /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:35:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererStreamInfoClass; /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:83:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererContainerInfoClass; /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:104:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererAudioInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:129:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererVideoInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:159:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererSubtitleInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:202:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererInfoClass; ^ In file included from /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:65:0: /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:47:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstEncodingProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:66:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingContainerProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:85:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingVideoProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:104:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingAudioProfileClass; ^ /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp: In member function 'virtual bool CvCapture_GStreamer::grabFrame()': /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:232:57: error: 'gst_app_sink_pull_sample' was not declared in this scope sample = gst_app_sink_pull_sample(GST_APP_SINK(sink)); ^ make[2]: *** [modules/highgui/CMakeFiles/opencv_highgui.dir/src/cap_gstreamer.cpp.o] Error 1 ``` The configuration report for the compilation is as follows: ``` -- General configuration for OpenCV 2.4.11 ===================================== -- Version control: unknown -- -- Platform: -- Host: Linux 3.10.17 i686 -- CMake: 2.8.12 -- CMake generator: Unix Makefiles -- CMake build tool: /usr/bin/gmake -- Configuration: Release -- -- C/C++: -- Built as dynamic libs?: YES -- C++ Compiler: /usr/bin/c++ (ver 4.8.2) -- C++ flags (Release): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -O2 -DNDEBUG -DNDEBUG -- C++ flags (Debug): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -g -O0 -DDEBUG -D_DEBUG -- C Compiler: /usr/bin/cc -- C flags (Release): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -O2 -DNDEBUG -DNDEBUG -- C flags (Debug): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -g -O0 -DDEBUG -D_DEBUG -- Linker flags (Release): -- Linker flags (Debug): -- Precompiled headers: NO -- -- OpenCV modules: -- To be built: core flann imgproc highgui features2d calib3d ml video legacy objdetect photo gpu ocl nonfree contrib stitching superres ts videostab -- Disabled: world -- Disabled by dependency: - -- Unavailable: androidcamera dynamicuda java python viz -- -- GUI: -- QT 4.x: YES (ver 4.8.5 EDITION = OpenSource) -- QT OpenGL support: NO -- OpenGL support: NO -- VTK support: NO -- -- Media I/O: -- ZLib: /usr/lib/libz.so (ver 1.2.8) -- JPEG: /usr/lib/libjpeg.so (ver 80) -- PNG: /usr/lib/libpng.so (ver 1.4.12) -- TIFF: /usr/lib/libtiff.so (ver 42 - 3.9.7) -- JPEG 2000: build (ver 1.900.1) -- OpenEXR: build (ver 1.7.1) -- -- Video I/O: -- DC1394 1.x: NO -- DC1394 2.x: YES (ver 2.2.2) -- FFMPEG: NO -- codec: NO -- format: NO -- util: NO -- swscale: NO -- gentoo-style: NO -- GStreamer: -- base: YES (ver 0.10.36) -- video: YES (ver 0.10.36) -- app: YES (ver 0.10.36) -- riff: YES (ver 0.10.36) -- pbutils: YES (ver 0.10.36) -- OpenNI: NO -- OpenNI PrimeSensor Modules: NO -- PvAPI: NO -- GigEVisionSDK: NO -- UniCap: NO -- UniCap ucil: NO -- V4L/V4L2: Using libv4l1 (ver 0.9.5) / libv4l2 (ver 0.9.5) -- XIMEA: NO -- Xine: NO -- -- Other third-party libraries: -- Use IPP: NO -- Use Eigen: NO -- Use TBB: NO -- Use OpenMP: NO -- Use GCD NO -- Use Concurrency NO -- Use C=: NO -- Use Cuda: NO -- Use OpenCL: YES -- -- OpenCL: -- Version: dynamic -- Include path: /tmp/SBo/opencv-2.4.11/3rdparty/include/opencl/1.2 -- Use AMD FFT: NO -- Use AMD BLAS: NO -- -- Python: -- Interpreter: /usr/bin/python2 (ver 2.7.5) -- -- Java: -- ant: NO -- JNI: /usr/lib/java/include /usr/lib/java/include/linux /usr/lib/java/include -- Java tests: NO -- -- Documentation: -- Build Documentation: NO -- Sphinx: NO -- PdfLaTeX compiler: /usr/share/texmf/bin/pdflatex -- Doxygen: YES (/usr/bin/doxygen) -- -- Tests and samples: -- Tests: YES -- Performance tests: YES -- C/C++ Examples: NO -- -- Install path: /usr -- -- cvconfig.h is in: /tmp/SBo/opencv-2.4.11/build ``` I looked through the opencv requirement from below link <http://docs.opencv.org/doc/tutorials/introduction/linux_install/linux_install.html#linux-installation> That I need ffmpeg or libav packages, which I cannot find under standard slackware 14.1 packages. But I installed gstreamer completely instead (gstreamer, gst-pluigns-base, and good) and the error I encountered above definitely has something to do with gstreamer.
2015/06/01
[ "https://Stackoverflow.com/questions/30578381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4962063/" ]
I got this fixed by installing `libgstreamer-plugins-base1.0-dev`. Before that CMake detected GStreamer version 0.10.36, after that - 1.4.5.
I am using Ubuntu 12.04 but got the same error. This can be avoided by using the **-D WITH\_GSTREAMER=OFF** parameter. As advised [here](http://code.opencv.org/issues/3953) and [here](https://stackoverflow.com/questions/23669638/installing-opencv-on-ubuntu-12-04). Then [here](https://gist.github.com/melvincabatuan/c8a95cf4beef39614ce0) they advise to update gstreamer, but this didn't fix it for me. I still want to verify this with a fresh installation.
30,578,381
I am trying to compile opencv on Slackware 4.1. However I encountered the following error each time. ``` In file included from /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:29:0, from /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:65: /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:35:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererStreamInfoClass; /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:83:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererContainerInfoClass; /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:104:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererAudioInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:129:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererVideoInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:159:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererSubtitleInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:202:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererInfoClass; ^ In file included from /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:65:0: /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:47:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstEncodingProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:66:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingContainerProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:85:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingVideoProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:104:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingAudioProfileClass; ^ /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp: In member function 'virtual bool CvCapture_GStreamer::grabFrame()': /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:232:57: error: 'gst_app_sink_pull_sample' was not declared in this scope sample = gst_app_sink_pull_sample(GST_APP_SINK(sink)); ^ make[2]: *** [modules/highgui/CMakeFiles/opencv_highgui.dir/src/cap_gstreamer.cpp.o] Error 1 ``` The configuration report for the compilation is as follows: ``` -- General configuration for OpenCV 2.4.11 ===================================== -- Version control: unknown -- -- Platform: -- Host: Linux 3.10.17 i686 -- CMake: 2.8.12 -- CMake generator: Unix Makefiles -- CMake build tool: /usr/bin/gmake -- Configuration: Release -- -- C/C++: -- Built as dynamic libs?: YES -- C++ Compiler: /usr/bin/c++ (ver 4.8.2) -- C++ flags (Release): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -O2 -DNDEBUG -DNDEBUG -- C++ flags (Debug): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -g -O0 -DDEBUG -D_DEBUG -- C Compiler: /usr/bin/cc -- C flags (Release): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -O2 -DNDEBUG -DNDEBUG -- C flags (Debug): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -g -O0 -DDEBUG -D_DEBUG -- Linker flags (Release): -- Linker flags (Debug): -- Precompiled headers: NO -- -- OpenCV modules: -- To be built: core flann imgproc highgui features2d calib3d ml video legacy objdetect photo gpu ocl nonfree contrib stitching superres ts videostab -- Disabled: world -- Disabled by dependency: - -- Unavailable: androidcamera dynamicuda java python viz -- -- GUI: -- QT 4.x: YES (ver 4.8.5 EDITION = OpenSource) -- QT OpenGL support: NO -- OpenGL support: NO -- VTK support: NO -- -- Media I/O: -- ZLib: /usr/lib/libz.so (ver 1.2.8) -- JPEG: /usr/lib/libjpeg.so (ver 80) -- PNG: /usr/lib/libpng.so (ver 1.4.12) -- TIFF: /usr/lib/libtiff.so (ver 42 - 3.9.7) -- JPEG 2000: build (ver 1.900.1) -- OpenEXR: build (ver 1.7.1) -- -- Video I/O: -- DC1394 1.x: NO -- DC1394 2.x: YES (ver 2.2.2) -- FFMPEG: NO -- codec: NO -- format: NO -- util: NO -- swscale: NO -- gentoo-style: NO -- GStreamer: -- base: YES (ver 0.10.36) -- video: YES (ver 0.10.36) -- app: YES (ver 0.10.36) -- riff: YES (ver 0.10.36) -- pbutils: YES (ver 0.10.36) -- OpenNI: NO -- OpenNI PrimeSensor Modules: NO -- PvAPI: NO -- GigEVisionSDK: NO -- UniCap: NO -- UniCap ucil: NO -- V4L/V4L2: Using libv4l1 (ver 0.9.5) / libv4l2 (ver 0.9.5) -- XIMEA: NO -- Xine: NO -- -- Other third-party libraries: -- Use IPP: NO -- Use Eigen: NO -- Use TBB: NO -- Use OpenMP: NO -- Use GCD NO -- Use Concurrency NO -- Use C=: NO -- Use Cuda: NO -- Use OpenCL: YES -- -- OpenCL: -- Version: dynamic -- Include path: /tmp/SBo/opencv-2.4.11/3rdparty/include/opencl/1.2 -- Use AMD FFT: NO -- Use AMD BLAS: NO -- -- Python: -- Interpreter: /usr/bin/python2 (ver 2.7.5) -- -- Java: -- ant: NO -- JNI: /usr/lib/java/include /usr/lib/java/include/linux /usr/lib/java/include -- Java tests: NO -- -- Documentation: -- Build Documentation: NO -- Sphinx: NO -- PdfLaTeX compiler: /usr/share/texmf/bin/pdflatex -- Doxygen: YES (/usr/bin/doxygen) -- -- Tests and samples: -- Tests: YES -- Performance tests: YES -- C/C++ Examples: NO -- -- Install path: /usr -- -- cvconfig.h is in: /tmp/SBo/opencv-2.4.11/build ``` I looked through the opencv requirement from below link <http://docs.opencv.org/doc/tutorials/introduction/linux_install/linux_install.html#linux-installation> That I need ffmpeg or libav packages, which I cannot find under standard slackware 14.1 packages. But I installed gstreamer completely instead (gstreamer, gst-pluigns-base, and good) and the error I encountered above definitely has something to do with gstreamer.
2015/06/01
[ "https://Stackoverflow.com/questions/30578381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4962063/" ]
I am using Ubuntu 12.04 but got the same error. This can be avoided by using the **-D WITH\_GSTREAMER=OFF** parameter. As advised [here](http://code.opencv.org/issues/3953) and [here](https://stackoverflow.com/questions/23669638/installing-opencv-on-ubuntu-12-04). Then [here](https://gist.github.com/melvincabatuan/c8a95cf4beef39614ce0) they advise to update gstreamer, but this didn't fix it for me. I still want to verify this with a fresh installation.
If anybody still have problem with that, try to install gstreamer1.0 properly with all that packages Example for Fedora OS: ``` dnf install gstreamer1-devel gstreamer1-plugins-base-tools gstreamer1-devel-docs gstreamer1-plugins-base-devel gstreamer1-plugins-base-devel-docs gstreamer1-plugins-good gstreamer1-plugins-good-extras gstreamer1-plugins-ugly gstreamer1-plugins-ugly-devel-docs gstreamer1-plugins-bad-free gstreamer1-plugins-bad-free-devel gstreamer1-plugins-bad-free-extras ``` Here is comprehensive installation guide for your system: [official link.](https://gstreamer.freedesktop.org/documentation/installing/on-linux.html)
30,578,381
I am trying to compile opencv on Slackware 4.1. However I encountered the following error each time. ``` In file included from /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:29:0, from /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:65: /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:35:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererStreamInfoClass; /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:83:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererContainerInfoClass; /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:104:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererAudioInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:129:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererVideoInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:159:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererSubtitleInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:202:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererInfoClass; ^ In file included from /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:65:0: /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:47:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstEncodingProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:66:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingContainerProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:85:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingVideoProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:104:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingAudioProfileClass; ^ /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp: In member function 'virtual bool CvCapture_GStreamer::grabFrame()': /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:232:57: error: 'gst_app_sink_pull_sample' was not declared in this scope sample = gst_app_sink_pull_sample(GST_APP_SINK(sink)); ^ make[2]: *** [modules/highgui/CMakeFiles/opencv_highgui.dir/src/cap_gstreamer.cpp.o] Error 1 ``` The configuration report for the compilation is as follows: ``` -- General configuration for OpenCV 2.4.11 ===================================== -- Version control: unknown -- -- Platform: -- Host: Linux 3.10.17 i686 -- CMake: 2.8.12 -- CMake generator: Unix Makefiles -- CMake build tool: /usr/bin/gmake -- Configuration: Release -- -- C/C++: -- Built as dynamic libs?: YES -- C++ Compiler: /usr/bin/c++ (ver 4.8.2) -- C++ flags (Release): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -O2 -DNDEBUG -DNDEBUG -- C++ flags (Debug): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -g -O0 -DDEBUG -D_DEBUG -- C Compiler: /usr/bin/cc -- C flags (Release): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -O2 -DNDEBUG -DNDEBUG -- C flags (Debug): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -g -O0 -DDEBUG -D_DEBUG -- Linker flags (Release): -- Linker flags (Debug): -- Precompiled headers: NO -- -- OpenCV modules: -- To be built: core flann imgproc highgui features2d calib3d ml video legacy objdetect photo gpu ocl nonfree contrib stitching superres ts videostab -- Disabled: world -- Disabled by dependency: - -- Unavailable: androidcamera dynamicuda java python viz -- -- GUI: -- QT 4.x: YES (ver 4.8.5 EDITION = OpenSource) -- QT OpenGL support: NO -- OpenGL support: NO -- VTK support: NO -- -- Media I/O: -- ZLib: /usr/lib/libz.so (ver 1.2.8) -- JPEG: /usr/lib/libjpeg.so (ver 80) -- PNG: /usr/lib/libpng.so (ver 1.4.12) -- TIFF: /usr/lib/libtiff.so (ver 42 - 3.9.7) -- JPEG 2000: build (ver 1.900.1) -- OpenEXR: build (ver 1.7.1) -- -- Video I/O: -- DC1394 1.x: NO -- DC1394 2.x: YES (ver 2.2.2) -- FFMPEG: NO -- codec: NO -- format: NO -- util: NO -- swscale: NO -- gentoo-style: NO -- GStreamer: -- base: YES (ver 0.10.36) -- video: YES (ver 0.10.36) -- app: YES (ver 0.10.36) -- riff: YES (ver 0.10.36) -- pbutils: YES (ver 0.10.36) -- OpenNI: NO -- OpenNI PrimeSensor Modules: NO -- PvAPI: NO -- GigEVisionSDK: NO -- UniCap: NO -- UniCap ucil: NO -- V4L/V4L2: Using libv4l1 (ver 0.9.5) / libv4l2 (ver 0.9.5) -- XIMEA: NO -- Xine: NO -- -- Other third-party libraries: -- Use IPP: NO -- Use Eigen: NO -- Use TBB: NO -- Use OpenMP: NO -- Use GCD NO -- Use Concurrency NO -- Use C=: NO -- Use Cuda: NO -- Use OpenCL: YES -- -- OpenCL: -- Version: dynamic -- Include path: /tmp/SBo/opencv-2.4.11/3rdparty/include/opencl/1.2 -- Use AMD FFT: NO -- Use AMD BLAS: NO -- -- Python: -- Interpreter: /usr/bin/python2 (ver 2.7.5) -- -- Java: -- ant: NO -- JNI: /usr/lib/java/include /usr/lib/java/include/linux /usr/lib/java/include -- Java tests: NO -- -- Documentation: -- Build Documentation: NO -- Sphinx: NO -- PdfLaTeX compiler: /usr/share/texmf/bin/pdflatex -- Doxygen: YES (/usr/bin/doxygen) -- -- Tests and samples: -- Tests: YES -- Performance tests: YES -- C/C++ Examples: NO -- -- Install path: /usr -- -- cvconfig.h is in: /tmp/SBo/opencv-2.4.11/build ``` I looked through the opencv requirement from below link <http://docs.opencv.org/doc/tutorials/introduction/linux_install/linux_install.html#linux-installation> That I need ffmpeg or libav packages, which I cannot find under standard slackware 14.1 packages. But I installed gstreamer completely instead (gstreamer, gst-pluigns-base, and good) and the error I encountered above definitely has something to do with gstreamer.
2015/06/01
[ "https://Stackoverflow.com/questions/30578381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4962063/" ]
I got this fixed by installing `libgstreamer-plugins-base1.0-dev`. Before that CMake detected GStreamer version 0.10.36, after that - 1.4.5.
It worked for me after I set WITH\_GSTREAMER\_0\_10 to ON
30,578,381
I am trying to compile opencv on Slackware 4.1. However I encountered the following error each time. ``` In file included from /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:29:0, from /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:65: /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:35:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererStreamInfoClass; /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:83:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererContainerInfoClass; /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:104:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererAudioInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:129:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererVideoInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:159:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererSubtitleInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:202:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererInfoClass; ^ In file included from /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:65:0: /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:47:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstEncodingProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:66:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingContainerProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:85:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingVideoProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:104:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingAudioProfileClass; ^ /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp: In member function 'virtual bool CvCapture_GStreamer::grabFrame()': /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:232:57: error: 'gst_app_sink_pull_sample' was not declared in this scope sample = gst_app_sink_pull_sample(GST_APP_SINK(sink)); ^ make[2]: *** [modules/highgui/CMakeFiles/opencv_highgui.dir/src/cap_gstreamer.cpp.o] Error 1 ``` The configuration report for the compilation is as follows: ``` -- General configuration for OpenCV 2.4.11 ===================================== -- Version control: unknown -- -- Platform: -- Host: Linux 3.10.17 i686 -- CMake: 2.8.12 -- CMake generator: Unix Makefiles -- CMake build tool: /usr/bin/gmake -- Configuration: Release -- -- C/C++: -- Built as dynamic libs?: YES -- C++ Compiler: /usr/bin/c++ (ver 4.8.2) -- C++ flags (Release): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -O2 -DNDEBUG -DNDEBUG -- C++ flags (Debug): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -g -O0 -DDEBUG -D_DEBUG -- C Compiler: /usr/bin/cc -- C flags (Release): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -O2 -DNDEBUG -DNDEBUG -- C flags (Debug): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -g -O0 -DDEBUG -D_DEBUG -- Linker flags (Release): -- Linker flags (Debug): -- Precompiled headers: NO -- -- OpenCV modules: -- To be built: core flann imgproc highgui features2d calib3d ml video legacy objdetect photo gpu ocl nonfree contrib stitching superres ts videostab -- Disabled: world -- Disabled by dependency: - -- Unavailable: androidcamera dynamicuda java python viz -- -- GUI: -- QT 4.x: YES (ver 4.8.5 EDITION = OpenSource) -- QT OpenGL support: NO -- OpenGL support: NO -- VTK support: NO -- -- Media I/O: -- ZLib: /usr/lib/libz.so (ver 1.2.8) -- JPEG: /usr/lib/libjpeg.so (ver 80) -- PNG: /usr/lib/libpng.so (ver 1.4.12) -- TIFF: /usr/lib/libtiff.so (ver 42 - 3.9.7) -- JPEG 2000: build (ver 1.900.1) -- OpenEXR: build (ver 1.7.1) -- -- Video I/O: -- DC1394 1.x: NO -- DC1394 2.x: YES (ver 2.2.2) -- FFMPEG: NO -- codec: NO -- format: NO -- util: NO -- swscale: NO -- gentoo-style: NO -- GStreamer: -- base: YES (ver 0.10.36) -- video: YES (ver 0.10.36) -- app: YES (ver 0.10.36) -- riff: YES (ver 0.10.36) -- pbutils: YES (ver 0.10.36) -- OpenNI: NO -- OpenNI PrimeSensor Modules: NO -- PvAPI: NO -- GigEVisionSDK: NO -- UniCap: NO -- UniCap ucil: NO -- V4L/V4L2: Using libv4l1 (ver 0.9.5) / libv4l2 (ver 0.9.5) -- XIMEA: NO -- Xine: NO -- -- Other third-party libraries: -- Use IPP: NO -- Use Eigen: NO -- Use TBB: NO -- Use OpenMP: NO -- Use GCD NO -- Use Concurrency NO -- Use C=: NO -- Use Cuda: NO -- Use OpenCL: YES -- -- OpenCL: -- Version: dynamic -- Include path: /tmp/SBo/opencv-2.4.11/3rdparty/include/opencl/1.2 -- Use AMD FFT: NO -- Use AMD BLAS: NO -- -- Python: -- Interpreter: /usr/bin/python2 (ver 2.7.5) -- -- Java: -- ant: NO -- JNI: /usr/lib/java/include /usr/lib/java/include/linux /usr/lib/java/include -- Java tests: NO -- -- Documentation: -- Build Documentation: NO -- Sphinx: NO -- PdfLaTeX compiler: /usr/share/texmf/bin/pdflatex -- Doxygen: YES (/usr/bin/doxygen) -- -- Tests and samples: -- Tests: YES -- Performance tests: YES -- C/C++ Examples: NO -- -- Install path: /usr -- -- cvconfig.h is in: /tmp/SBo/opencv-2.4.11/build ``` I looked through the opencv requirement from below link <http://docs.opencv.org/doc/tutorials/introduction/linux_install/linux_install.html#linux-installation> That I need ffmpeg or libav packages, which I cannot find under standard slackware 14.1 packages. But I installed gstreamer completely instead (gstreamer, gst-pluigns-base, and good) and the error I encountered above definitely has something to do with gstreamer.
2015/06/01
[ "https://Stackoverflow.com/questions/30578381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4962063/" ]
It worked for me after I set WITH\_GSTREAMER\_0\_10 to ON
If anybody still have problem with that, try to install gstreamer1.0 properly with all that packages Example for Fedora OS: ``` dnf install gstreamer1-devel gstreamer1-plugins-base-tools gstreamer1-devel-docs gstreamer1-plugins-base-devel gstreamer1-plugins-base-devel-docs gstreamer1-plugins-good gstreamer1-plugins-good-extras gstreamer1-plugins-ugly gstreamer1-plugins-ugly-devel-docs gstreamer1-plugins-bad-free gstreamer1-plugins-bad-free-devel gstreamer1-plugins-bad-free-extras ``` Here is comprehensive installation guide for your system: [official link.](https://gstreamer.freedesktop.org/documentation/installing/on-linux.html)
30,578,381
I am trying to compile opencv on Slackware 4.1. However I encountered the following error each time. ``` In file included from /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:29:0, from /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:65: /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:35:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererStreamInfoClass; /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:83:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererContainerInfoClass; /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:104:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererAudioInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:129:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererVideoInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:159:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererSubtitleInfoClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/gstdiscoverer.h:202:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstDiscovererInfoClass; ^ In file included from /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:65:0: /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:47:9: error: 'GstMiniObjectClass' does not name a type typedef GstMiniObjectClass GstEncodingProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:66:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingContainerProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:85:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingVideoProfileClass; ^ /usr/include/gstreamer-0.10/gst/pbutils/encoding-profile.h:104:9: error: 'GstEncodingProfileClass' does not name a type typedef GstEncodingProfileClass GstEncodingAudioProfileClass; ^ /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp: In member function 'virtual bool CvCapture_GStreamer::grabFrame()': /tmp/SBo/opencv-2.4.11/modules/highgui/src/cap_gstreamer.cpp:232:57: error: 'gst_app_sink_pull_sample' was not declared in this scope sample = gst_app_sink_pull_sample(GST_APP_SINK(sink)); ^ make[2]: *** [modules/highgui/CMakeFiles/opencv_highgui.dir/src/cap_gstreamer.cpp.o] Error 1 ``` The configuration report for the compilation is as follows: ``` -- General configuration for OpenCV 2.4.11 ===================================== -- Version control: unknown -- -- Platform: -- Host: Linux 3.10.17 i686 -- CMake: 2.8.12 -- CMake generator: Unix Makefiles -- CMake build tool: /usr/bin/gmake -- Configuration: Release -- -- C/C++: -- Built as dynamic libs?: YES -- C++ Compiler: /usr/bin/c++ (ver 4.8.2) -- C++ flags (Release): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -O2 -DNDEBUG -DNDEBUG -- C++ flags (Debug): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -g -O0 -DDEBUG -D_DEBUG -- C Compiler: /usr/bin/cc -- C flags (Release): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -O2 -DNDEBUG -DNDEBUG -- C flags (Debug): -O2 -march=i486 -mtune=i686 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -march=i686 -fomit-frame-pointer -msse -msse2 -msse3 -mfpmath=sse -ffunction-sections -g -O0 -DDEBUG -D_DEBUG -- Linker flags (Release): -- Linker flags (Debug): -- Precompiled headers: NO -- -- OpenCV modules: -- To be built: core flann imgproc highgui features2d calib3d ml video legacy objdetect photo gpu ocl nonfree contrib stitching superres ts videostab -- Disabled: world -- Disabled by dependency: - -- Unavailable: androidcamera dynamicuda java python viz -- -- GUI: -- QT 4.x: YES (ver 4.8.5 EDITION = OpenSource) -- QT OpenGL support: NO -- OpenGL support: NO -- VTK support: NO -- -- Media I/O: -- ZLib: /usr/lib/libz.so (ver 1.2.8) -- JPEG: /usr/lib/libjpeg.so (ver 80) -- PNG: /usr/lib/libpng.so (ver 1.4.12) -- TIFF: /usr/lib/libtiff.so (ver 42 - 3.9.7) -- JPEG 2000: build (ver 1.900.1) -- OpenEXR: build (ver 1.7.1) -- -- Video I/O: -- DC1394 1.x: NO -- DC1394 2.x: YES (ver 2.2.2) -- FFMPEG: NO -- codec: NO -- format: NO -- util: NO -- swscale: NO -- gentoo-style: NO -- GStreamer: -- base: YES (ver 0.10.36) -- video: YES (ver 0.10.36) -- app: YES (ver 0.10.36) -- riff: YES (ver 0.10.36) -- pbutils: YES (ver 0.10.36) -- OpenNI: NO -- OpenNI PrimeSensor Modules: NO -- PvAPI: NO -- GigEVisionSDK: NO -- UniCap: NO -- UniCap ucil: NO -- V4L/V4L2: Using libv4l1 (ver 0.9.5) / libv4l2 (ver 0.9.5) -- XIMEA: NO -- Xine: NO -- -- Other third-party libraries: -- Use IPP: NO -- Use Eigen: NO -- Use TBB: NO -- Use OpenMP: NO -- Use GCD NO -- Use Concurrency NO -- Use C=: NO -- Use Cuda: NO -- Use OpenCL: YES -- -- OpenCL: -- Version: dynamic -- Include path: /tmp/SBo/opencv-2.4.11/3rdparty/include/opencl/1.2 -- Use AMD FFT: NO -- Use AMD BLAS: NO -- -- Python: -- Interpreter: /usr/bin/python2 (ver 2.7.5) -- -- Java: -- ant: NO -- JNI: /usr/lib/java/include /usr/lib/java/include/linux /usr/lib/java/include -- Java tests: NO -- -- Documentation: -- Build Documentation: NO -- Sphinx: NO -- PdfLaTeX compiler: /usr/share/texmf/bin/pdflatex -- Doxygen: YES (/usr/bin/doxygen) -- -- Tests and samples: -- Tests: YES -- Performance tests: YES -- C/C++ Examples: NO -- -- Install path: /usr -- -- cvconfig.h is in: /tmp/SBo/opencv-2.4.11/build ``` I looked through the opencv requirement from below link <http://docs.opencv.org/doc/tutorials/introduction/linux_install/linux_install.html#linux-installation> That I need ffmpeg or libav packages, which I cannot find under standard slackware 14.1 packages. But I installed gstreamer completely instead (gstreamer, gst-pluigns-base, and good) and the error I encountered above definitely has something to do with gstreamer.
2015/06/01
[ "https://Stackoverflow.com/questions/30578381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4962063/" ]
I got this fixed by installing `libgstreamer-plugins-base1.0-dev`. Before that CMake detected GStreamer version 0.10.36, after that - 1.4.5.
If anybody still have problem with that, try to install gstreamer1.0 properly with all that packages Example for Fedora OS: ``` dnf install gstreamer1-devel gstreamer1-plugins-base-tools gstreamer1-devel-docs gstreamer1-plugins-base-devel gstreamer1-plugins-base-devel-docs gstreamer1-plugins-good gstreamer1-plugins-good-extras gstreamer1-plugins-ugly gstreamer1-plugins-ugly-devel-docs gstreamer1-plugins-bad-free gstreamer1-plugins-bad-free-devel gstreamer1-plugins-bad-free-extras ``` Here is comprehensive installation guide for your system: [official link.](https://gstreamer.freedesktop.org/documentation/installing/on-linux.html)
70,819,915
This is the code: ``` name = input("Enter file: ") handle = open(name) counts = dict() filetext = handle.read() for line in handle: words = line.split() for word in words: counts[word] = counts.get(word, 0) + 1 print(words) print(counts) bigcount = None bigword = None for word,count in counts.items(): if bigcount == None or count > bigcount: bigword = word bigcount = count print(filetext) print("Most common word: ", bigword, bigcount) print(counts.items()) this is the output: Enter file: pls.txt Traceback (most recent call last): File "D:\Tools\Coding\PyCharm Community Edition 2021.2.3\bin\pythonProject2\Mostcommonword.py", line 10, in <module> print(words) NameError: name 'words' is not defined ``` Process finished with exit code 1 When running the program, instead of returning the most common number, it returned None. I managed to find out that the reason for that is that the "words" list is completely empty, for some reason. The good thing about simple problems is that I know what's going on. The bad thing is that there are not many ways to fix it at all.
2022/01/23
[ "https://Stackoverflow.com/questions/70819915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18007432/" ]
After you do `handle.read()`, the file is positioned at end-of-file. There's nothing left for the `for line in handle:` to read. You either need to rewind in between (`handle.seek(0)`), or just skip the first read altogether.
You could consider building a list of lines as you iterate over the file handle rather than doing a read/seek. Also, you can work out the most frequently occurring word as you work through the file rather than doing a second pass of your dictionary. Something like this: ``` D = dict() M = 0 B = None C = list() with open('<Your filename goes here>') as txt: for line in txt: C.append(line) for word in line.strip().split(): D[word] = D.get(word, 0) + 1 if D[word] > M: B = word M = D[word] print(''.join(C)) print(f'Most common word with {M} occurrences is {B}') ```
30,421,267
I'm currently having troubles in setting `is_active` field from `False` back to `True` in Django. I have a custom Account model which is inhereted from `AbstractBaseUser` and is managed by `class AccountManager(BaseUserManager)`. By default, I override the `is_active` field to be False. However, when I try to reactivate the field again. It does update at that time in `python manage.py shell`, but when I logout and login back to the shell. The `is_active` field is still `False`. Below is my `activateUser()` function ``` def activateUser(self, account): account.is_active = True account.save() return account ``` Below is my `python manage.py shell` perform: ``` >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False >>> Account.objects.activateUser(a) >>> a.is_active True >>> exit() python manage.py shell >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False ``` **Updated:** Here is my Account class. The `activateUser()` function above is from the `AccountManager` class which is inherited from `BaseUserManager` and is managing the Account class. ``` class Account(AbstractBaseUser): """ Create a new model from AbstractBaseUser account to have our own fields """ username = models.CharField(max_length=40, unique=True) email = models.EmailField(unique=True) firstName = models.CharField(max_length=40, blank=True, null=True) lastName = models.CharField(max_length=40, blank=True, null=True) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(default=False) is_active = False objects = AccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __unicode__(self): return self.username def get_full_name(self): return self.firstName + ' ' + self.lastName def get_short_name(self): return self.firstName ```
2015/05/24
[ "https://Stackoverflow.com/questions/30421267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3773879/" ]
In Java, we have a class named `String` which has a method called `length()`. In C, you need to have a `\0` at the end of your string so you could know where your string ends. But in Java, this problem handled with the method`length()`.
C doesn't have strings as an actual data type and the convention is just that character arrays ending in a null character can be used as strings. That's what you get when you use string literals in the language and that's what you have to recreate when you don't use them. The underlying issue is that C wanted to save memory on its string representation by not storing a length (Pascal stored the string length in the first byte for example), thus the length has to follow somehow from the data, in this case by ending the data with `'\0'`.
30,421,267
I'm currently having troubles in setting `is_active` field from `False` back to `True` in Django. I have a custom Account model which is inhereted from `AbstractBaseUser` and is managed by `class AccountManager(BaseUserManager)`. By default, I override the `is_active` field to be False. However, when I try to reactivate the field again. It does update at that time in `python manage.py shell`, but when I logout and login back to the shell. The `is_active` field is still `False`. Below is my `activateUser()` function ``` def activateUser(self, account): account.is_active = True account.save() return account ``` Below is my `python manage.py shell` perform: ``` >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False >>> Account.objects.activateUser(a) >>> a.is_active True >>> exit() python manage.py shell >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False ``` **Updated:** Here is my Account class. The `activateUser()` function above is from the `AccountManager` class which is inherited from `BaseUserManager` and is managing the Account class. ``` class Account(AbstractBaseUser): """ Create a new model from AbstractBaseUser account to have our own fields """ username = models.CharField(max_length=40, unique=True) email = models.EmailField(unique=True) firstName = models.CharField(max_length=40, blank=True, null=True) lastName = models.CharField(max_length=40, blank=True, null=True) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(default=False) is_active = False objects = AccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __unicode__(self): return self.username def get_full_name(self): return self.firstName + ' ' + self.lastName def get_short_name(self): return self.firstName ```
2015/05/24
[ "https://Stackoverflow.com/questions/30421267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3773879/" ]
in C there is no type `string`, there is only a pointer to a `char`. When in C you need a string, you need to know how many characters are in the string, or have an indicator to see that you have reached the end of the string. Traditionally there are two approaches to this requirements. In the C world the convention is to terminate the string with the `\0` character. In the PASCAL world the convention is to use another variable to store the length of the string. Java uses the PASCAL convention and stores the length of the string in another variable as the content of the string. Both approaches have their merits. In the Java/PASCAL world, it is easy to know the length of the strings and a string can contain the \0 character. In C you can reuse the same character array for tail substrings etc.
In Java, we have a class named `String` which has a method called `length()`. In C, you need to have a `\0` at the end of your string so you could know where your string ends. But in Java, this problem handled with the method`length()`.
30,421,267
I'm currently having troubles in setting `is_active` field from `False` back to `True` in Django. I have a custom Account model which is inhereted from `AbstractBaseUser` and is managed by `class AccountManager(BaseUserManager)`. By default, I override the `is_active` field to be False. However, when I try to reactivate the field again. It does update at that time in `python manage.py shell`, but when I logout and login back to the shell. The `is_active` field is still `False`. Below is my `activateUser()` function ``` def activateUser(self, account): account.is_active = True account.save() return account ``` Below is my `python manage.py shell` perform: ``` >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False >>> Account.objects.activateUser(a) >>> a.is_active True >>> exit() python manage.py shell >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False ``` **Updated:** Here is my Account class. The `activateUser()` function above is from the `AccountManager` class which is inherited from `BaseUserManager` and is managing the Account class. ``` class Account(AbstractBaseUser): """ Create a new model from AbstractBaseUser account to have our own fields """ username = models.CharField(max_length=40, unique=True) email = models.EmailField(unique=True) firstName = models.CharField(max_length=40, blank=True, null=True) lastName = models.CharField(max_length=40, blank=True, null=True) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(default=False) is_active = False objects = AccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __unicode__(self): return self.username def get_full_name(self): return self.firstName + ' ' + self.lastName def get_short_name(self): return self.firstName ```
2015/05/24
[ "https://Stackoverflow.com/questions/30421267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3773879/" ]
In Java, we have a class named `String` which has a method called `length()`. In C, you need to have a `\0` at the end of your string so you could know where your string ends. But in Java, this problem handled with the method`length()`.
In Java, a string is mostly an abstraction, where you are not supposed to care about the internal representation. You have methods that perform operations on it and that allow you to obtain information about the string. In C, however, this is quite the opposite. You want to know and care a string's internal structure, in order to avoid segmentation violations. Moreover, in C the null-terminated sequence of chars that composes a string occupies a contiguous set of memory locations. Most string functions (strcmp, strcat, and so on) expect that you will have a null terminated string to know where the end of the string is. So, in case you don't have the null character in the end, then the string function can run off the end of the string.
30,421,267
I'm currently having troubles in setting `is_active` field from `False` back to `True` in Django. I have a custom Account model which is inhereted from `AbstractBaseUser` and is managed by `class AccountManager(BaseUserManager)`. By default, I override the `is_active` field to be False. However, when I try to reactivate the field again. It does update at that time in `python manage.py shell`, but when I logout and login back to the shell. The `is_active` field is still `False`. Below is my `activateUser()` function ``` def activateUser(self, account): account.is_active = True account.save() return account ``` Below is my `python manage.py shell` perform: ``` >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False >>> Account.objects.activateUser(a) >>> a.is_active True >>> exit() python manage.py shell >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False ``` **Updated:** Here is my Account class. The `activateUser()` function above is from the `AccountManager` class which is inherited from `BaseUserManager` and is managing the Account class. ``` class Account(AbstractBaseUser): """ Create a new model from AbstractBaseUser account to have our own fields """ username = models.CharField(max_length=40, unique=True) email = models.EmailField(unique=True) firstName = models.CharField(max_length=40, blank=True, null=True) lastName = models.CharField(max_length=40, blank=True, null=True) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(default=False) is_active = False objects = AccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __unicode__(self): return self.username def get_full_name(self): return self.firstName + ' ' + self.lastName def get_short_name(self): return self.firstName ```
2015/05/24
[ "https://Stackoverflow.com/questions/30421267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3773879/" ]
In Java, we have a class named `String` which has a method called `length()`. In C, you need to have a `\0` at the end of your string so you could know where your string ends. But in Java, this problem handled with the method`length()`.
As it is a board question, we have to point out two important things here: 1) First thing to confirm is, C as being a basic language and having low abstraction, it doesn't have string as a datatype. In C, string is just a collection of chars. So we need some thing to specifies where the string ends, for that we use \0 null terminator (which tells the library that, this is where the string ends) **So, why \0 null terminator:** Null termination happens to be the way chosen for C, for string literals and the standard library functions that deal with strings. Obliviously, It's convenient because the null character is not really used for anything else. It's not printable neither it's a control character nor it has any behavior defined to it (like moving the cursor in some particular way, for example \t) Also, according to the ISO C standard, section 7.1.1, defines a string this way: ``` A string is a contiguous sequence of characters terminated by and including the first null character. ``` 2) Java is a matured language, what i mean is, it is high level language than C. In Java, we can define the string as: ``` A String is defined to be a fixed length sequence of char values. All possible char values (from 0 to 65535) may be used in a String. There is no "distinguished" value that means that the string ends. ``` **So, how they track string ending?** String class provides a method called length to know the number of characters in the string. So, you can clearly see from the language implementation prescriptive that, C requires Null termination for string because, they are nothing but a sequence of characters and need a special character to determine where this sequence ends, while, java strings are implemented as classes (& objects). **Extra Notes:** I know this is not asked, but i am specifying, If you're reading the Java string's data in C code via JNI, then we use JNI functions like GetStringChars() or GetStringUTFChars(). Neither of these functions are not documented as returning null-terminated data, we should use GetStringLength() to determine its length. Likewise with GetStringUTFChars(), you must use GetStringUTF8Length() to determine its length in modified UTF-8 format.
30,421,267
I'm currently having troubles in setting `is_active` field from `False` back to `True` in Django. I have a custom Account model which is inhereted from `AbstractBaseUser` and is managed by `class AccountManager(BaseUserManager)`. By default, I override the `is_active` field to be False. However, when I try to reactivate the field again. It does update at that time in `python manage.py shell`, but when I logout and login back to the shell. The `is_active` field is still `False`. Below is my `activateUser()` function ``` def activateUser(self, account): account.is_active = True account.save() return account ``` Below is my `python manage.py shell` perform: ``` >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False >>> Account.objects.activateUser(a) >>> a.is_active True >>> exit() python manage.py shell >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False ``` **Updated:** Here is my Account class. The `activateUser()` function above is from the `AccountManager` class which is inherited from `BaseUserManager` and is managing the Account class. ``` class Account(AbstractBaseUser): """ Create a new model from AbstractBaseUser account to have our own fields """ username = models.CharField(max_length=40, unique=True) email = models.EmailField(unique=True) firstName = models.CharField(max_length=40, blank=True, null=True) lastName = models.CharField(max_length=40, blank=True, null=True) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(default=False) is_active = False objects = AccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __unicode__(self): return self.username def get_full_name(self): return self.firstName + ' ' + self.lastName def get_short_name(self): return self.firstName ```
2015/05/24
[ "https://Stackoverflow.com/questions/30421267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3773879/" ]
in C there is no type `string`, there is only a pointer to a `char`. When in C you need a string, you need to know how many characters are in the string, or have an indicator to see that you have reached the end of the string. Traditionally there are two approaches to this requirements. In the C world the convention is to terminate the string with the `\0` character. In the PASCAL world the convention is to use another variable to store the length of the string. Java uses the PASCAL convention and stores the length of the string in another variable as the content of the string. Both approaches have their merits. In the Java/PASCAL world, it is easy to know the length of the strings and a string can contain the \0 character. In C you can reuse the same character array for tail substrings etc.
C doesn't have strings as an actual data type and the convention is just that character arrays ending in a null character can be used as strings. That's what you get when you use string literals in the language and that's what you have to recreate when you don't use them. The underlying issue is that C wanted to save memory on its string representation by not storing a length (Pascal stored the string length in the first byte for example), thus the length has to follow somehow from the data, in this case by ending the data with `'\0'`.
30,421,267
I'm currently having troubles in setting `is_active` field from `False` back to `True` in Django. I have a custom Account model which is inhereted from `AbstractBaseUser` and is managed by `class AccountManager(BaseUserManager)`. By default, I override the `is_active` field to be False. However, when I try to reactivate the field again. It does update at that time in `python manage.py shell`, but when I logout and login back to the shell. The `is_active` field is still `False`. Below is my `activateUser()` function ``` def activateUser(self, account): account.is_active = True account.save() return account ``` Below is my `python manage.py shell` perform: ``` >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False >>> Account.objects.activateUser(a) >>> a.is_active True >>> exit() python manage.py shell >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False ``` **Updated:** Here is my Account class. The `activateUser()` function above is from the `AccountManager` class which is inherited from `BaseUserManager` and is managing the Account class. ``` class Account(AbstractBaseUser): """ Create a new model from AbstractBaseUser account to have our own fields """ username = models.CharField(max_length=40, unique=True) email = models.EmailField(unique=True) firstName = models.CharField(max_length=40, blank=True, null=True) lastName = models.CharField(max_length=40, blank=True, null=True) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(default=False) is_active = False objects = AccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __unicode__(self): return self.username def get_full_name(self): return self.firstName + ' ' + self.lastName def get_short_name(self): return self.firstName ```
2015/05/24
[ "https://Stackoverflow.com/questions/30421267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3773879/" ]
C doesn't have strings as an actual data type and the convention is just that character arrays ending in a null character can be used as strings. That's what you get when you use string literals in the language and that's what you have to recreate when you don't use them. The underlying issue is that C wanted to save memory on its string representation by not storing a length (Pascal stored the string length in the first byte for example), thus the length has to follow somehow from the data, in this case by ending the data with `'\0'`.
As it is a board question, we have to point out two important things here: 1) First thing to confirm is, C as being a basic language and having low abstraction, it doesn't have string as a datatype. In C, string is just a collection of chars. So we need some thing to specifies where the string ends, for that we use \0 null terminator (which tells the library that, this is where the string ends) **So, why \0 null terminator:** Null termination happens to be the way chosen for C, for string literals and the standard library functions that deal with strings. Obliviously, It's convenient because the null character is not really used for anything else. It's not printable neither it's a control character nor it has any behavior defined to it (like moving the cursor in some particular way, for example \t) Also, according to the ISO C standard, section 7.1.1, defines a string this way: ``` A string is a contiguous sequence of characters terminated by and including the first null character. ``` 2) Java is a matured language, what i mean is, it is high level language than C. In Java, we can define the string as: ``` A String is defined to be a fixed length sequence of char values. All possible char values (from 0 to 65535) may be used in a String. There is no "distinguished" value that means that the string ends. ``` **So, how they track string ending?** String class provides a method called length to know the number of characters in the string. So, you can clearly see from the language implementation prescriptive that, C requires Null termination for string because, they are nothing but a sequence of characters and need a special character to determine where this sequence ends, while, java strings are implemented as classes (& objects). **Extra Notes:** I know this is not asked, but i am specifying, If you're reading the Java string's data in C code via JNI, then we use JNI functions like GetStringChars() or GetStringUTFChars(). Neither of these functions are not documented as returning null-terminated data, we should use GetStringLength() to determine its length. Likewise with GetStringUTFChars(), you must use GetStringUTF8Length() to determine its length in modified UTF-8 format.
30,421,267
I'm currently having troubles in setting `is_active` field from `False` back to `True` in Django. I have a custom Account model which is inhereted from `AbstractBaseUser` and is managed by `class AccountManager(BaseUserManager)`. By default, I override the `is_active` field to be False. However, when I try to reactivate the field again. It does update at that time in `python manage.py shell`, but when I logout and login back to the shell. The `is_active` field is still `False`. Below is my `activateUser()` function ``` def activateUser(self, account): account.is_active = True account.save() return account ``` Below is my `python manage.py shell` perform: ``` >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False >>> Account.objects.activateUser(a) >>> a.is_active True >>> exit() python manage.py shell >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False ``` **Updated:** Here is my Account class. The `activateUser()` function above is from the `AccountManager` class which is inherited from `BaseUserManager` and is managing the Account class. ``` class Account(AbstractBaseUser): """ Create a new model from AbstractBaseUser account to have our own fields """ username = models.CharField(max_length=40, unique=True) email = models.EmailField(unique=True) firstName = models.CharField(max_length=40, blank=True, null=True) lastName = models.CharField(max_length=40, blank=True, null=True) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(default=False) is_active = False objects = AccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __unicode__(self): return self.username def get_full_name(self): return self.firstName + ' ' + self.lastName def get_short_name(self): return self.firstName ```
2015/05/24
[ "https://Stackoverflow.com/questions/30421267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3773879/" ]
in C there is no type `string`, there is only a pointer to a `char`. When in C you need a string, you need to know how many characters are in the string, or have an indicator to see that you have reached the end of the string. Traditionally there are two approaches to this requirements. In the C world the convention is to terminate the string with the `\0` character. In the PASCAL world the convention is to use another variable to store the length of the string. Java uses the PASCAL convention and stores the length of the string in another variable as the content of the string. Both approaches have their merits. In the Java/PASCAL world, it is easy to know the length of the strings and a string can contain the \0 character. In C you can reuse the same character array for tail substrings etc.
In Java, a string is mostly an abstraction, where you are not supposed to care about the internal representation. You have methods that perform operations on it and that allow you to obtain information about the string. In C, however, this is quite the opposite. You want to know and care a string's internal structure, in order to avoid segmentation violations. Moreover, in C the null-terminated sequence of chars that composes a string occupies a contiguous set of memory locations. Most string functions (strcmp, strcat, and so on) expect that you will have a null terminated string to know where the end of the string is. So, in case you don't have the null character in the end, then the string function can run off the end of the string.
30,421,267
I'm currently having troubles in setting `is_active` field from `False` back to `True` in Django. I have a custom Account model which is inhereted from `AbstractBaseUser` and is managed by `class AccountManager(BaseUserManager)`. By default, I override the `is_active` field to be False. However, when I try to reactivate the field again. It does update at that time in `python manage.py shell`, but when I logout and login back to the shell. The `is_active` field is still `False`. Below is my `activateUser()` function ``` def activateUser(self, account): account.is_active = True account.save() return account ``` Below is my `python manage.py shell` perform: ``` >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False >>> Account.objects.activateUser(a) >>> a.is_active True >>> exit() python manage.py shell >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False ``` **Updated:** Here is my Account class. The `activateUser()` function above is from the `AccountManager` class which is inherited from `BaseUserManager` and is managing the Account class. ``` class Account(AbstractBaseUser): """ Create a new model from AbstractBaseUser account to have our own fields """ username = models.CharField(max_length=40, unique=True) email = models.EmailField(unique=True) firstName = models.CharField(max_length=40, blank=True, null=True) lastName = models.CharField(max_length=40, blank=True, null=True) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(default=False) is_active = False objects = AccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __unicode__(self): return self.username def get_full_name(self): return self.firstName + ' ' + self.lastName def get_short_name(self): return self.firstName ```
2015/05/24
[ "https://Stackoverflow.com/questions/30421267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3773879/" ]
in C there is no type `string`, there is only a pointer to a `char`. When in C you need a string, you need to know how many characters are in the string, or have an indicator to see that you have reached the end of the string. Traditionally there are two approaches to this requirements. In the C world the convention is to terminate the string with the `\0` character. In the PASCAL world the convention is to use another variable to store the length of the string. Java uses the PASCAL convention and stores the length of the string in another variable as the content of the string. Both approaches have their merits. In the Java/PASCAL world, it is easy to know the length of the strings and a string can contain the \0 character. In C you can reuse the same character array for tail substrings etc.
As it is a board question, we have to point out two important things here: 1) First thing to confirm is, C as being a basic language and having low abstraction, it doesn't have string as a datatype. In C, string is just a collection of chars. So we need some thing to specifies where the string ends, for that we use \0 null terminator (which tells the library that, this is where the string ends) **So, why \0 null terminator:** Null termination happens to be the way chosen for C, for string literals and the standard library functions that deal with strings. Obliviously, It's convenient because the null character is not really used for anything else. It's not printable neither it's a control character nor it has any behavior defined to it (like moving the cursor in some particular way, for example \t) Also, according to the ISO C standard, section 7.1.1, defines a string this way: ``` A string is a contiguous sequence of characters terminated by and including the first null character. ``` 2) Java is a matured language, what i mean is, it is high level language than C. In Java, we can define the string as: ``` A String is defined to be a fixed length sequence of char values. All possible char values (from 0 to 65535) may be used in a String. There is no "distinguished" value that means that the string ends. ``` **So, how they track string ending?** String class provides a method called length to know the number of characters in the string. So, you can clearly see from the language implementation prescriptive that, C requires Null termination for string because, they are nothing but a sequence of characters and need a special character to determine where this sequence ends, while, java strings are implemented as classes (& objects). **Extra Notes:** I know this is not asked, but i am specifying, If you're reading the Java string's data in C code via JNI, then we use JNI functions like GetStringChars() or GetStringUTFChars(). Neither of these functions are not documented as returning null-terminated data, we should use GetStringLength() to determine its length. Likewise with GetStringUTFChars(), you must use GetStringUTF8Length() to determine its length in modified UTF-8 format.
30,421,267
I'm currently having troubles in setting `is_active` field from `False` back to `True` in Django. I have a custom Account model which is inhereted from `AbstractBaseUser` and is managed by `class AccountManager(BaseUserManager)`. By default, I override the `is_active` field to be False. However, when I try to reactivate the field again. It does update at that time in `python manage.py shell`, but when I logout and login back to the shell. The `is_active` field is still `False`. Below is my `activateUser()` function ``` def activateUser(self, account): account.is_active = True account.save() return account ``` Below is my `python manage.py shell` perform: ``` >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False >>> Account.objects.activateUser(a) >>> a.is_active True >>> exit() python manage.py shell >>> from authentication.models import Account >>> a = Account.objects.all()[0] >>> a.is_active False ``` **Updated:** Here is my Account class. The `activateUser()` function above is from the `AccountManager` class which is inherited from `BaseUserManager` and is managing the Account class. ``` class Account(AbstractBaseUser): """ Create a new model from AbstractBaseUser account to have our own fields """ username = models.CharField(max_length=40, unique=True) email = models.EmailField(unique=True) firstName = models.CharField(max_length=40, blank=True, null=True) lastName = models.CharField(max_length=40, blank=True, null=True) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) is_staff = models.BooleanField(default=False) is_active = False objects = AccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __unicode__(self): return self.username def get_full_name(self): return self.firstName + ' ' + self.lastName def get_short_name(self): return self.firstName ```
2015/05/24
[ "https://Stackoverflow.com/questions/30421267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3773879/" ]
In Java, a string is mostly an abstraction, where you are not supposed to care about the internal representation. You have methods that perform operations on it and that allow you to obtain information about the string. In C, however, this is quite the opposite. You want to know and care a string's internal structure, in order to avoid segmentation violations. Moreover, in C the null-terminated sequence of chars that composes a string occupies a contiguous set of memory locations. Most string functions (strcmp, strcat, and so on) expect that you will have a null terminated string to know where the end of the string is. So, in case you don't have the null character in the end, then the string function can run off the end of the string.
As it is a board question, we have to point out two important things here: 1) First thing to confirm is, C as being a basic language and having low abstraction, it doesn't have string as a datatype. In C, string is just a collection of chars. So we need some thing to specifies where the string ends, for that we use \0 null terminator (which tells the library that, this is where the string ends) **So, why \0 null terminator:** Null termination happens to be the way chosen for C, for string literals and the standard library functions that deal with strings. Obliviously, It's convenient because the null character is not really used for anything else. It's not printable neither it's a control character nor it has any behavior defined to it (like moving the cursor in some particular way, for example \t) Also, according to the ISO C standard, section 7.1.1, defines a string this way: ``` A string is a contiguous sequence of characters terminated by and including the first null character. ``` 2) Java is a matured language, what i mean is, it is high level language than C. In Java, we can define the string as: ``` A String is defined to be a fixed length sequence of char values. All possible char values (from 0 to 65535) may be used in a String. There is no "distinguished" value that means that the string ends. ``` **So, how they track string ending?** String class provides a method called length to know the number of characters in the string. So, you can clearly see from the language implementation prescriptive that, C requires Null termination for string because, they are nothing but a sequence of characters and need a special character to determine where this sequence ends, while, java strings are implemented as classes (& objects). **Extra Notes:** I know this is not asked, but i am specifying, If you're reading the Java string's data in C code via JNI, then we use JNI functions like GetStringChars() or GetStringUTFChars(). Neither of these functions are not documented as returning null-terminated data, we should use GetStringLength() to determine its length. Likewise with GetStringUTFChars(), you must use GetStringUTF8Length() to determine its length in modified UTF-8 format.
72,923,752
I am learning python. For the code below, how to convert for loop to while loop in an efficient way? ``` import pandas as pd transactions01 = [] file=open('raw-data1.txt','w') file.write('HotDogs,Buns\nHotDogs,Buns\nHotDogs,Coke,Chips\nChips,Coke\nChips,Ketchup\nHotDogs,Coke,Chips\n') file.close() file=open('raw-data1.txt','r') lines = file.readlines() for line in lines: items = line[:-1].split(',') has_item = {} for item in items: has_item[item] = 1 transactions01.append(has_item)** file.close() data = pd.DataFrame(transactions01) data.fillna(0, inplace = True) data ```
2022/07/09
[ "https://Stackoverflow.com/questions/72923752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19517608/" ]
Code : ``` i = 0 while i<len(lines): items = lines[i][:-1].split(',') has_item = {} j = 0 while j<len(items): has_item[items[j]]=1 j+=1 transactions01.append(has_item) i+=1 ```
It looks like you could just take your, use the csv module to parse the file as you've got an inconsistent number of rows per column, then turn it into a dataframe, use `pd.get_dummies` to get 0/1's per item present, then aggregate back to a row level to product your final output, eg: ``` import pandas as pd import csv with open('raw-data1.txt') as fin: df = pd.get_dummies(pd.DataFrame(csv.reader(fin)).stack()).groupby(level=0).max() ``` Will give you a `df` of: ``` Buns Chips Coke HotDogs Ketchup 0 1 0 0 1 0 1 1 0 0 1 0 2 0 1 1 1 0 3 0 1 1 0 0 4 0 1 0 0 1 5 0 1 1 1 0 ``` .. which you can then write back out as CSV if required.
38,000,412
I'm just new to python and I can't seem to find a solution to my problem, since it seems to be pretty simple. I have a geometry on paraview, I'm saving it as a vtk file and I'm trying to use python to calculate it's volume. This is the code I'm using: ``` import vtk reader = vtk.vtkPolyDataReader() reader.SetFileName("C:\Users\Pauuu\Google Drive\2016-01\SURF\Sim Vascular\Modelos\apoE183 Day 14 3D\AAA.vtk") reader.Update() polydata = reader.GetOutput() Mass = vtk.vtkMassProperties() Mass.SetInputConnection(polydata.GetOutput()) Mass.Update() print "Volume = ", Mass.GetVolume() print "Surface = ", Mass.GetSurfaceArea() ``` I think there might be a problem with the way im loding the data, and i get the `AttributeError: GetOutput`. Do you know what might be happening or what I'm doing wrong? Thank you in advance.
2016/06/23
[ "https://Stackoverflow.com/questions/38000412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6505466/" ]
Depending on your version of `vtk` package you may want to test the following syntax if your version <= `5`: ``` Mass.SetInput(polydata.GetOutput()); ``` Otherwise, the actual syntax is: ``` Mass.SetInputData(polydata.GetOutputPort()); ``` PS: you can check the python-wrapped `vtk` version by running: ``` import vtk print vtk.vtkVersion.GetVTKSourceVersion() ```
You have assigned `reader.GetOutput()` in `polydata`. From `polydata`, I believe you need to do, `polydata.GetOutputPort()`
38,000,412
I'm just new to python and I can't seem to find a solution to my problem, since it seems to be pretty simple. I have a geometry on paraview, I'm saving it as a vtk file and I'm trying to use python to calculate it's volume. This is the code I'm using: ``` import vtk reader = vtk.vtkPolyDataReader() reader.SetFileName("C:\Users\Pauuu\Google Drive\2016-01\SURF\Sim Vascular\Modelos\apoE183 Day 14 3D\AAA.vtk") reader.Update() polydata = reader.GetOutput() Mass = vtk.vtkMassProperties() Mass.SetInputConnection(polydata.GetOutput()) Mass.Update() print "Volume = ", Mass.GetVolume() print "Surface = ", Mass.GetSurfaceArea() ``` I think there might be a problem with the way im loding the data, and i get the `AttributeError: GetOutput`. Do you know what might be happening or what I'm doing wrong? Thank you in advance.
2016/06/23
[ "https://Stackoverflow.com/questions/38000412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6505466/" ]
You have assigned `reader.GetOutput()` in `polydata`. From `polydata`, I believe you need to do, `polydata.GetOutputPort()`
I guess you have VTK 6 , you can provide as input to a filter either the output port of a filter or a vtkDataObject : ``` Mass.SetInputConnection(reader.GetOutputPort()) Mass.SetInputData(polydata) #that is Mass.SetInputData(reader.GetOutput()) ``` For understanding why these method are not equivalent when updating a pipeline, and for comparison with the previous version, see <http://www.vtk.org/Wiki/VTK/VTK_6_Migration/Removal_of_GetProducerPort> <http://www.vtk.org/Wiki/VTK/VTK_6_Migration/Replacement_of_SetInput>
38,000,412
I'm just new to python and I can't seem to find a solution to my problem, since it seems to be pretty simple. I have a geometry on paraview, I'm saving it as a vtk file and I'm trying to use python to calculate it's volume. This is the code I'm using: ``` import vtk reader = vtk.vtkPolyDataReader() reader.SetFileName("C:\Users\Pauuu\Google Drive\2016-01\SURF\Sim Vascular\Modelos\apoE183 Day 14 3D\AAA.vtk") reader.Update() polydata = reader.GetOutput() Mass = vtk.vtkMassProperties() Mass.SetInputConnection(polydata.GetOutput()) Mass.Update() print "Volume = ", Mass.GetVolume() print "Surface = ", Mass.GetSurfaceArea() ``` I think there might be a problem with the way im loding the data, and i get the `AttributeError: GetOutput`. Do you know what might be happening or what I'm doing wrong? Thank you in advance.
2016/06/23
[ "https://Stackoverflow.com/questions/38000412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6505466/" ]
Depending on your version of `vtk` package you may want to test the following syntax if your version <= `5`: ``` Mass.SetInput(polydata.GetOutput()); ``` Otherwise, the actual syntax is: ``` Mass.SetInputData(polydata.GetOutputPort()); ``` PS: you can check the python-wrapped `vtk` version by running: ``` import vtk print vtk.vtkVersion.GetVTKSourceVersion() ```
I guess you have VTK 6 , you can provide as input to a filter either the output port of a filter or a vtkDataObject : ``` Mass.SetInputConnection(reader.GetOutputPort()) Mass.SetInputData(polydata) #that is Mass.SetInputData(reader.GetOutput()) ``` For understanding why these method are not equivalent when updating a pipeline, and for comparison with the previous version, see <http://www.vtk.org/Wiki/VTK/VTK_6_Migration/Removal_of_GetProducerPort> <http://www.vtk.org/Wiki/VTK/VTK_6_Migration/Replacement_of_SetInput>
32,157,861
I use this in python: ``` test = zlib.compress(test, 1) ``` And now I want to use this in java, but I don't know how. At the end I need to convert the result to a string... I wait your help! thx
2015/08/22
[ "https://Stackoverflow.com/questions/32157861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3363949/" ]
You need to be more specific in describing what you want to achieve. Are you just seeking to decompress a zlib-compressed piece of data? Or are you seeking for a way to exchange data between Python and Java, possibly by transferring it across a network? For the former, it's basically sticking the compressed datastream in an `Inflater` (not `Deflater`!). Something like: ``` Inflater decompresser = new Inflater(); decompresser.setInput(data); ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length); byte[] buffer = new byte[8192]; while (!decompresser.finished()) { int size = decompresser.inflate(buffer); bos.write(buffer, 0, size); } byte[] unzippeddata = bos.toByteArray(); decompresser.end(); ``` For the latter, alex's answer already points to Pyro/Pyrolite.
You can try using a RPC to create a server. <https://github.com/irmen/Pyro4> And access that server using java. <https://github.com/irmen/Pyrolite>
66,129,119
Trying to install freeradius package on Debian 10 buster and it fails. ``` $ sudo apt install freeradius Reading package lists... Done Building dependency tree... Done Reading state information... Done Suggested packages: freeradius-krb5 freeradius-ldap freeradius-mysql freeradius-postgresql freeradius-python3 The following NEW packages will be installed: freeradius 0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded. Need to get 555 kB of archives. After this operation, 2230 kB of additional disk space will be used. Get:1 http://ftp.de.debian.org/debian sid/main amd64 freeradius amd64 3.0.21+dfsg-2+b2 [555 kB] Fetched 555 kB in 0s (2753 kB/s) Selecting previously unselected package freeradius. (Reading database ... 140557 files and directories currently installed.) Preparing to unpack .../freeradius_3.0.21+dfsg-2+b2_amd64.deb ... Unpacking freeradius (3.0.21+dfsg-2+b2) ... Setting up freeradius (3.0.21+dfsg-2+b2) ... update-rc.d: warning: start and stop actions are no longer supported; falling back to defaults install: invalid user ‘freerad’ dpkg: error processing package freeradius (--configure): installed freeradius package post-installation script subprocess returned error exit status 1 Errors were encountered while processing: freeradius E: Sub-process /usr/bin/dpkg returned an error code (1) ``` install: invalid user ‘freerad’ Apparently it seems as if there's something wrong with the freerad user which doesn't exist? Typing / checking inside /etc/passwd file learly shows there's no such user ``` $ cat /etc/passwd | grep freer* ``` Checking the syslog shows: ``` Feb 10 00:38:45 server-1 systemd[1]: freeradius.service: Scheduled restart job, restart counter is at 277. Feb 10 00:38:45 server-1 freeradius[10918]: FreeRADIUS Version 3.0.21 Feb 10 00:38:45 server-1 freeradius[10918]: Copyright (C) 1999-2019 The FreeRADIUS server project and contributors Feb 10 00:38:45 server-1 freeradius[10918]: There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A Feb 10 00:38:45 server-1 freeradius[10918]: PARTICULAR PURPOSE Feb 10 00:38:45 server-1 freeradius[10918]: You may redistribute copies of FreeRADIUS under the terms of the Feb 10 00:38:45 server-1 freeradius[10918]: GNU General Public License Feb 10 00:38:45 server-1 freeradius[10918]: For more information about these matters, see the file named COPYRIGHT Feb 10 00:38:45 server-1 freeradius[10918]: Errors reading /etc/freeradius/3.0: Permission denied Feb 10 00:38:45 server-1 systemd[1]: freeradius.service: Control process exited, code=exited, status=1/FAILURE Feb 10 00:38:45 server-1 systemd[1]: freeradius.service: Failed with result 'exit-code'. ``` Tried a\*\*smarting this by adding the user manually with the command adduser freeradius and then tried re-installing: ``` $ sudo apt install freeradius Reading package lists... Done Building dependency tree... Done Reading state information... Done freeradius is already the newest version (3.0.21+dfsg-2+b2). 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. 1 not fully installed or removed. After this operation, 0 B of additional disk space will be used. Do you want to continue? [Y/n] y Setting up freeradius (3.0.21+dfsg-2+b2) ... update-rc.d: warning: start and stop actions are no longer supported; falling back to defaults chown: cannot access '/etc/freeradius': No such file or directory dpkg: error processing package freeradius (--configure): installed freeradius package post-installation script subprocess returned error exit status 1 Errors were encountered while processing: freeradius E: Sub-process /usr/bin/dpkg returned an error code (1) ``` now it fails prompting a new error: chown: cannot access '/etc/freeradius': No such file or directory Tried purging / removing / clean / cache deleting / rebooting and then restarting the installation but it keeps reappearing. Let me know if there's more info I can provide in manner to help you help me. Cheers.
2021/02/10
[ "https://Stackoverflow.com/questions/66129119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11966276/" ]
when removing freeradius (either by `apt remove freeradius` or `apt purge freeradius`) mind that config files are a seperate package called `freeradius-config` so to completely wipe freeradius and do a reinstall do: ``` apt purge freeradius freeradius-config rm -rf /etc/freeradius/ apt install freeradius ```
After installation of freeradius, add the following lines at the end of the client.conf file to set the access of your client: ``` #vi /etc/freeradius/3.0/clients.conf ``` For Example : ``` client SWITCH-01 { ipaddr = 192.168.0.10 secret = kamisama123 } client LINUX-01 { ipaddr = 192.168.0.20 secret = vegeto123 } ``` In our example, we are adding 2 client devices, both devices will offer a login promt to authenticate on freeradius server database. Now, locate and edit the freeradius users configuration file: Example: ``` # vi /etc/freeradius/3.0/users ``` Adding Your Username And Password Like below: ``` freerad1 Cleartext-Password := "freerad1234" freerad2 Cleartext-Password := "freerad2123" ``` Now, Restart freeradius server : ``` # service freeradius restart ``` Now, test your radius server configuration file : ``` #freeradius -CX ``` you can Test your radius authentication locally on the Radius server using the following commands: ``` # radtest freerad1 freerad1234 localhost 0 testing123 ``` Here is an example of a successful radius authentication: ``` Sent Access-Request Id 151 from 0.0.0.0:34857 to 127.0.0.1:1812 length 75 User-Name = "freerad1" User-Password = "freerad1234" NAS-IP-Address = 172.31.41.98 NAS-Port = 0 Message-Authenticator = 0x00 Cleartext-Password = "freerad1234" Received Access-Accept Id 151 from 127.0.0.1:1812 to 0.0.0.0:0 length 20 ``` We are using the freerad1 username and the freerad1234 password to authenticate the user account. The testing123 is a default device password included in the clients.conf file. Now, go to the Linux server included on the clients.conf configuration file as LINUX-01. Install the freeradius-utils package. ``` # apt-get install freeradius-utils ``` Test your radius authentication remotely on the Linux server (LINUX-01 OR YOUR CLIENT YOU ARE ADDED ON client.conf) using the following commands: ``` # radtest freerad freerad1234 192.168.0.50 0 vegeto123 ``` \*\* Congratulations, Your Freeradius server is on the service \*\*
71,397,984
I have successfully installed Pillow: chris@MBPvonChristoph sources % python3 -m pip install --upgrade Pillow Collecting Pillow Using cached Pillow-9.0.1-1-cp310-cp310-macosx\_11\_0\_arm64.whl (2.7 MB) Installing collected packages: Pillow Successfully installed Pillow-9.0.1 but when i try to use it in pycharm got: Traceback (most recent call last): File "/Users/chris/PycharmProjects/pythonProject2/main.py", line 1, in from PIL import Image ModuleNotFoundError: No module named 'PIL' or using in Blender i got: ModuleNotFoundError: No module named 'PIL' I am not a python lib installing pro...so obviously i made something wrong. But how do i fix that? Maybe i have to say i am working on a M1 Macbook
2022/03/08
[ "https://Stackoverflow.com/questions/71397984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8457280/" ]
looks like you may need to repoint your pycharm to your installed python interpreter. --- 1. go to command line and find out python interpreter path. On windows you can `where python` in your command line an it will give you where your python and packages are installed.. You could also activate python directly in command line and find paths from there. For example, open command line then; ``` python ``` press enter = activates python within then you can do: ``` import sys ``` ``` for x in sys.path: x ``` --- 2. In pycharm make sure you point to path discovered from step 1 and select that to be your python interpreter within pycharm --- check out examples here <https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html#add-existing-interpreter> --- 3. Should work. Not sure about all the steps you took, but if you installed python with pycharm on top of your regular installation of python i would recommend : * finding all the paths from step 1 * deleting python using system * checking if folders found from paths step still exist * if they do, delete those as well * start over just with one python installation * repoint to that in pycharm
first ``` pip uninstall PIL ``` after uninstall ``` python3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow ``` or ``` brew install Pillow ```
61,941,471
i'm still new to the field of deep learning using keras and wanted to ask if it is possible to take a model after training the network and run the network again with the variables of that model? in other words, say i train the network and reach an accuracy of 90%, can i train the network again starting with the variable values reached before in order to further improve the accuracy.and if so how can i do so in python? i would appreciate if you can explain this to me or provide a resource for me to learn about something like this.
2020/05/21
[ "https://Stackoverflow.com/questions/61941471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12139083/" ]
For me I just had to add `./mongo_data` to `.dockerignore` and the Dockerfile would ignore this directory while building `api`. I did this for all my volumes and things work fine now, no permission errors.
I had the same problem. I assume that you didn't have this permission error at your first time of docker-compose up. The The file "mongo\_data/diagnostic.data" did not exist either. The mongo container will create the file when starting, and the file belongs to a user, it's 999:root in my case(postgres). ``` drwx------ 19 999 root 4096 Jun 4 12:19 postgres-data/ ``` Your api container has the current directory as the build context. The user who builds the docker is your host user, it has to not be 999. So when you docker-compose up would have the permission denied. You can create a .dockerignore file in the context folder, the content is: ``` mongo_data ``` You have to add other folders in this file in the volumes of other containers.
32,925,532
I had already looked through this post: [Python: building new list from existing by dropping every n-th element](https://stackoverflow.com/questions/16406772/python-building-new-list-from-existing-by-dropping-every-n-th-element), but for some reason it does not work for me: I tried this way: ``` def drop(mylist, n): del mylist[0::n] print(mylist) ``` This function takes a list and `n`. Then it removes every n-th element by using n-step from list and prints result. Here is my function call: ``` drop([1,2,3,4],2) ``` Wrong output: `[2, 4]` instead of `[1, 3]` --- Then I tried a variant from the link above: ``` def drop(mylist, n): new_list = [item for index, item in enumerate(mylist) if index % n != 0] print(new_list) ``` Again, function call: ``` drop([1,2,3,4],2) ``` Gives me the same wrong result: `[2, 4]` instead of `[1, 3]` --- How to correctly remove/delete/drop every **n-th** item from a list?
2015/10/03
[ "https://Stackoverflow.com/questions/32925532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4786305/" ]
The output is correct, you are removing the the elements with index 0, n, 2n, ... . So 1 and 3 are removed, 2 and 4 are left. So if you want to print the 0, n, 2n, ... element, just write ``` print(mylist[::n]) ```
your first approach looks good to me - you just have to adapt your start index if you want to drop the elements 1, 1+n, 1+2n, ... (as seems to be the case): ``` lst = list(range(1, 5)) del lst[1::2] print(lst) ```
32,925,532
I had already looked through this post: [Python: building new list from existing by dropping every n-th element](https://stackoverflow.com/questions/16406772/python-building-new-list-from-existing-by-dropping-every-n-th-element), but for some reason it does not work for me: I tried this way: ``` def drop(mylist, n): del mylist[0::n] print(mylist) ``` This function takes a list and `n`. Then it removes every n-th element by using n-step from list and prints result. Here is my function call: ``` drop([1,2,3,4],2) ``` Wrong output: `[2, 4]` instead of `[1, 3]` --- Then I tried a variant from the link above: ``` def drop(mylist, n): new_list = [item for index, item in enumerate(mylist) if index % n != 0] print(new_list) ``` Again, function call: ``` drop([1,2,3,4],2) ``` Gives me the same wrong result: `[2, 4]` instead of `[1, 3]` --- How to correctly remove/delete/drop every **n-th** item from a list?
2015/10/03
[ "https://Stackoverflow.com/questions/32925532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4786305/" ]
Let's say you have the list: ``` a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` If you want to remove every k-th element you can do something like ``` del a[k-1::k] ``` For example with `k = 3`, the current list is now ``` [1, 2, 4, 5, 7, 8, 10] ```
The output is correct, you are removing the the elements with index 0, n, 2n, ... . So 1 and 3 are removed, 2 and 4 are left. So if you want to print the 0, n, 2n, ... element, just write ``` print(mylist[::n]) ```
32,925,532
I had already looked through this post: [Python: building new list from existing by dropping every n-th element](https://stackoverflow.com/questions/16406772/python-building-new-list-from-existing-by-dropping-every-n-th-element), but for some reason it does not work for me: I tried this way: ``` def drop(mylist, n): del mylist[0::n] print(mylist) ``` This function takes a list and `n`. Then it removes every n-th element by using n-step from list and prints result. Here is my function call: ``` drop([1,2,3,4],2) ``` Wrong output: `[2, 4]` instead of `[1, 3]` --- Then I tried a variant from the link above: ``` def drop(mylist, n): new_list = [item for index, item in enumerate(mylist) if index % n != 0] print(new_list) ``` Again, function call: ``` drop([1,2,3,4],2) ``` Gives me the same wrong result: `[2, 4]` instead of `[1, 3]` --- How to correctly remove/delete/drop every **n-th** item from a list?
2015/10/03
[ "https://Stackoverflow.com/questions/32925532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4786305/" ]
The output is correct, you are removing the the elements with index 0, n, 2n, ... . So 1 and 3 are removed, 2 and 4 are left. So if you want to print the 0, n, 2n, ... element, just write ``` print(mylist[::n]) ```
Another way to do this, would be to generate a new list containing only the elements you need. ``` newList = [x for i, x in enumerate(myList) if i%n !=0] ``` If n were 5, this would return a list containing the elements [1,2,3,4,6,7,8,9,11...] The advantage of doing it this way is that you keep your original list which is useful if you're going to reuse the data. However, if you're worried about saving memory, then probably not the best.
32,925,532
I had already looked through this post: [Python: building new list from existing by dropping every n-th element](https://stackoverflow.com/questions/16406772/python-building-new-list-from-existing-by-dropping-every-n-th-element), but for some reason it does not work for me: I tried this way: ``` def drop(mylist, n): del mylist[0::n] print(mylist) ``` This function takes a list and `n`. Then it removes every n-th element by using n-step from list and prints result. Here is my function call: ``` drop([1,2,3,4],2) ``` Wrong output: `[2, 4]` instead of `[1, 3]` --- Then I tried a variant from the link above: ``` def drop(mylist, n): new_list = [item for index, item in enumerate(mylist) if index % n != 0] print(new_list) ``` Again, function call: ``` drop([1,2,3,4],2) ``` Gives me the same wrong result: `[2, 4]` instead of `[1, 3]` --- How to correctly remove/delete/drop every **n-th** item from a list?
2015/10/03
[ "https://Stackoverflow.com/questions/32925532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4786305/" ]
In your first function `mylist[0::n]` is `[1, 3]` because `0::n` means first element is 0 and other elements are every n*th* element after first. As Daniel suggested you could use `mylist[::n]` which means every n*th* element. In your second function index is starting with 0 and `0 % 0` is 0, so it doesn't copy first element. It's same for third element (`2 % 2` is 0). So all you need to do is `new_list = [item for index, item in enumerate(mylist) if (index + 1) % n != 0]` Tip: you may want to use `return` instead of `print()` in functions like these.
your first approach looks good to me - you just have to adapt your start index if you want to drop the elements 1, 1+n, 1+2n, ... (as seems to be the case): ``` lst = list(range(1, 5)) del lst[1::2] print(lst) ```
32,925,532
I had already looked through this post: [Python: building new list from existing by dropping every n-th element](https://stackoverflow.com/questions/16406772/python-building-new-list-from-existing-by-dropping-every-n-th-element), but for some reason it does not work for me: I tried this way: ``` def drop(mylist, n): del mylist[0::n] print(mylist) ``` This function takes a list and `n`. Then it removes every n-th element by using n-step from list and prints result. Here is my function call: ``` drop([1,2,3,4],2) ``` Wrong output: `[2, 4]` instead of `[1, 3]` --- Then I tried a variant from the link above: ``` def drop(mylist, n): new_list = [item for index, item in enumerate(mylist) if index % n != 0] print(new_list) ``` Again, function call: ``` drop([1,2,3,4],2) ``` Gives me the same wrong result: `[2, 4]` instead of `[1, 3]` --- How to correctly remove/delete/drop every **n-th** item from a list?
2015/10/03
[ "https://Stackoverflow.com/questions/32925532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4786305/" ]
Let's say you have the list: ``` a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` If you want to remove every k-th element you can do something like ``` del a[k-1::k] ``` For example with `k = 3`, the current list is now ``` [1, 2, 4, 5, 7, 8, 10] ```
your first approach looks good to me - you just have to adapt your start index if you want to drop the elements 1, 1+n, 1+2n, ... (as seems to be the case): ``` lst = list(range(1, 5)) del lst[1::2] print(lst) ```
32,925,532
I had already looked through this post: [Python: building new list from existing by dropping every n-th element](https://stackoverflow.com/questions/16406772/python-building-new-list-from-existing-by-dropping-every-n-th-element), but for some reason it does not work for me: I tried this way: ``` def drop(mylist, n): del mylist[0::n] print(mylist) ``` This function takes a list and `n`. Then it removes every n-th element by using n-step from list and prints result. Here is my function call: ``` drop([1,2,3,4],2) ``` Wrong output: `[2, 4]` instead of `[1, 3]` --- Then I tried a variant from the link above: ``` def drop(mylist, n): new_list = [item for index, item in enumerate(mylist) if index % n != 0] print(new_list) ``` Again, function call: ``` drop([1,2,3,4],2) ``` Gives me the same wrong result: `[2, 4]` instead of `[1, 3]` --- How to correctly remove/delete/drop every **n-th** item from a list?
2015/10/03
[ "https://Stackoverflow.com/questions/32925532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4786305/" ]
your first approach looks good to me - you just have to adapt your start index if you want to drop the elements 1, 1+n, 1+2n, ... (as seems to be the case): ``` lst = list(range(1, 5)) del lst[1::2] print(lst) ```
Another way to do this, would be to generate a new list containing only the elements you need. ``` newList = [x for i, x in enumerate(myList) if i%n !=0] ``` If n were 5, this would return a list containing the elements [1,2,3,4,6,7,8,9,11...] The advantage of doing it this way is that you keep your original list which is useful if you're going to reuse the data. However, if you're worried about saving memory, then probably not the best.
32,925,532
I had already looked through this post: [Python: building new list from existing by dropping every n-th element](https://stackoverflow.com/questions/16406772/python-building-new-list-from-existing-by-dropping-every-n-th-element), but for some reason it does not work for me: I tried this way: ``` def drop(mylist, n): del mylist[0::n] print(mylist) ``` This function takes a list and `n`. Then it removes every n-th element by using n-step from list and prints result. Here is my function call: ``` drop([1,2,3,4],2) ``` Wrong output: `[2, 4]` instead of `[1, 3]` --- Then I tried a variant from the link above: ``` def drop(mylist, n): new_list = [item for index, item in enumerate(mylist) if index % n != 0] print(new_list) ``` Again, function call: ``` drop([1,2,3,4],2) ``` Gives me the same wrong result: `[2, 4]` instead of `[1, 3]` --- How to correctly remove/delete/drop every **n-th** item from a list?
2015/10/03
[ "https://Stackoverflow.com/questions/32925532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4786305/" ]
Let's say you have the list: ``` a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` If you want to remove every k-th element you can do something like ``` del a[k-1::k] ``` For example with `k = 3`, the current list is now ``` [1, 2, 4, 5, 7, 8, 10] ```
In your first function `mylist[0::n]` is `[1, 3]` because `0::n` means first element is 0 and other elements are every n*th* element after first. As Daniel suggested you could use `mylist[::n]` which means every n*th* element. In your second function index is starting with 0 and `0 % 0` is 0, so it doesn't copy first element. It's same for third element (`2 % 2` is 0). So all you need to do is `new_list = [item for index, item in enumerate(mylist) if (index + 1) % n != 0]` Tip: you may want to use `return` instead of `print()` in functions like these.
32,925,532
I had already looked through this post: [Python: building new list from existing by dropping every n-th element](https://stackoverflow.com/questions/16406772/python-building-new-list-from-existing-by-dropping-every-n-th-element), but for some reason it does not work for me: I tried this way: ``` def drop(mylist, n): del mylist[0::n] print(mylist) ``` This function takes a list and `n`. Then it removes every n-th element by using n-step from list and prints result. Here is my function call: ``` drop([1,2,3,4],2) ``` Wrong output: `[2, 4]` instead of `[1, 3]` --- Then I tried a variant from the link above: ``` def drop(mylist, n): new_list = [item for index, item in enumerate(mylist) if index % n != 0] print(new_list) ``` Again, function call: ``` drop([1,2,3,4],2) ``` Gives me the same wrong result: `[2, 4]` instead of `[1, 3]` --- How to correctly remove/delete/drop every **n-th** item from a list?
2015/10/03
[ "https://Stackoverflow.com/questions/32925532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4786305/" ]
In your first function `mylist[0::n]` is `[1, 3]` because `0::n` means first element is 0 and other elements are every n*th* element after first. As Daniel suggested you could use `mylist[::n]` which means every n*th* element. In your second function index is starting with 0 and `0 % 0` is 0, so it doesn't copy first element. It's same for third element (`2 % 2` is 0). So all you need to do is `new_list = [item for index, item in enumerate(mylist) if (index + 1) % n != 0]` Tip: you may want to use `return` instead of `print()` in functions like these.
Another way to do this, would be to generate a new list containing only the elements you need. ``` newList = [x for i, x in enumerate(myList) if i%n !=0] ``` If n were 5, this would return a list containing the elements [1,2,3,4,6,7,8,9,11...] The advantage of doing it this way is that you keep your original list which is useful if you're going to reuse the data. However, if you're worried about saving memory, then probably not the best.
32,925,532
I had already looked through this post: [Python: building new list from existing by dropping every n-th element](https://stackoverflow.com/questions/16406772/python-building-new-list-from-existing-by-dropping-every-n-th-element), but for some reason it does not work for me: I tried this way: ``` def drop(mylist, n): del mylist[0::n] print(mylist) ``` This function takes a list and `n`. Then it removes every n-th element by using n-step from list and prints result. Here is my function call: ``` drop([1,2,3,4],2) ``` Wrong output: `[2, 4]` instead of `[1, 3]` --- Then I tried a variant from the link above: ``` def drop(mylist, n): new_list = [item for index, item in enumerate(mylist) if index % n != 0] print(new_list) ``` Again, function call: ``` drop([1,2,3,4],2) ``` Gives me the same wrong result: `[2, 4]` instead of `[1, 3]` --- How to correctly remove/delete/drop every **n-th** item from a list?
2015/10/03
[ "https://Stackoverflow.com/questions/32925532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4786305/" ]
Let's say you have the list: ``` a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` If you want to remove every k-th element you can do something like ``` del a[k-1::k] ``` For example with `k = 3`, the current list is now ``` [1, 2, 4, 5, 7, 8, 10] ```
Another way to do this, would be to generate a new list containing only the elements you need. ``` newList = [x for i, x in enumerate(myList) if i%n !=0] ``` If n were 5, this would return a list containing the elements [1,2,3,4,6,7,8,9,11...] The advantage of doing it this way is that you keep your original list which is useful if you're going to reuse the data. However, if you're worried about saving memory, then probably not the best.
67,972,487
I want to get a script to: a) check if a number within the user defined range is prime or not b) print the result of a check c) print amount of numbers checked and how many of these numbers were primes d) print the last prime number Here is what I have so far: ``` lower = int(input("Lower boundry: ")) upper = int(input("Upper boundry: ")) for n in range(lower, upper + 1): if (n <= 1): print(n, "error") elif (n > 1): for x in range(2, n): if ((n % x) == 0): print(n, "not prime, because", x, "*", int(n/x),"=", n) break else: print(n, "prime") last = [n] print("Checked", n, "numbers, of which","XXX","were prime.") print("Last prime number found was", *last) ``` Question: 1. The tool im using gives me an error. Lets say, I check the numbers 1-10. On 1 I get a notification that 1 is not prime (as intended, as n <= 1). Number 2 is a prime and the programme notifies me of this. However, on 3 i get an error - "incorrect output: your program printed "prime3", but should have printed "prime.". I don't get it. Is it the white space python seems to like so much? Or did I fail with else if use? 2. For checking the number of primes within the specified range - am I supposed to use a list to store the values generated in the for loop? The material will cover lists during later sessions, so I am guessing I am meant to use some other method. But lets say I want to use the list. Is it something like: ``` list=[] for y in [1,10] : for z in [0,1,2,3] : x=y+z list.append(x) ``` and the use len(list) where the XXX placeholder is ATM? Edit: Got the c) and d) to work - used list as a storage for values. Printed last value in the list for d) and used the length of the list for c). Fixed the indentation issue pointed out to me in the comments below. Still cannot get the code to run properly. In I in put 1 and 10 as bounds, the programme identifies 1 as not prime, 2 as prime and then gives error. Error text is: "Incorrect output: your program printed "prime3", but should have printed "prime." " Not really sure what is up with that.
2021/06/14
[ "https://Stackoverflow.com/questions/67972487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16223545/" ]
The indentation of your `else` clause is wrong. It should belong to the `for` loop. This means it will be executed when the loop is not terminated by the `break` statement. I can't answer your question about the error message, because I don't know the test tool in question. To keep track of the number of primes found, you can use a simple integer variable: Initialize it as zero and increment it by 1 whenever a prime is found. ```py lower = int(input("Lower boundry: ")) upper = int(input("Upper boundry: ")) n_primes = 0 for n in range(lower, upper + 1): if (n <= 1): print(n, "error") else: for x in range(2, n): if ((n % x) == 0): print(n, "not prime, because", x, "*", int(n/x),"=", n) break else: print(n, "prime") n_primes += 1 last = n print("Checked", upper - lower + 1, "numbers, of which", n_primes, "were prime.") print("Last prime number found was", last) ```
How about this . ``` # define a flag variable lower = int(input("Lower boundry: ")) upper = int(input("Upper boundry: ")) prime_list=[] for num in range(lower,upper+1): flag = False # prime numbers are greater than 1 if num > 1: # check for factors for i in range(2, num): if (num % i) == 0: # if factor is found, set flag to True flag = True # break out of loop break # check if flag is True if flag: flag=False else: prime_list.append(num) print("Checked:",len(list(range(lower,upper+1))),"numbers where",len(prime_list),"were prime.") print("Last prime number checked: ",prime_list[-1]) print("All prime numbers are: ",','.join(str(n) for n in prime_list)) ``` Output ``` Lower boundry: 1 Upper boundry: 30 Checked: 30 numbers where 11 were prime. Last prime number checked: 29 All prime numbers are: 1,2,3,5,7,11,13,17,19,23,29 ```
67,972,487
I want to get a script to: a) check if a number within the user defined range is prime or not b) print the result of a check c) print amount of numbers checked and how many of these numbers were primes d) print the last prime number Here is what I have so far: ``` lower = int(input("Lower boundry: ")) upper = int(input("Upper boundry: ")) for n in range(lower, upper + 1): if (n <= 1): print(n, "error") elif (n > 1): for x in range(2, n): if ((n % x) == 0): print(n, "not prime, because", x, "*", int(n/x),"=", n) break else: print(n, "prime") last = [n] print("Checked", n, "numbers, of which","XXX","were prime.") print("Last prime number found was", *last) ``` Question: 1. The tool im using gives me an error. Lets say, I check the numbers 1-10. On 1 I get a notification that 1 is not prime (as intended, as n <= 1). Number 2 is a prime and the programme notifies me of this. However, on 3 i get an error - "incorrect output: your program printed "prime3", but should have printed "prime.". I don't get it. Is it the white space python seems to like so much? Or did I fail with else if use? 2. For checking the number of primes within the specified range - am I supposed to use a list to store the values generated in the for loop? The material will cover lists during later sessions, so I am guessing I am meant to use some other method. But lets say I want to use the list. Is it something like: ``` list=[] for y in [1,10] : for z in [0,1,2,3] : x=y+z list.append(x) ``` and the use len(list) where the XXX placeholder is ATM? Edit: Got the c) and d) to work - used list as a storage for values. Printed last value in the list for d) and used the length of the list for c). Fixed the indentation issue pointed out to me in the comments below. Still cannot get the code to run properly. In I in put 1 and 10 as bounds, the programme identifies 1 as not prime, 2 as prime and then gives error. Error text is: "Incorrect output: your program printed "prime3", but should have printed "prime." " Not really sure what is up with that.
2021/06/14
[ "https://Stackoverflow.com/questions/67972487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16223545/" ]
Fist of all: Please pose your question in the title. For Example: "How do I find all primes in a user-defined range?" The Algorithm ------------- To find out whether or not a number is prime you can divide it by all primes smaller than the number, since all non-primes can be divided by primes. This is significantly faster than checking all numbers Generating primes ----------------- I would first define a function to generate the next prime. For this I take the last prime number and then continue to add 2 to it until we find the next prime: ``` def dividable_by_any_in_list(x, list): for n in list: if x%n == 0: return True return False def next_prime(known_primes): """ Takes a list of known primes and returns the next prime. """ current = known_primes[-1]+2 while True: if dividable_by_any_in_list(current, known_primes): current += 2 else: return current ``` I tested that with this main function: ``` def main(): # Not what you want to copy-paste known_primes = [2,3,5,7,11,13,17,19] next = next_prime(known_primes) print(next) if __name__ == '__main__': main() ``` and it returned 23, which is correct. Finding all primes in range --------------------------- Now we can write a function to find all primes below an upper boundary: ``` def find_primes_below(known_primes, max): last = known_primes[-1] while last <= max: last = next_prime(known_primes) known_primes.append(last) return known_primes[:-1] ``` Using this we can write a function that takes the return value of this function and cuts out all primes below the lower bound: ``` def find_primes_in_range(known_primes, min, max): all_primes = find_primes_below(known_primes, max) l = 0 while all_primes[l] < min: l+=1 u = len(all_primes)-1 while all_primes[u] > max: u -= 1 return all_primes[l:u] ``` Output ------ Now we can define the main function: ``` def main(): known_primes = [2,3,5,7,11,13,17,19] lower = int(input("Lower boundry: ")) upper = int(input("Upper boundry: ")) primes = find_primes_in_range(known_primes, lower, upper) print("Found Primes:") print(primes) print(f"Checked {upper-lower} numbers, of which {len(primes)} were prime.") print("Last prime number found was", primes[-1]) if __name__ == '__main__': main() ```
How about this . ``` # define a flag variable lower = int(input("Lower boundry: ")) upper = int(input("Upper boundry: ")) prime_list=[] for num in range(lower,upper+1): flag = False # prime numbers are greater than 1 if num > 1: # check for factors for i in range(2, num): if (num % i) == 0: # if factor is found, set flag to True flag = True # break out of loop break # check if flag is True if flag: flag=False else: prime_list.append(num) print("Checked:",len(list(range(lower,upper+1))),"numbers where",len(prime_list),"were prime.") print("Last prime number checked: ",prime_list[-1]) print("All prime numbers are: ",','.join(str(n) for n in prime_list)) ``` Output ``` Lower boundry: 1 Upper boundry: 30 Checked: 30 numbers where 11 were prime. Last prime number checked: 29 All prime numbers are: 1,2,3,5,7,11,13,17,19,23,29 ```
52,767,072
I am trying psql and getting an error. ``` $ psql psql: FATAL: "myilmaz" role not available ``` Then I try ``` $ createdb python_getting_started createdb: Unable to connect to template1 database: FATAL: "myilmaz" does not have access to the system ``` I run `export DATABASE_URL=postgres://$(whoami)` as indicated [here](https://devcenter.heroku.com/articles/heroku-postgresql#local-setup) and then started getting this error. I don't know if there was an error before that. **Note:** I'm using Pardus 17.3, and it based Debian 9. 'myilmaz' is my username. **Edit:** I tried adding my user to template1 in postgres user.
2018/10/11
[ "https://Stackoverflow.com/questions/52767072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10398711/" ]
The part you haven't understood is that every method - in fact, every call to every method - has its own collection of local variables. That means that * the `winnings` variable declared in `main` is NOT the same variable as the `winnings` variable declared in `determineWinnings`; * the `bet` variable declared in `main` is NOT the same variable as the `bet` variable declared in `getBet`. What you need to do is to make sure that the value returned by each *called* method is assigned to the variable that you want to store it in, in the *caller* method. So in `main`, when you call `getBet`, you actually want to write ``` bet = getBet(inScanner, currentPool); ``` so that the value returned from `getBet` gets assigned to the `bet` variable from `main`. Similarly, when you call `determineWinnings`, you need to write ``` winnings = determineWinnings(highLow, bet, roll); ``` so that the value returned from `determineWinnings` gets assigned to the `winnings` variable from `main`. If you don't do that, then all the variables in `main` just keep their original values, which are `100` for `currentPool` and `32` for winnings (because `' '` is just another way to write `32`). That's why your final value turns out to be `132`.
To avoid skipping if in execution use `bet = getBet(inScanner, currentPool); highLow = getHighLow(inScanner); winnings = determineWinnings(highLow, bet, roll);` instead of directly calling `getBet(inScanner, currentPool); getHighLow(inScanner); determineWinnings(highLow, bet, roll);` Reson for skipping if statement and wrong answer: getBet(inScanner, currentPool) method is returning the value which is not assigned to int bet = ' '; java tries to convert ' ' to an integer which is 32. so bet is every time assigned 32 value when you call getBet(inScanner, currentPool) even if the entered value is different(which will give wrong answer). In the case of getHighLow(inScanner) method is returning char value but since it is not assigned to highLow, highLow will always have value ' '. since highLow has not assigned the actual value(H/L/S), if statement will be skipped as ' '!=(H/L/S) and always statements in else are executed.
74,436,487
I am using OR-Tools to solve a problem similar to the Nurse Scheduling problem. The difference in my case is that when I schedule a "Nurse" for a shift, they must then work consecutive days (i.e., there can be no gaps between days worked). Most of the similar questions point to this [code](https://github.com/google/or-tools/blob/master/examples/python/shift_scheduling_sat.py). I have attempted to implement the answer adapted from there. However, I am getting output solutions which do not respecting the constraints. The logic I was trying to follow is that I want to forbid patterns that have gaps. For example: ``` [1,0,1] [1,0,0,1] [1,0,0,0,1] ``` Below is an example of my code where for ``` # Modified from the code linked above: def negated_bounded_span(works, start, length): sequence = [] # Left border sequence.append(works[start].Not()) # Middle for i in range(1,length+1): sequence.append(works[start + i]) # Right border sequence.append(works[start + length + 1].Not()) return sequence for n in range(num_nurses): # nurse_days[(n,d)] is 1 if nurse n works on day d nrses = [nurse_days[(n, d)] for d in range(5)] for length in range(1, 4): for start in range(5 - length - 1): model.AddBoolOr(negated_bounded_span(nrses, start, length)) ``` A modified excerpt of what the output of the above would look like is the following: ``` ['Not(nurse_days_n0d0)', nurse_days_n0d1(0..1), 'Not(nurse_days_n0d2)'] ['Not(nurse_days_n0d1)', nurse_days_n0d2(0..1), 'Not(nurse_days_n0d3)'] ['Not(nurse_days_n0d2)', nurse_days_n0d3(0..1), 'Not(nurse_days_n0d4)'] ['Not(nurse_days_n0d0)', nurse_days_n0d1(0..1), nurse_days_n0d2(0..1), 'Not(nurse_days_n0d3)'] ['Not(nurse_days_n0d1)', nurse_days_n0d2(0..1), nurse_days_n0d3(0..1), 'Not(nurse_days_n0d4)'] ['Not(nurse_days_n0d0)', nurse_days_n0d1(0..1), nurse_days_n0d2(0..1), nurse_days_n0d3(0..1), 'Not(nurse_days_n0d4)'] ``` Thanks for your help in advance. Similar questions reviewed: [[1](https://stackoverflow.com/questions/56872713/setting-binary-constraints-with-google-or-tools/56877058#56877058)], [[2](https://stackoverflow.com/questions/62980487/or-tools-add-2-days-in-a-row-to-the-scheduling-problem?noredirect=1&lq=1)], [[3](https://stackoverflow.com/questions/55100229/google-or-tools-employee-scheduling-the-condition-does-not-work-properly?rq=1)].
2022/11/14
[ "https://Stackoverflow.com/questions/74436487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18497033/" ]
[Select-String](https://learn.microsoft.com/en-gb/powershell/module/microsoft.powershell.utility/select-string): *By default, the output is a set of `MatchInfo` objects with one for each match found.* Apply `.substring` method to the `$_.Line` string, e.g. as follows: ``` Select-String -Path "DatabaseBackup - USER_DATABASES - FULL*.txt" -pattern "MB/sec" | ForEach-Object { $_.Line.substring(42,30) } ```
[`Select-String`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.powershell.commands.matchinfo?view=powershellsdk-7.2.0) is returning a `MatchInfo` object so you would need to iterate over the `Matches` property of that object. So you could do something like this: ``` (Select-String -Path "DatabaseBackup - USER_DATABASES - FULL*.txt" -pattern "MB/sec").Matches | ForEach-Object { $_.substring(42,30) } ```
68,769,200
by no means am i an expert when it comes to python but i have tried my best. I have written a short code in python that reads a text file from a blob storage and appends it with some column names and outputs it to target folder. The code executes correctly when i run from VS Code. When i try to run it via Azure Function i get it throws an error. Can it be that i have wrong parameters in my function.json binding file? { "statusCode": 500, "message": "Internal server error" } This is my original code: ``` import logging import azure.functions as func from azure.storage.blob import BlobClient,BlobServiceClient def main(): logging.info(' start Python Main function processed a request.') #CONNECTION STRING blob_service_client = BlobServiceClient.from_connection_string(CONN_STR) # MAP SOURCE FILE blob_client = blob_service_client.get_blob_client(container="source", blob="source.txt") #SOURCE CONTENTS content= blob_client.download_blob().content_as_text() # WRITE HEADER TO A OUT PUTFILE output_file_dest = blob_service_client.get_blob_client(container="target", blob="target.csv") #INITIALIZE OUTPUT output_str = "" #STORE COULMN HEADERS data= list() data.append(list(["column1", "column2", "column3", "column4"])) output_str += ('"' + '","'.join(data[0]) + '"\n') output_file_dest.upload_blob(output_str,overwrite=True) logging.info(' END OF FILE UPLOAD') if __name__ == "__main__": main() ``` **This is my function.json** ``` { "scriptFile": "__init__.py", "bindings": [ { "type": "blob", "direction": "in", "name": "blob_client", "path": "source/source.txt", "connection": "STORAGE_CONN_STR" }, { "type": "blob", "direction": "out", "name": "output_file_dest", "path": "target/target.csv", "connection": "STORAGE_CONN_STR" } ] } ``` **This is my requirement.txt** ``` azure-functions==1.7.2 azure-storage-blob==12.8.1 ```
2021/08/13
[ "https://Stackoverflow.com/questions/68769200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4511169/" ]
You have to revert the order of your aggregation operations since your `$project` will only leave one property `title` so there is no way to filter by `year` afterwards: ``` db.collection.aggregate([ { "$match": { "year": { "$gt": 1967, "$lt": 2020 } } }, { "$project": { "title": 1, "year": 1 } }]) ``` [Mongo Playground](https://mongoplayground.net/p/2VffYA8gfha)
``` db.movies.find({year: {$gte:1967, $lte:1995} },{title:1,year:1,"director.last_name":1 }).sort({year:1}) ```
4,834,036
I need to have an array of python objects to be used in creating a trie datastructure. I need a structure that will be fixed-length like a tuple and mutable like a list. I don't want to use a list because I want to be able to ensure that the list is *exactly* the right size (if it starts allocating extra elements, the memory overhead could add up very quickly as the trie grows larger). Is there a way to do this? I tried creating an array of objects: ``` cdef class TrieNode: cdef object members[32] ``` ...but that gave an error: ``` Error compiling Cython file: ------------------------------------------------------------ ... cdef class TrieNode: cdef object members[32] ^ ------------------------------------------------------------ /Users/jason/src/pysistence/source/pysistence/trie.pyx:2:23: Array element cannot be a Python object ``` What is the best way to do what I'm trying to do?
2011/01/28
[ "https://Stackoverflow.com/questions/4834036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
If you only need few fixed sizes of such a structure, I'd look at making classes with uniformly named `__slots__`, including one `size` slot to store the size. You'll need to declare a separate class for each size (number of slots). Define a `cdecl` function to access slots by index. Access performance will probably be not as great as with plain address arithmetics of a C array, but you'll be sure that there's only so many slots and none more.
How about this? ``` class TrieNode(): def __init__(self, length = 32): self.members = list() self.length = length for i in range(length): self.members.append(None) def set(self, idx, item): if idx < self.length and idx >= 0: self.members[idx] = item else: print "ERROR: Specified index out of range." # Alternately, you could raise an IndexError. def unset(self, idx): if idx < self.length and idx >= 0: self.members[idx] = None else: raise IndexError("Specified index out of range (0..%d)." % self.length) ```
4,834,036
I need to have an array of python objects to be used in creating a trie datastructure. I need a structure that will be fixed-length like a tuple and mutable like a list. I don't want to use a list because I want to be able to ensure that the list is *exactly* the right size (if it starts allocating extra elements, the memory overhead could add up very quickly as the trie grows larger). Is there a way to do this? I tried creating an array of objects: ``` cdef class TrieNode: cdef object members[32] ``` ...but that gave an error: ``` Error compiling Cython file: ------------------------------------------------------------ ... cdef class TrieNode: cdef object members[32] ^ ------------------------------------------------------------ /Users/jason/src/pysistence/source/pysistence/trie.pyx:2:23: Array element cannot be a Python object ``` What is the best way to do what I'm trying to do?
2011/01/28
[ "https://Stackoverflow.com/questions/4834036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
I don't know about the *best* solution, but here's *a* solution: ``` from cpython.ref cimport PyObject, Py_XINCREF, Py_XDECREF DEF SIZE = 32 cdef class TrieNode: cdef PyObject *members[SIZE] def __cinit__(self): cdef object temp_object for i in range(SIZE): temp_object = int(i) # increment its refcount so it's not gc'd. # We hold a reference to the object and are responsible for # decref-ing it in __dealloc__. Py_XINCREF(<PyObject*>temp_object) self.members[i] = <PyObject*>temp_object def __init__(self): # just to show that it works... for i in range(SIZE): print <object>self.members[i] def __dealloc__(self): # make sure we decref the members elements. for i in range(SIZE): Py_XDECREF(self.members[i]) self.members[i] = NULL ``` A Cython `object` is an automatically refcounted `PyObject *`. You can always roll your own arrays of `PyObject *`'s as long as you take responsibility for refcounting the little buggers. This can be a major headache for non-trivial cases.
How about this? ``` class TrieNode(): def __init__(self, length = 32): self.members = list() self.length = length for i in range(length): self.members.append(None) def set(self, idx, item): if idx < self.length and idx >= 0: self.members[idx] = item else: print "ERROR: Specified index out of range." # Alternately, you could raise an IndexError. def unset(self, idx): if idx < self.length and idx >= 0: self.members[idx] = None else: raise IndexError("Specified index out of range (0..%d)." % self.length) ```
4,834,036
I need to have an array of python objects to be used in creating a trie datastructure. I need a structure that will be fixed-length like a tuple and mutable like a list. I don't want to use a list because I want to be able to ensure that the list is *exactly* the right size (if it starts allocating extra elements, the memory overhead could add up very quickly as the trie grows larger). Is there a way to do this? I tried creating an array of objects: ``` cdef class TrieNode: cdef object members[32] ``` ...but that gave an error: ``` Error compiling Cython file: ------------------------------------------------------------ ... cdef class TrieNode: cdef object members[32] ^ ------------------------------------------------------------ /Users/jason/src/pysistence/source/pysistence/trie.pyx:2:23: Array element cannot be a Python object ``` What is the best way to do what I'm trying to do?
2011/01/28
[ "https://Stackoverflow.com/questions/4834036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
I don't know about the *best* solution, but here's *a* solution: ``` from cpython.ref cimport PyObject, Py_XINCREF, Py_XDECREF DEF SIZE = 32 cdef class TrieNode: cdef PyObject *members[SIZE] def __cinit__(self): cdef object temp_object for i in range(SIZE): temp_object = int(i) # increment its refcount so it's not gc'd. # We hold a reference to the object and are responsible for # decref-ing it in __dealloc__. Py_XINCREF(<PyObject*>temp_object) self.members[i] = <PyObject*>temp_object def __init__(self): # just to show that it works... for i in range(SIZE): print <object>self.members[i] def __dealloc__(self): # make sure we decref the members elements. for i in range(SIZE): Py_XDECREF(self.members[i]) self.members[i] = NULL ``` A Cython `object` is an automatically refcounted `PyObject *`. You can always roll your own arrays of `PyObject *`'s as long as you take responsibility for refcounting the little buggers. This can be a major headache for non-trivial cases.
If you only need few fixed sizes of such a structure, I'd look at making classes with uniformly named `__slots__`, including one `size` slot to store the size. You'll need to declare a separate class for each size (number of slots). Define a `cdecl` function to access slots by index. Access performance will probably be not as great as with plain address arithmetics of a C array, but you'll be sure that there's only so many slots and none more.
49,868,348
I'm trying to install sklearn onm an AWS DeepLearning AMI, with Conda and an assortment of backends pre-installed. I'm following ScikitLearn's website instructions: ``` $ conda install -c anaconda scikit-learn $ source activate python3 $ jupyter notebook ``` In Jupyter notebook: ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt #Scaling the data from sklearn.preprocessing import MinMaxScaler ModuleNotFoundError Traceback (most recent call last) <ipython-input-1-884b8a303194> in <module>() 12 13 #Scaling the data ---> 14 from sklearn.preprocessing import MinMaxScaler 15 sc = MinMaxScaler() #scaling using normalisation 16 training_set1 = sc.fit_transform(training_set1) ModuleNotFoundError: No module named 'sklearn' ```
2018/04/17
[ "https://Stackoverflow.com/questions/49868348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8268013/" ]
You need to start the virtual environment **first** "source activate python3", then install scikit-learn. Without activating the virtual environment, you are installing into the base python and not into the virtual environment. Cheers
And in case anybody didn't know how to install packages in each conda environment, it is (as in this case my environment of choice was `Tensorflow` in *Python 3.6*) here is the command I used my *mac bash*, and in my EC2 environment: ``` ubuntu@ip ***.***.**.***:~$ source activate tensorflow_p36 ``` and then: ``` ubuntu@ip ***.***.**.***:~$ conda install -c anaconda scikit-learn ```
49,868,348
I'm trying to install sklearn onm an AWS DeepLearning AMI, with Conda and an assortment of backends pre-installed. I'm following ScikitLearn's website instructions: ``` $ conda install -c anaconda scikit-learn $ source activate python3 $ jupyter notebook ``` In Jupyter notebook: ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt #Scaling the data from sklearn.preprocessing import MinMaxScaler ModuleNotFoundError Traceback (most recent call last) <ipython-input-1-884b8a303194> in <module>() 12 13 #Scaling the data ---> 14 from sklearn.preprocessing import MinMaxScaler 15 sc = MinMaxScaler() #scaling using normalisation 16 training_set1 = sc.fit_transform(training_set1) ModuleNotFoundError: No module named 'sklearn' ```
2018/04/17
[ "https://Stackoverflow.com/questions/49868348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8268013/" ]
You need to start the virtual environment **first** "source activate python3", then install scikit-learn. Without activating the virtual environment, you are installing into the base python and not into the virtual environment. Cheers
Did you install "scikit-learn", try: `conda install -c anaconda scikit-learn` or : first create virtual env and try: `conda install -c anaconda scikit-learn` to create virutal env: `conda create -n *yourenvname* python=*x.x* anaconda`
49,868,348
I'm trying to install sklearn onm an AWS DeepLearning AMI, with Conda and an assortment of backends pre-installed. I'm following ScikitLearn's website instructions: ``` $ conda install -c anaconda scikit-learn $ source activate python3 $ jupyter notebook ``` In Jupyter notebook: ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt #Scaling the data from sklearn.preprocessing import MinMaxScaler ModuleNotFoundError Traceback (most recent call last) <ipython-input-1-884b8a303194> in <module>() 12 13 #Scaling the data ---> 14 from sklearn.preprocessing import MinMaxScaler 15 sc = MinMaxScaler() #scaling using normalisation 16 training_set1 = sc.fit_transform(training_set1) ModuleNotFoundError: No module named 'sklearn' ```
2018/04/17
[ "https://Stackoverflow.com/questions/49868348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8268013/" ]
Did you install "scikit-learn", try: `conda install -c anaconda scikit-learn` or : first create virtual env and try: `conda install -c anaconda scikit-learn` to create virutal env: `conda create -n *yourenvname* python=*x.x* anaconda`
And in case anybody didn't know how to install packages in each conda environment, it is (as in this case my environment of choice was `Tensorflow` in *Python 3.6*) here is the command I used my *mac bash*, and in my EC2 environment: ``` ubuntu@ip ***.***.**.***:~$ source activate tensorflow_p36 ``` and then: ``` ubuntu@ip ***.***.**.***:~$ conda install -c anaconda scikit-learn ```
57,277,513
I'm generating the pictures of my latex document with the following program `genimg.py`: ``` #!/usr/bin/env python3 def figCircle(): print('generate circle picture') def figSquare(): print('generate square picture') def main(): for key, value in globals().items(): if callable(value) and key.startswith('fig'): value() if __name__== "__main__": main() ``` Now, since the images get more and more, I would like to split `genimg.py` in more files, lets say `genimgFirst.py` and `genimgSecond.py` and the `genimg.py` should go through the modules starting with `genimg` and execute all functions starting with `fig`. Lets assume that I add `import genimgFirst` and `import genimgSecond` at the beginning of my new modified `genimg.py`. Is this possible (without a revolution, that is just copy and paste of my fig\* functions)? **EDIT** Here the code after a merge of the two answers of @bluenote and @inspectorG4dget: ``` #!/usr/bin/env python3 import glob def main(): for fname in glob.glob("genimg*.py"): # get all the relevant files if fname == "genimg.py": continue print('>>>> {}'.format(fname)) mod = fname.rsplit('.',1)[0] mod = __import__(mod) # import the module for k,v in mod.__dict__.items(): if callable(v) and k.startswith('fig'): v() # if a module attribute is a function, call it if __name__== "__main__": main() ```
2019/07/30
[ "https://Stackoverflow.com/questions/57277513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11811021/" ]
You could call your code recursively for imported modules. Something like ``` import types def call_functions(module_dict): for key, value in module_dict.items(): if callable(value) and key.startswith('fig'): value() elif isinstance(value, types.ModuleType): call_functions(value.__dict__) if __name__=='__main__': call_functions(globals()) ```
``` import glob for fname in glob.glob("genimg*.py"): # get all the relevant files mod = gname.rsplit('.',1)([0]) mod = __import__(mod) # import the module for k,v in mod.__dict__.items(): if callable(v): v() # if a module attribute is a function, call it ```
62,670,115
I have text file containing employee details and various other details. Below is the consolidated data as shown below. ``` Data file created on 4 Jun 2020 GROUPCASEINSENSITIVE ON #KCT-User-Group GROUP KCT ALopp190 e190 ARaga789 Lshastri921 GROUP KCT DPatel592 ANaidu026 e026 KRam161 e161 #KBN-User-Group GROUP KBN SPatil322 e322 LAgarwal908 AKeshri132 e132 GROUP KBN BRaju105 e105 LNaik110 PNeema163 e163 #PDA-User-Group GROUP PDA SRoy977 AAgarwal594 e594 AMath577 e577 GROUP PDA BSharma865 e865 CUmesh195 RRana354 ``` When i run a Python code i need output as shown below ``` ALopp190 ARaga789 Lshastri921 DPatel592 ANaidu026 KRam161 SPatil322 LAgarwal908 AKeshri132 BRaju105 LNaik110 PNeema163 SRoy977 AAgarwal594 AMath577 BSharma865 CUmesh195 RRana354 ``` From that text file i need only the above data.This is what i had tried but its not working ``` def user(li): n = len (li) for j in range(0, n, 2): print (li[j]) import os os.getcwd() fo = open(r'C:\\Users\\Kiran\\Desktop\\Emplyoees\\User.txt', 'r') for i in fo.readlines(): li = list(i.split(" ")) #print (li) li.remove("GROUP") li.remove("KCT") li.remove("KBN") li.remove("PDA") user (li) ``` I am new to python and not sure how to get the data. Can you please assist me in fixing this issue.
2020/07/01
[ "https://Stackoverflow.com/questions/62670115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13761107/" ]
As others have mentioned, you can source your `.vimrc`, but that doesn't completely reset Vim. If you want to just restart Vim, then you can do so by re-execing it. Vim doesn't provide a built-in way to exec processes from within it, since typically one doesn't want to replace one's editor with another process, but it is possible to do so with Perl or Ruby, as you see fit: ``` :perl exec "vim" ``` or ``` :ruby exec "vim" ``` This may or may not work on Windows, and it of course requires that your Vim version have been compiled with support for the appropriate interpreters. Debian provides both in the `vim-nox`, `vim-gtk3`, and `vim-athena` packages, but not in `vim` or `vim-tiny`; Ubuntu, last I checked, did not provide Ruby support but did include Perl. If you want to re-exec with the same buffer, you can use one of these: ``` :perl exec "vim", $curbuf->Name(); ``` or ``` :ruby exec "vim", Vim::Buffer.current.name ``` Note that re-execing may cause your screen to be slightly messed up when exiting, so you may need to use `reset` to set it back to normal.
I don't know if you had tried this but you can source your vimrc file from vim itself by typing > > :so $MYVIMRC > > >
62,670,115
I have text file containing employee details and various other details. Below is the consolidated data as shown below. ``` Data file created on 4 Jun 2020 GROUPCASEINSENSITIVE ON #KCT-User-Group GROUP KCT ALopp190 e190 ARaga789 Lshastri921 GROUP KCT DPatel592 ANaidu026 e026 KRam161 e161 #KBN-User-Group GROUP KBN SPatil322 e322 LAgarwal908 AKeshri132 e132 GROUP KBN BRaju105 e105 LNaik110 PNeema163 e163 #PDA-User-Group GROUP PDA SRoy977 AAgarwal594 e594 AMath577 e577 GROUP PDA BSharma865 e865 CUmesh195 RRana354 ``` When i run a Python code i need output as shown below ``` ALopp190 ARaga789 Lshastri921 DPatel592 ANaidu026 KRam161 SPatil322 LAgarwal908 AKeshri132 BRaju105 LNaik110 PNeema163 SRoy977 AAgarwal594 AMath577 BSharma865 CUmesh195 RRana354 ``` From that text file i need only the above data.This is what i had tried but its not working ``` def user(li): n = len (li) for j in range(0, n, 2): print (li[j]) import os os.getcwd() fo = open(r'C:\\Users\\Kiran\\Desktop\\Emplyoees\\User.txt', 'r') for i in fo.readlines(): li = list(i.split(" ")) #print (li) li.remove("GROUP") li.remove("KCT") li.remove("KBN") li.remove("PDA") user (li) ``` I am new to python and not sure how to get the data. Can you please assist me in fixing this issue.
2020/07/01
[ "https://Stackoverflow.com/questions/62670115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13761107/" ]
As others have mentioned, you can source your `.vimrc`, but that doesn't completely reset Vim. If you want to just restart Vim, then you can do so by re-execing it. Vim doesn't provide a built-in way to exec processes from within it, since typically one doesn't want to replace one's editor with another process, but it is possible to do so with Perl or Ruby, as you see fit: ``` :perl exec "vim" ``` or ``` :ruby exec "vim" ``` This may or may not work on Windows, and it of course requires that your Vim version have been compiled with support for the appropriate interpreters. Debian provides both in the `vim-nox`, `vim-gtk3`, and `vim-athena` packages, but not in `vim` or `vim-tiny`; Ubuntu, last I checked, did not provide Ruby support but did include Perl. If you want to re-exec with the same buffer, you can use one of these: ``` :perl exec "vim", $curbuf->Name(); ``` or ``` :ruby exec "vim", Vim::Buffer.current.name ``` Note that re-execing may cause your screen to be slightly messed up when exiting, so you may need to use `reset` to set it back to normal.
In order to apply the changes, you don't have to exit vim and open it again, no need for a "hard refresh" :) If you want to apply in on the .vimrc file itself, you can type ``` :so % ``` to apply the changes in another file, you can type: ``` :so ~/.vimrc #path to your .vimrc file ``` in normal mode, `Ctrl-O` takes you to where your cursor has been backward and `Ctrl-I` forward. You can check your jump list by typing `:jumps`, to clear your jumps :clearjumps in insert mode, `Ctrl-O` escapes to normal mode and lets the user to do one normal mode command.
28,769,698
I am learning python. I have a file like this ``` str1 str2 str3 str4 str1 str2 str7 str8 *** str9 str10 str12 str13 str9 str10 str16 str17 **** str 18 str19 str20 str21 *** ``` and so on. I want to change it to this format-> ``` str1 str2 str3 str4 str2 str7 str8 str9 str10 str12 str13 str10 str16 str17 str 18 str19 str20 str21 ``` so if the first 2 words are common between 2 lines, arrange the lines together and remove the first word to a separate line. This should be changeable recursively but i can't seem to figure it out
2015/02/27
[ "https://Stackoverflow.com/questions/28769698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/612258/" ]
A class diagram shows classes in their relation and their properties and methods. A state diagram visualizes a class's states and how they can change over time. In both cases you are talking about diagrams which are only a window into the model. The class relations define how the single classes relate to each other. A state machine can be defined for each class to show its states. In embedded systems you use state machines almost all the time but there are also state machines for business applications (you can do this if that).
A state diagram shows the behavior of the class. A class model shows the relationship between two or more classes. It includes its properties/attributes... A state is an allowable sequence of changes of objects of a class model.
28,769,698
I am learning python. I have a file like this ``` str1 str2 str3 str4 str1 str2 str7 str8 *** str9 str10 str12 str13 str9 str10 str16 str17 **** str 18 str19 str20 str21 *** ``` and so on. I want to change it to this format-> ``` str1 str2 str3 str4 str2 str7 str8 str9 str10 str12 str13 str10 str16 str17 str 18 str19 str20 str21 ``` so if the first 2 words are common between 2 lines, arrange the lines together and remove the first word to a separate line. This should be changeable recursively but i can't seem to figure it out
2015/02/27
[ "https://Stackoverflow.com/questions/28769698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/612258/" ]
This question reveals a very common misunderstanding. There are only thirteen types of diagram in UML. They're not used to describe different types of system, but to describe different aspects of the system you are documenting. Which you pick in any given situation is more a question of style, what you want to emphasize. It is better to use state diagrams if you want to focus on how the system can go into different states in response to various events. Activity diagrams are better if you want to focus on activities being carried out in some order, sequence diagrams are better if you want to show messages being sent between entities. The above are all types of diagram which show behaviour. Class diagrams are a different type of beast altogether, and show how structures of things fit together (as do package diagrams and component diagrams). It might be worth pointing out that while UML does not include a "requirement" element type, the related modelling language SysML does. If you want to express a number of functional requirements on the form "the system shall" in a model, SysML is a better fit.
A state diagram shows the behavior of the class. A class model shows the relationship between two or more classes. It includes its properties/attributes... A state is an allowable sequence of changes of objects of a class model.
69,325,145
Suppose I have a string of A's and B's. I can either remove a character from either end of the string for a cost of 1, or I can remove any character from the middle for a cost of 2. What's the minimum cost to create a string of only A's? For example, if I have the string "BBABAA", then the minimum cost to remove is 4, since I would remove the B's from the left for a cost of 2, then remove the singular B from the right for a cost of 2, resulting in a combined cost of 4. I attempted a top-down solution with caching below: ```python def MRC_helper(s, count, cache): if count == 0: cache[s] = 0 cache[s[::-1]] = 0 return 0 if s in cache: return cache[s] min_cost = len(s) for i in range(len(s)): new_count = count - int(s[i] == 'B') new_s = s[:i]+s[i+1:] if i == 0 or i == len(s)-1: min_cost = min(min_cost, 1 + MRC_helper(new_s, new_count, cache)) elif s[i] == 'B': min_cost = min(min_cost, 2 + MRC_helper(new_s, new_count, cache)) cache[s] = min_cost cache[s[::-1]] = min_cost return min_cost def minRemovalCost(s): min_cost = MRC_helper(s, s.count('B'), {}) return min_cost ``` The idea is pretty simple: for each character that you can remove, try to remove it and calculate the cost to transform the resulting substring. Then calculate the minimum cost move and cache it. I also cache the string forwards and backwards since it's the same thing. My friend said that it could be done greedily, but I disagree. Can anybody shed some light on a better solution than mine?
2021/09/25
[ "https://Stackoverflow.com/questions/69325145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11228246/" ]
All `B`s must be removed. If we remove one `B` from the middle, we split the string into two sections. For the section on the right, none of the characters could be deleted from the left since otherwise we would have deleted the `B` from the left at a lower cost for that deletion. Mirror for the section on the left. A section that cannot have deletions from one side can be solved by iterating from the side that allows deletion and at each point comparing the costs of that deletion vs a middle deletion. Precalculate the latter and meet in the optimal middle. ``` Example 1: BBABAA x cost_l: --> 122444 cost_r: 642200 <-- x optimal: 22 = 4 22 = 4 40 = 4 40 = 4 4 = 4 Example 2: ABBA x cost_l: --> 0233 cost_r: 3320 <-- x optimal: 3 = 3 30 = 3 03 = 3 3 = 3 ``` In case it's unclear, the one-sided cost calculation is: ``` cost_l(0) -> 0 if str[0] == 'A' else 1 cost_l(i) -> if str[i] == 'B': min(2 + cost_l(i-1), i + 1) else: cost_l(i - 1) ``` (Mirror for `cost_r`.)
Let `C` be an array where `C[i]` Is the optimal cost for the substring `s[0:i+1]`(assuming right sise Is exclusive]. Consider another game, exactly the same, EXCEPT eating from the right costs 2 instead of 1. Let `D` be the associated cost array of this new game, this cost is helpful to keep track of situations where we restrict ourselves to not eating the last element of a substring. We compute `C` and `D` in a single pass loop as follows: The optimal cost values for the subtring consisting of the first character are: ``` C[0] = int(s1=='B' )# (1 if It Is B, 0 otherwise) D[0] = int( s1=='B') ``` For i+1, if we eat the last character, the cost is `1+C[i]` (we must eat last character if It is 'B') If we don't eat the last character,the cost equals `D[i]` since we can't eat from the right. So ``` C[i+1]=C[i]+1 if s[i+1]=='B' else min(C[i]+1,D[i]) ``` and similarly for the second game, if we eat the last character, then either we pay 2 from eating it from the right, or we have to eat everything to the left of it as well. So ``` D[i+1]=min(D[i]+2, i+1) if s[i+1]=='B' else D[i]. ``` So we iterate over i, and output `C[len(s)]`. This Is O(len(s)) in time and memory, although if we only keep the costs from the previous iteration It becomes constant in memory(not recommended since we can no longer recover the optimal policy by backtracking).
69,325,145
Suppose I have a string of A's and B's. I can either remove a character from either end of the string for a cost of 1, or I can remove any character from the middle for a cost of 2. What's the minimum cost to create a string of only A's? For example, if I have the string "BBABAA", then the minimum cost to remove is 4, since I would remove the B's from the left for a cost of 2, then remove the singular B from the right for a cost of 2, resulting in a combined cost of 4. I attempted a top-down solution with caching below: ```python def MRC_helper(s, count, cache): if count == 0: cache[s] = 0 cache[s[::-1]] = 0 return 0 if s in cache: return cache[s] min_cost = len(s) for i in range(len(s)): new_count = count - int(s[i] == 'B') new_s = s[:i]+s[i+1:] if i == 0 or i == len(s)-1: min_cost = min(min_cost, 1 + MRC_helper(new_s, new_count, cache)) elif s[i] == 'B': min_cost = min(min_cost, 2 + MRC_helper(new_s, new_count, cache)) cache[s] = min_cost cache[s[::-1]] = min_cost return min_cost def minRemovalCost(s): min_cost = MRC_helper(s, s.count('B'), {}) return min_cost ``` The idea is pretty simple: for each character that you can remove, try to remove it and calculate the cost to transform the resulting substring. Then calculate the minimum cost move and cache it. I also cache the string forwards and backwards since it's the same thing. My friend said that it could be done greedily, but I disagree. Can anybody shed some light on a better solution than mine?
2021/09/25
[ "https://Stackoverflow.com/questions/69325145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11228246/" ]
All `B`s must be removed. If we remove one `B` from the middle, we split the string into two sections. For the section on the right, none of the characters could be deleted from the left since otherwise we would have deleted the `B` from the left at a lower cost for that deletion. Mirror for the section on the left. A section that cannot have deletions from one side can be solved by iterating from the side that allows deletion and at each point comparing the costs of that deletion vs a middle deletion. Precalculate the latter and meet in the optimal middle. ``` Example 1: BBABAA x cost_l: --> 122444 cost_r: 642200 <-- x optimal: 22 = 4 22 = 4 40 = 4 40 = 4 4 = 4 Example 2: ABBA x cost_l: --> 0233 cost_r: 3320 <-- x optimal: 3 = 3 30 = 3 03 = 3 3 = 3 ``` In case it's unclear, the one-sided cost calculation is: ``` cost_l(0) -> 0 if str[0] == 'A' else 1 cost_l(i) -> if str[i] == 'B': min(2 + cost_l(i-1), i + 1) else: cost_l(i - 1) ``` (Mirror for `cost_r`.)
``` int n = s.length(); int l[] = new int[]; int r[] = new int[]; if(s.charAt(0)=='b') l[0]=1; if(s.charAt(n-1)=='b') r[n-1]=1; for(int i = 1; i<n; i++) { l[i] = Math.min(l[i-1]+2, i+1); } for(int i = n-2; i>=0; i--) { r[i] = Math.min(r[i+1]+2, n-i); } int ans = Math.min(l[n-1], r[0]); for(int i = 0; i<n-1; i++) { ans = Math.min(l[i] + r[i+1]); } return ans; ```
61,190,064
I am trying to create a docker image with opencv in order to display a video. I have the following Dockerfile: ``` FROM python:3 ADD testDocker_1.py / ADD video1.mp4 / RUN pip install opencv-python CMD [ "python", "./testDocker_1.py" ] ``` And the following python script: ``` import cv2 import os if __name__ == '__main__': file_path = './video1.mp4' cap = cv2.VideoCapture(file_path) ret, frame = cap.read() while ret: ret, frame = cap.read() if ret: cv2.imshow('Frame Docker', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break ``` So first I build the Image: ``` $ sudo docker build -t test1 . ``` And the problem comes when I run the container: ``` $ sudo docker run -ti --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix test1 No protocol specified : cannot connect to X server :1 ``` Regards.
2020/04/13
[ "https://Stackoverflow.com/questions/61190064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11266804/" ]
Try this ``` xhost + sudo docker run -ti --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix test1 ``` Although it would solve this particular use case, but you need to make a note of the following: > > **Basically, the xhost + allows everybody to use your host x server;** > > > [Refrence](https://marcosnietoblog.wordpress.com/2017/04/30/docker-image-with-opencv-with-x11-forwarding-for-gui/) A better and recommended solution is present [here](https://stackoverflow.com/questions/16296753/can-you-run-gui-applications-in-a-docker-container/)
Kapil Khandelwal, your solution works for me. But only using the docker image on ubuntu, when I try to share it with windows it does not work.+
18,744,584
Right, I am trying to setup a django dev site based on a current live site. I've setup the new virtualenv and installed all of the dependencies. I've also made a copy of the database and done a fresh DB dump. I'm now getting the error above and I have no idea why. My django.wsgi file seems to be pointing at the virtalenv. Here is a little more info on the error. ``` Request Method: GET Request URL: http://website.co.uk/ Django Version: 1.3 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'endswith' Exception Location: /usr/lib/python2.6/posixpath.py in join, line 67 Python Executable: /usr/bin/python Python Version: 2.6.5 Python Path: ['/var/www/website.co.uk/website/', '/var/www/website.co.uk/website/apps', '/var/www/website.co.uk/website/apps', '/var/www/website.co.uk', '/var/www/website.co.uk/lib/python2.6/site-packages/distribute-0.6.10-py2.6.egg', '/var/www/website.co.uk/lib/python2.6/site-packages/pip-1.4.1-py2.6.egg', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/pymodules/python2.6', '/usr/local/lib/python2.6/dist-packages', '/var/www/website.co.uk/lib/python2.6/site-packages', '/var/www/website.co.uk/lib/python2.6/site-packages/PIL'] FULL TRACEBACK Environment: Request Method: GET Request URL: http://website.co.uk/ Django Version: 1.3 Python Version: 2.6.5 Installed Applications: ['django.contrib.sites', 'satchmo_store.shop', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.comments', 'django.contrib.sessions', 'django.contrib.sitemaps', 'registration', 'sorl.thumbnail', 'keyedcache', 'livesettings', 'l10n', 'tax', 'tax.modules.no', 'tax.modules.area', 'tax.modules.percent', 'shipping', 'product', 'payment', 'satchmo_ext.satchmo_toolbar', 'satchmo_utils', 'app_plugins', 'authority', 'foodies', 'localsite', 'django_extensions', 'south', 'django_wysiwyg', 'mptt', 'tinymce', 'tagging', 'pages', 'filebrowser', 'html5lib'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.doc.XViewMiddleware', 'django.middleware.locale.LocaleMiddleware') Traceback: File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response 101. request.path_info) File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py" in resolve 250. for pattern in self.url_patterns: File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py" in _get_url_patterns 279. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py" in _get_urlconf_module 274. self._urlconf_module = import_module(self.urlconf_name) File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py" in import_module 35. __import__(name) File "/var/www/website.co.uk/website_app/urls.py" in <module> 4. from satchmo_store.urls import urlpatterns File "/var/www/website.co.uk/lib/python2.6/site-packages/satchmo_store/urls/__init__.py" in <module> 28. from default import urlpatterns as defaultpatterns File "/var/www/website.co.uk/lib/python2.6/site-packages/satchmo_store/urls/default.py" in <module> 9. admin.autodiscover() File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/__init__.py" in autodiscover 26. import_module('%s.admin' % app) File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py" in import_module 35. __import__(name) File "/var/www/website.co.uk/website_app/foodies/admin.py" in <module> 2. from foodies.models import * File "/var/www/website.co.uk/website_app/foodies/models.py" in <module> 24. from pages.admin import * File "/var/www/website.co.uk/lib/python2.6/site-packages/pages/admin/__init__.py" in <module> 3. from pages import settings File "/var/www/website.co.uk/lib/python2.6/site-packages/pages/settings.py" in <module> 144. join(_media_url, 'pages/')) File "/usr/lib/python2.6/posixpath.py" in join 67. elif path == '' or path.endswith('/'): Exception Type: AttributeError at / Exception Value: 'NoneType' object has no attribute 'endswith' ``` Code from pages/settings.py ``` # -*- coding: utf-8 -*- """Convenience module that provides default settings for the ``pages`` application when the project ``settings`` module does not contain the appropriate settings.""" from os.path import join from django.conf import settings from django.core.exceptions import ImproperlyConfigured # The path to default template DEFAULT_PAGE_TEMPLATE = getattr(settings, 'DEFAULT_PAGE_TEMPLATE', None) if DEFAULT_PAGE_TEMPLATE is None: raise ImproperlyConfigured('Please make sure you specified a ' 'DEFAULT_PAGE_TEMPLATE setting.') # PAGE_TEMPLATES is a list of tuples that specifies the which templates # are available in the ``pages`` admin. Templates should be assigned in # the following format: # # PAGE_TEMPLATES = ( # ('pages/nice.html', 'nice one'), # ('pages/cool.html', 'cool one'), # ) # # One can also assign a callable (which should return the tuple) to this # variable to achieve dynamic template list e.g.: # # def _get_templates(): # ... # # PAGE_TEMPLATES = _get_templates PAGE_TEMPLATES = getattr(settings, 'PAGE_TEMPLATES', None) if (PAGE_TEMPLATES is None and not (isinstance(PAGE_TEMPLATES, str) or isinstance(PAGE_TEMPLATES, unicode))): PAGE_TEMPLATES = () # The callable that is used by the CMS def get_page_templates(): if callable(PAGE_TEMPLATES): return PAGE_TEMPLATES() else: return PAGE_TEMPLATES # Set ``PAGE_TAGGING`` to ``False`` if you do not wish to use the # ``django-tagging`` application. PAGE_TAGGING = getattr(settings, 'PAGE_TAGGING', False) if PAGE_TAGGING and "tagging" not in getattr(settings, 'INSTALLED_APPS', []): raise ImproperlyConfigured('django-tagging could not be found.\n' 'Please make sure you\'ve installed it ' 'correctly or disable the tagging feature by ' 'setting PAGE_TAGGING to False.') # Set this to ``True`` if you wish to use the ``django-tinymce`` application. PAGE_TINYMCE = getattr(settings, 'PAGE_TINYMCE', False) if PAGE_TINYMCE and "tinymce" not in getattr(settings, 'INSTALLED_APPS', []): raise ImproperlyConfigured('django-tinymce could not be found.\n' 'Please make sure you\'ve installed it ' 'correctly or disable the tinymce feature by ' 'setting PAGE_TINYMCE to False.') # Set ``PAGE_UNIQUE_SLUG_REQUIRED`` to ``True`` to enforce unique slug names # for all pages. PAGE_UNIQUE_SLUG_REQUIRED = getattr(settings, 'PAGE_UNIQUE_SLUG_REQUIRED', False) # Set ``PAGE_CONTENT_REVISION`` to ``False`` to disable the recording of # pages revision information in the database PAGE_CONTENT_REVISION = getattr(settings, 'PAGE_CONTENT_REVISION', True) # A list tuples that defines the languages that pages can be translated into. # # gettext_noop = lambda s: s # # PAGE_LANGUAGES = ( # ('zh-cn', gettext_noop('Chinese Simplified')), # ('fr-ch', gettext_noop('Swiss french')), # ('en-us', gettext_noop('US English')), #) PAGE_LANGUAGES = getattr(settings, 'PAGE_LANGUAGES', settings.LANGUAGES) # Defines which language should be used by default. If # ``PAGE_DEFAULT_LANGUAGE`` not specified, then project's # ``settings.LANGUAGE_CODE`` is used PAGE_DEFAULT_LANGUAGE = getattr(settings, 'PAGE_DEFAULT_LANGUAGE', settings.LANGUAGE_CODE) extra = [('can_freeze', 'Can freeze page',)] for lang in PAGE_LANGUAGES: extra.append( ('can_manage_' + lang[0].replace('-', '_'), 'Manage' + ' ' + lang[1]) ) PAGE_EXTRA_PERMISSIONS = getattr(settings, 'PAGE_EXTRA_PERMISSIONS', extra) # PAGE_LANGUAGE_MAPPING should be assigned a function that takes a single # argument, the language code of the incoming browser request. This function # maps the incoming client language code to another language code, presumably # one for which you have translation strings. This is most useful if your # project only has one set of translation strings for a language like Chinese, # which has several variants like ``zh-cn``, ``zh-tw``, ``zh-hk`, etc., but # you want to provide your Chinese translations to all Chinese browsers, not # just those with the exact ``zh-cn`` # locale. # # Enable that behavior here by assigning the following function to the # PAGE_LANGUAGE_MAPPING variable. # # def language_mapping(lang): # if lang.startswith('zh'): # return 'zh-cn' # return lang # PAGE_LANGUAGE_MAPPING = language_mapping PAGE_LANGUAGE_MAPPING = getattr(settings, 'PAGE_LANGUAGE_MAPPING', lambda l: l) # Set SITE_ID to the id of the default ``Site`` instance to be used on # installations where content from a single installation is served on # multiple domains via the ``django.contrib.sites`` framework. SITE_ID = getattr(settings, 'SITE_ID', 1) # Set PAGE_USE_SITE_ID to ``True`` to make use of the ``django.contrib.sites`` # framework PAGE_USE_SITE_ID = getattr(settings, 'PAGE_USE_SITE_ID', False) # Set PAGE_USE_LANGUAGE_PREFIX to ``True`` to make the ``get_absolute_url`` # method to prefix the URLs with the language code PAGE_USE_LANGUAGE_PREFIX = getattr(settings, 'PAGE_USE_LANGUAGE_PREFIX', False) # Assign a list of placeholders to PAGE_CONTENT_REVISION_EXCLUDE_LIST # to exclude them from the revision process. PAGE_CONTENT_REVISION_EXCLUDE_LIST = getattr(settings, 'PAGE_CONTENT_REVISION_EXCLUDE_LIST', () ) # Set ``PAGE_SANITIZE_USER_INPUT`` to ``True`` to sanitize the user input with # ``html5lib`` PAGE_SANITIZE_USER_INPUT = getattr(settings, 'PAGE_SANITIZE_USER_INPUT', False) # URL that handles pages media and uses <MEDIA_ROOT>/pages by default. _media_url = getattr(settings, "STATIC_URL", settings.MEDIA_URL) PAGES_MEDIA_URL = getattr(settings, 'PAGES_MEDIA_URL', join(_media_url, 'pages/')) # Hide the slug's of the first root page ie: ``/home/`` becomes ``/`` PAGE_HIDE_ROOT_SLUG = getattr(settings, 'PAGE_HIDE_ROOT_SLUG', False) # Show the publication start date field in the admin. Allows for future dating # Changing the ``PAGE_SHOW_START_DATE`` from ``True`` to ``False`` # after adding data could cause some weirdness. If you must do this, you # should update your database to correct any future dated pages. PAGE_SHOW_START_DATE = getattr(settings, 'PAGE_SHOW_START_DATE', False) # Show the publication end date field in the admin, allows for page expiration # Changing ``PAGE_SHOW_END_DATE`` from ``True`` to ``False`` after adding # data could cause some weirdness. If you must do this, you should update # your database and null any pages with ``publication_end_date`` set. PAGE_SHOW_END_DATE = getattr(settings, 'PAGE_SHOW_END_DATE', False) # ``PAGE_CONNECTED_MODELS`` allows you to specify a model and form for this # model into your settings to get an automatic form to create # and directly link a new instance of this model with your page in the admin. # # Here is an example: # # PAGE_CONNECTED_MODELS = [ # {'model':'documents.models.Document', # 'form':'documents.models.DocumentForm'}, # ] # PAGE_CONNECTED_MODELS = getattr(settings, 'PAGE_CONNECTED_MODELS', False) # The page link filter enable a output filter on you content links. The goal # is to transform special page class into real links at the last moment. # This ensure that even if you have moved a page, the URL will remain correct. PAGE_LINK_FILTER = getattr(settings, 'PAGE_LINK_FILTER', False) # This setting is a function that can be defined if you need to pass extra # context data to the pages templates. PAGE_EXTRA_CONTEXT = getattr(settings, 'PAGE_EXTRA_CONTEXT', None) # This setting is the name of a sub-folder where uploaded content, like # placeholder images, is placed. PAGE_UPLOAD_ROOT = getattr(settings, 'PAGE_UPLOAD_ROOT', 'upload') ``` I hope this is enough to go on but i'm really stuck as to why this is coming up! Thanks
2013/09/11
[ "https://Stackoverflow.com/questions/18744584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1256637/" ]
In this stanza: ``` # URL that handles pages media and uses <MEDIA_ROOT>/pages by default. _media_url = getattr(settings, "STATIC_URL", settings.MEDIA_URL) PAGES_MEDIA_URL = getattr(settings, 'PAGES_MEDIA_URL', join(_media_url, 'pages/')) ``` `STATIC_URL` is not in settings, and `settings.MEDIA_URL` is `None`. Looks like you need to fix your settings.
in this line, ``` ile "/usr/lib/python2.6/posixpath.py" in join 67. elif path == '' or path.endswith('/'): ``` path is None. so a nonetype("path") has to attribute .endswith i would suggest like the other users said to put the full traceback error and check your code and see why path is None.
24,589,241
I just wrote a Google Cloud Endpoints API using Python (using the latest Mac OS), and now need to create an Android Client by following this: <https://developers.google.com/appengine/docs/python/endpoints/endpoints_tool> In the instructions, it says that there's a file called endpointscfg.py under google\_appengine, but I can't find them. When I downloaded the GAE SDK for Mac, I only got a DMG containing GoogleAppEngineLauncher.app. I placed it under my Applications folder. Below is the contents of GoogleAppEnglineLauncher.app, with clearly no \*.py files. ``` my-macbook-pro:GoogleAppEngineLauncher.app user1$ ls -al total 0 drwxr-xr-x@ 3 user1 admin 102 May 30 10:16 . drwxrwxr-x+ 124 root admin 4216 Jul 5 10:50 .. drwxr-xr-x@ 8 user1 admin 272 May 30 10:16 Contents my-macbook-pro:GoogleAppEngineLauncher.app user1$ ``` Where do I find endpointscfg.py? Thanks. Gerard
2014/07/05
[ "https://Stackoverflow.com/questions/24589241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3108752/" ]
After a lot of trial and error I figured out the solution. All in all you need two different things in your project: **1) A class that inherits from ProminentProjectAction:** ``` import hudson.model.ProminentProjectAction; public class MyProjectAction implements ProminentProjectAction { @Override public String getIconFileName() { // return the path to the icon file return "/images/jenkins.png"; } @Override public String getDisplayName() { // return the label for your link return "MyActionLink"; } @Override public String getUrlName() { // defines the suburl, which is appended to ...jenkins/job/jobname return "myactionpage"; } } ``` **2) Even more important is that you add this action somehow to your project.** In my case I wanted to show the link if and only if the related build step of my plugin is configured for the actual project. So I took my Builder class and overwrote the getProjectActionsMethod. ``` public class MyBuilder extends Builder { ... @Override public Collection<? extends Action> getProjectActions(AbstractProject<?,?> project) { List<Action> actions = new ArrayList<>(); actions.add(new MyProjectAction()); return actions; } } ``` Maybe this is not the perfect solution yet (because I'm still trying to figure out how all the artifacts are working together), but it might give people which want to implement the same a good starting point. The page, which is loaded after clicking the link is defined as index.jelly file under source/main/resources and an underlying package with the name of the package of your Action class appended by its class name (e.g. src/main/resources/org/example/myplugin/MyProjectAction).
As it happens, there was a [plugin workshop](http://jenkins-ci.org/content/get-drunk-code-juc-boston) by Steven Christou at the recent [Jenkins User Conference](http://www.cloudbees.com/jenkins/juc-2014/boston) in Boston, which covered this case. You need to add a new RootAction, as shown in the following code from the JUC session ``` package org.jenkinsci.plugins.JUCBeer; import hudson.Extension; import hudson.model.RootAction; @Extension public class JenkinsRootAction implements RootAction { public String getIconFileName() { return "/images/jenkins.png"; } public String getDisplayName() { return "Jenkins home page"; } public String getUrlName() { return "http://jenkins-ci.org"; } } ```
24,589,241
I just wrote a Google Cloud Endpoints API using Python (using the latest Mac OS), and now need to create an Android Client by following this: <https://developers.google.com/appengine/docs/python/endpoints/endpoints_tool> In the instructions, it says that there's a file called endpointscfg.py under google\_appengine, but I can't find them. When I downloaded the GAE SDK for Mac, I only got a DMG containing GoogleAppEngineLauncher.app. I placed it under my Applications folder. Below is the contents of GoogleAppEnglineLauncher.app, with clearly no \*.py files. ``` my-macbook-pro:GoogleAppEngineLauncher.app user1$ ls -al total 0 drwxr-xr-x@ 3 user1 admin 102 May 30 10:16 . drwxrwxr-x+ 124 root admin 4216 Jul 5 10:50 .. drwxr-xr-x@ 8 user1 admin 272 May 30 10:16 Contents my-macbook-pro:GoogleAppEngineLauncher.app user1$ ``` Where do I find endpointscfg.py? Thanks. Gerard
2014/07/05
[ "https://Stackoverflow.com/questions/24589241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3108752/" ]
Root Action and Actions are different. The first one goes only to initial page (root), the second one can be attach to a Project/Job or to a Build. To create a Root Action, just need to create a class that it's: 1. Annotated with @Extension (so it can be found and automatically loaded by Jenkins) 2. Implements RootAction Interface 3. Override 3 methods: getIconFileName(), getDisplayName() and getUrlName() For example: ``` @Extension public class GoogleRootAction implements RootAction{ @Override public String getIconFileName() { return "clipboard.png"; } @Override public String getDisplayName() { return "Google URL"; } @Override public String getUrlName() { return "http://www.google.pt"; } } ``` To create an Action at a Project it's more complicated, and there's more than a way, depending of what you want. But first, the class Action itself is the easy part, since it's very similar to a class RootAction. It's not annotated with @Extension and implements Action interface instead of RootAction. For example: ``` public class LatestConsoleProjectAction implements Action { private AbstractProject<?, ?> project; @Override public String getIconFileName() { return (Jenkins.RESOURCE_PATH + "/images/48x48/terminal.png").replaceFirst("^/", ""); } @Override public String getDisplayName() { return Messages.Latest_Console_Project_Action(); } @Override public String getUrlName() { return "lastBuild/console"; } public LatestConsoleProjectAction(final AbstractProject<?, ?> project) { this.project = project; } } ``` The tricky part is to inform jenkins that this class Action exists. As I said, there are different ways. For instance, one can associate an Action to a Builder or Publisher or other by just overriding getProjectAction() method at those classes. For example: ``` @Override public Action getProjectAction(AbstractProject<?, ?> project) { return new LatestConsoleProjectAction(project); } ``` But this way, the Action link will only show on Project left menu, if the corresponding Builder or Publisher is used by the job (or selected at Job configurations). Another way, that always shows your Action link on left menu, it's create a factory class to inform jenkins. There are many factories, but at my example I will use TransientProjectActionFactory class. For this, one will need to create a class that: 1. It's annotated with @Extensions 2. Extends TransientProjectActionFactory class (or another Factory class) 3. Override createFor method to create your class Action associated with Project object For example: ``` @Extension public class LatestConsoleProjectActionFactory extends TransientProjectActionFactory { @Override public Collection<? extends Action> createFor(AbstractProject abstractProject) { return Collections.singletonList(new LatestConsoleProjectAction(abstractProject)); } } ``` One can still filter project object to just the projects types you want. The one you don't want, just return Collections.emptyList(). Beside this two ways, I think there are others. You can see this link to reference: <https://wiki.jenkins-ci.org/display/JENKINS/Action+and+its+family+of+subtypes> Although, they refer to addAction method and others, but I couldn't use it (I have 2.19.2 Jenkins version). Also they refer groovy, but I didn't try it, since I want to stick with Java :) Btw, my example will create an action link to open console page of last build. Useful to avoid selecting last build and then select his console page.
As it happens, there was a [plugin workshop](http://jenkins-ci.org/content/get-drunk-code-juc-boston) by Steven Christou at the recent [Jenkins User Conference](http://www.cloudbees.com/jenkins/juc-2014/boston) in Boston, which covered this case. You need to add a new RootAction, as shown in the following code from the JUC session ``` package org.jenkinsci.plugins.JUCBeer; import hudson.Extension; import hudson.model.RootAction; @Extension public class JenkinsRootAction implements RootAction { public String getIconFileName() { return "/images/jenkins.png"; } public String getDisplayName() { return "Jenkins home page"; } public String getUrlName() { return "http://jenkins-ci.org"; } } ```
24,589,241
I just wrote a Google Cloud Endpoints API using Python (using the latest Mac OS), and now need to create an Android Client by following this: <https://developers.google.com/appengine/docs/python/endpoints/endpoints_tool> In the instructions, it says that there's a file called endpointscfg.py under google\_appengine, but I can't find them. When I downloaded the GAE SDK for Mac, I only got a DMG containing GoogleAppEngineLauncher.app. I placed it under my Applications folder. Below is the contents of GoogleAppEnglineLauncher.app, with clearly no \*.py files. ``` my-macbook-pro:GoogleAppEngineLauncher.app user1$ ls -al total 0 drwxr-xr-x@ 3 user1 admin 102 May 30 10:16 . drwxrwxr-x+ 124 root admin 4216 Jul 5 10:50 .. drwxr-xr-x@ 8 user1 admin 272 May 30 10:16 Contents my-macbook-pro:GoogleAppEngineLauncher.app user1$ ``` Where do I find endpointscfg.py? Thanks. Gerard
2014/07/05
[ "https://Stackoverflow.com/questions/24589241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3108752/" ]
As it happens, there was a [plugin workshop](http://jenkins-ci.org/content/get-drunk-code-juc-boston) by Steven Christou at the recent [Jenkins User Conference](http://www.cloudbees.com/jenkins/juc-2014/boston) in Boston, which covered this case. You need to add a new RootAction, as shown in the following code from the JUC session ``` package org.jenkinsci.plugins.JUCBeer; import hudson.Extension; import hudson.model.RootAction; @Extension public class JenkinsRootAction implements RootAction { public String getIconFileName() { return "/images/jenkins.png"; } public String getDisplayName() { return "Jenkins home page"; } public String getUrlName() { return "http://jenkins-ci.org"; } } ```
<https://github.com/jenkinsci/s3explorer-plugin> is my Jenkins plugin that adds an `S3 Explorer` link to all Jenkins project's side-panel. [![enter image description here](https://i.stack.imgur.com/WWnWn.png)](https://i.stack.imgur.com/WWnWn.png)
24,589,241
I just wrote a Google Cloud Endpoints API using Python (using the latest Mac OS), and now need to create an Android Client by following this: <https://developers.google.com/appengine/docs/python/endpoints/endpoints_tool> In the instructions, it says that there's a file called endpointscfg.py under google\_appengine, but I can't find them. When I downloaded the GAE SDK for Mac, I only got a DMG containing GoogleAppEngineLauncher.app. I placed it under my Applications folder. Below is the contents of GoogleAppEnglineLauncher.app, with clearly no \*.py files. ``` my-macbook-pro:GoogleAppEngineLauncher.app user1$ ls -al total 0 drwxr-xr-x@ 3 user1 admin 102 May 30 10:16 . drwxrwxr-x+ 124 root admin 4216 Jul 5 10:50 .. drwxr-xr-x@ 8 user1 admin 272 May 30 10:16 Contents my-macbook-pro:GoogleAppEngineLauncher.app user1$ ``` Where do I find endpointscfg.py? Thanks. Gerard
2014/07/05
[ "https://Stackoverflow.com/questions/24589241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3108752/" ]
As it happens, there was a [plugin workshop](http://jenkins-ci.org/content/get-drunk-code-juc-boston) by Steven Christou at the recent [Jenkins User Conference](http://www.cloudbees.com/jenkins/juc-2014/boston) in Boston, which covered this case. You need to add a new RootAction, as shown in the following code from the JUC session ``` package org.jenkinsci.plugins.JUCBeer; import hudson.Extension; import hudson.model.RootAction; @Extension public class JenkinsRootAction implements RootAction { public String getIconFileName() { return "/images/jenkins.png"; } public String getDisplayName() { return "Jenkins home page"; } public String getUrlName() { return "http://jenkins-ci.org"; } } ```
An addition to @dchang [comment](https://stackoverflow.com/a/41149546/4233342): I managed to make this functionality work also on pipelines by extending `TransientActionFactory<WorkflowJob>`: ``` @Extension public static class PipelineLatestConsoleProjectActionFactory extends TransientActionFactory<WorkflowJob> { @Override public Class<WorkflowJob> type() { return WorkflowJob.class; } @Nonnull @Override public Collection<? extends Action> createFor(@Nonnull WorkflowJob job) { return Collections.singletonList(new LatestConsoleProjectAction(job)); } } ```
24,589,241
I just wrote a Google Cloud Endpoints API using Python (using the latest Mac OS), and now need to create an Android Client by following this: <https://developers.google.com/appengine/docs/python/endpoints/endpoints_tool> In the instructions, it says that there's a file called endpointscfg.py under google\_appengine, but I can't find them. When I downloaded the GAE SDK for Mac, I only got a DMG containing GoogleAppEngineLauncher.app. I placed it under my Applications folder. Below is the contents of GoogleAppEnglineLauncher.app, with clearly no \*.py files. ``` my-macbook-pro:GoogleAppEngineLauncher.app user1$ ls -al total 0 drwxr-xr-x@ 3 user1 admin 102 May 30 10:16 . drwxrwxr-x+ 124 root admin 4216 Jul 5 10:50 .. drwxr-xr-x@ 8 user1 admin 272 May 30 10:16 Contents my-macbook-pro:GoogleAppEngineLauncher.app user1$ ``` Where do I find endpointscfg.py? Thanks. Gerard
2014/07/05
[ "https://Stackoverflow.com/questions/24589241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3108752/" ]
After a lot of trial and error I figured out the solution. All in all you need two different things in your project: **1) A class that inherits from ProminentProjectAction:** ``` import hudson.model.ProminentProjectAction; public class MyProjectAction implements ProminentProjectAction { @Override public String getIconFileName() { // return the path to the icon file return "/images/jenkins.png"; } @Override public String getDisplayName() { // return the label for your link return "MyActionLink"; } @Override public String getUrlName() { // defines the suburl, which is appended to ...jenkins/job/jobname return "myactionpage"; } } ``` **2) Even more important is that you add this action somehow to your project.** In my case I wanted to show the link if and only if the related build step of my plugin is configured for the actual project. So I took my Builder class and overwrote the getProjectActionsMethod. ``` public class MyBuilder extends Builder { ... @Override public Collection<? extends Action> getProjectActions(AbstractProject<?,?> project) { List<Action> actions = new ArrayList<>(); actions.add(new MyProjectAction()); return actions; } } ``` Maybe this is not the perfect solution yet (because I'm still trying to figure out how all the artifacts are working together), but it might give people which want to implement the same a good starting point. The page, which is loaded after clicking the link is defined as index.jelly file under source/main/resources and an underlying package with the name of the package of your Action class appended by its class name (e.g. src/main/resources/org/example/myplugin/MyProjectAction).
<https://github.com/jenkinsci/s3explorer-plugin> is my Jenkins plugin that adds an `S3 Explorer` link to all Jenkins project's side-panel. [![enter image description here](https://i.stack.imgur.com/WWnWn.png)](https://i.stack.imgur.com/WWnWn.png)
24,589,241
I just wrote a Google Cloud Endpoints API using Python (using the latest Mac OS), and now need to create an Android Client by following this: <https://developers.google.com/appengine/docs/python/endpoints/endpoints_tool> In the instructions, it says that there's a file called endpointscfg.py under google\_appengine, but I can't find them. When I downloaded the GAE SDK for Mac, I only got a DMG containing GoogleAppEngineLauncher.app. I placed it under my Applications folder. Below is the contents of GoogleAppEnglineLauncher.app, with clearly no \*.py files. ``` my-macbook-pro:GoogleAppEngineLauncher.app user1$ ls -al total 0 drwxr-xr-x@ 3 user1 admin 102 May 30 10:16 . drwxrwxr-x+ 124 root admin 4216 Jul 5 10:50 .. drwxr-xr-x@ 8 user1 admin 272 May 30 10:16 Contents my-macbook-pro:GoogleAppEngineLauncher.app user1$ ``` Where do I find endpointscfg.py? Thanks. Gerard
2014/07/05
[ "https://Stackoverflow.com/questions/24589241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3108752/" ]
After a lot of trial and error I figured out the solution. All in all you need two different things in your project: **1) A class that inherits from ProminentProjectAction:** ``` import hudson.model.ProminentProjectAction; public class MyProjectAction implements ProminentProjectAction { @Override public String getIconFileName() { // return the path to the icon file return "/images/jenkins.png"; } @Override public String getDisplayName() { // return the label for your link return "MyActionLink"; } @Override public String getUrlName() { // defines the suburl, which is appended to ...jenkins/job/jobname return "myactionpage"; } } ``` **2) Even more important is that you add this action somehow to your project.** In my case I wanted to show the link if and only if the related build step of my plugin is configured for the actual project. So I took my Builder class and overwrote the getProjectActionsMethod. ``` public class MyBuilder extends Builder { ... @Override public Collection<? extends Action> getProjectActions(AbstractProject<?,?> project) { List<Action> actions = new ArrayList<>(); actions.add(new MyProjectAction()); return actions; } } ``` Maybe this is not the perfect solution yet (because I'm still trying to figure out how all the artifacts are working together), but it might give people which want to implement the same a good starting point. The page, which is loaded after clicking the link is defined as index.jelly file under source/main/resources and an underlying package with the name of the package of your Action class appended by its class name (e.g. src/main/resources/org/example/myplugin/MyProjectAction).
An addition to @dchang [comment](https://stackoverflow.com/a/41149546/4233342): I managed to make this functionality work also on pipelines by extending `TransientActionFactory<WorkflowJob>`: ``` @Extension public static class PipelineLatestConsoleProjectActionFactory extends TransientActionFactory<WorkflowJob> { @Override public Class<WorkflowJob> type() { return WorkflowJob.class; } @Nonnull @Override public Collection<? extends Action> createFor(@Nonnull WorkflowJob job) { return Collections.singletonList(new LatestConsoleProjectAction(job)); } } ```
24,589,241
I just wrote a Google Cloud Endpoints API using Python (using the latest Mac OS), and now need to create an Android Client by following this: <https://developers.google.com/appengine/docs/python/endpoints/endpoints_tool> In the instructions, it says that there's a file called endpointscfg.py under google\_appengine, but I can't find them. When I downloaded the GAE SDK for Mac, I only got a DMG containing GoogleAppEngineLauncher.app. I placed it under my Applications folder. Below is the contents of GoogleAppEnglineLauncher.app, with clearly no \*.py files. ``` my-macbook-pro:GoogleAppEngineLauncher.app user1$ ls -al total 0 drwxr-xr-x@ 3 user1 admin 102 May 30 10:16 . drwxrwxr-x+ 124 root admin 4216 Jul 5 10:50 .. drwxr-xr-x@ 8 user1 admin 272 May 30 10:16 Contents my-macbook-pro:GoogleAppEngineLauncher.app user1$ ``` Where do I find endpointscfg.py? Thanks. Gerard
2014/07/05
[ "https://Stackoverflow.com/questions/24589241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3108752/" ]
Root Action and Actions are different. The first one goes only to initial page (root), the second one can be attach to a Project/Job or to a Build. To create a Root Action, just need to create a class that it's: 1. Annotated with @Extension (so it can be found and automatically loaded by Jenkins) 2. Implements RootAction Interface 3. Override 3 methods: getIconFileName(), getDisplayName() and getUrlName() For example: ``` @Extension public class GoogleRootAction implements RootAction{ @Override public String getIconFileName() { return "clipboard.png"; } @Override public String getDisplayName() { return "Google URL"; } @Override public String getUrlName() { return "http://www.google.pt"; } } ``` To create an Action at a Project it's more complicated, and there's more than a way, depending of what you want. But first, the class Action itself is the easy part, since it's very similar to a class RootAction. It's not annotated with @Extension and implements Action interface instead of RootAction. For example: ``` public class LatestConsoleProjectAction implements Action { private AbstractProject<?, ?> project; @Override public String getIconFileName() { return (Jenkins.RESOURCE_PATH + "/images/48x48/terminal.png").replaceFirst("^/", ""); } @Override public String getDisplayName() { return Messages.Latest_Console_Project_Action(); } @Override public String getUrlName() { return "lastBuild/console"; } public LatestConsoleProjectAction(final AbstractProject<?, ?> project) { this.project = project; } } ``` The tricky part is to inform jenkins that this class Action exists. As I said, there are different ways. For instance, one can associate an Action to a Builder or Publisher or other by just overriding getProjectAction() method at those classes. For example: ``` @Override public Action getProjectAction(AbstractProject<?, ?> project) { return new LatestConsoleProjectAction(project); } ``` But this way, the Action link will only show on Project left menu, if the corresponding Builder or Publisher is used by the job (or selected at Job configurations). Another way, that always shows your Action link on left menu, it's create a factory class to inform jenkins. There are many factories, but at my example I will use TransientProjectActionFactory class. For this, one will need to create a class that: 1. It's annotated with @Extensions 2. Extends TransientProjectActionFactory class (or another Factory class) 3. Override createFor method to create your class Action associated with Project object For example: ``` @Extension public class LatestConsoleProjectActionFactory extends TransientProjectActionFactory { @Override public Collection<? extends Action> createFor(AbstractProject abstractProject) { return Collections.singletonList(new LatestConsoleProjectAction(abstractProject)); } } ``` One can still filter project object to just the projects types you want. The one you don't want, just return Collections.emptyList(). Beside this two ways, I think there are others. You can see this link to reference: <https://wiki.jenkins-ci.org/display/JENKINS/Action+and+its+family+of+subtypes> Although, they refer to addAction method and others, but I couldn't use it (I have 2.19.2 Jenkins version). Also they refer groovy, but I didn't try it, since I want to stick with Java :) Btw, my example will create an action link to open console page of last build. Useful to avoid selecting last build and then select his console page.
<https://github.com/jenkinsci/s3explorer-plugin> is my Jenkins plugin that adds an `S3 Explorer` link to all Jenkins project's side-panel. [![enter image description here](https://i.stack.imgur.com/WWnWn.png)](https://i.stack.imgur.com/WWnWn.png)
24,589,241
I just wrote a Google Cloud Endpoints API using Python (using the latest Mac OS), and now need to create an Android Client by following this: <https://developers.google.com/appengine/docs/python/endpoints/endpoints_tool> In the instructions, it says that there's a file called endpointscfg.py under google\_appengine, but I can't find them. When I downloaded the GAE SDK for Mac, I only got a DMG containing GoogleAppEngineLauncher.app. I placed it under my Applications folder. Below is the contents of GoogleAppEnglineLauncher.app, with clearly no \*.py files. ``` my-macbook-pro:GoogleAppEngineLauncher.app user1$ ls -al total 0 drwxr-xr-x@ 3 user1 admin 102 May 30 10:16 . drwxrwxr-x+ 124 root admin 4216 Jul 5 10:50 .. drwxr-xr-x@ 8 user1 admin 272 May 30 10:16 Contents my-macbook-pro:GoogleAppEngineLauncher.app user1$ ``` Where do I find endpointscfg.py? Thanks. Gerard
2014/07/05
[ "https://Stackoverflow.com/questions/24589241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3108752/" ]
Root Action and Actions are different. The first one goes only to initial page (root), the second one can be attach to a Project/Job or to a Build. To create a Root Action, just need to create a class that it's: 1. Annotated with @Extension (so it can be found and automatically loaded by Jenkins) 2. Implements RootAction Interface 3. Override 3 methods: getIconFileName(), getDisplayName() and getUrlName() For example: ``` @Extension public class GoogleRootAction implements RootAction{ @Override public String getIconFileName() { return "clipboard.png"; } @Override public String getDisplayName() { return "Google URL"; } @Override public String getUrlName() { return "http://www.google.pt"; } } ``` To create an Action at a Project it's more complicated, and there's more than a way, depending of what you want. But first, the class Action itself is the easy part, since it's very similar to a class RootAction. It's not annotated with @Extension and implements Action interface instead of RootAction. For example: ``` public class LatestConsoleProjectAction implements Action { private AbstractProject<?, ?> project; @Override public String getIconFileName() { return (Jenkins.RESOURCE_PATH + "/images/48x48/terminal.png").replaceFirst("^/", ""); } @Override public String getDisplayName() { return Messages.Latest_Console_Project_Action(); } @Override public String getUrlName() { return "lastBuild/console"; } public LatestConsoleProjectAction(final AbstractProject<?, ?> project) { this.project = project; } } ``` The tricky part is to inform jenkins that this class Action exists. As I said, there are different ways. For instance, one can associate an Action to a Builder or Publisher or other by just overriding getProjectAction() method at those classes. For example: ``` @Override public Action getProjectAction(AbstractProject<?, ?> project) { return new LatestConsoleProjectAction(project); } ``` But this way, the Action link will only show on Project left menu, if the corresponding Builder or Publisher is used by the job (or selected at Job configurations). Another way, that always shows your Action link on left menu, it's create a factory class to inform jenkins. There are many factories, but at my example I will use TransientProjectActionFactory class. For this, one will need to create a class that: 1. It's annotated with @Extensions 2. Extends TransientProjectActionFactory class (or another Factory class) 3. Override createFor method to create your class Action associated with Project object For example: ``` @Extension public class LatestConsoleProjectActionFactory extends TransientProjectActionFactory { @Override public Collection<? extends Action> createFor(AbstractProject abstractProject) { return Collections.singletonList(new LatestConsoleProjectAction(abstractProject)); } } ``` One can still filter project object to just the projects types you want. The one you don't want, just return Collections.emptyList(). Beside this two ways, I think there are others. You can see this link to reference: <https://wiki.jenkins-ci.org/display/JENKINS/Action+and+its+family+of+subtypes> Although, they refer to addAction method and others, but I couldn't use it (I have 2.19.2 Jenkins version). Also they refer groovy, but I didn't try it, since I want to stick with Java :) Btw, my example will create an action link to open console page of last build. Useful to avoid selecting last build and then select his console page.
An addition to @dchang [comment](https://stackoverflow.com/a/41149546/4233342): I managed to make this functionality work also on pipelines by extending `TransientActionFactory<WorkflowJob>`: ``` @Extension public static class PipelineLatestConsoleProjectActionFactory extends TransientActionFactory<WorkflowJob> { @Override public Class<WorkflowJob> type() { return WorkflowJob.class; } @Nonnull @Override public Collection<? extends Action> createFor(@Nonnull WorkflowJob job) { return Collections.singletonList(new LatestConsoleProjectAction(job)); } } ```
56,674,284
I am trying to use beautiful soup to scrape data from [this](https://www.pro-football-reference.com/play-index/play_finder.cgi?request=1&match=summary_all&year_min=2018&year_max=2018&game_type=R&game_num_min=0&game_num_max=99&week_num_min=0&week_num_max=99&quarter%5B%5D=4&minutes_max=15&seconds_max=00&minutes_min=00&seconds_min=00&down%5B%5D=0&down%5B%5D=1&down%5B%5D=2&down%5B%5D=3&down%5B%5D=4&field_pos_min_field=team&field_pos_max_field=team&end_field_pos_min_field=team&end_field_pos_max_field=team&type%5B%5D=PUNT&no_play=N&turnover_type%5B%5D=interception&turnover_type%5B%5D=fumble&score_type%5B%5D=touchdown&score_type%5B%5D=field_goal&score_type%5B%5D=safety&rush_direction%5B%5D=LE&rush_direction%5B%5D=LT&rush_direction%5B%5D=LG&rush_direction%5B%5D=M&rush_direction%5B%5D=RG&rush_direction%5B%5D=RT&rush_direction%5B%5D=RE&pass_location%5B%5D=SL&pass_location%5B%5D=SM&pass_location%5B%5D=SR&pass_location%5B%5D=DL&pass_location%5B%5D=DM&pass_location%5B%5D=DR&order_by=yards) website. If you scroll down to the **Individual Plays** section, click "share and more > get table as csv" a CSV form of the tabulated data will appear. If I inspect this CSV text I see that it's in a `<pre>` tag and has an id of "csv\_all\_plays" I'm trying to use the python package beautifulsoup to scrape this data. What I'm currently doing is ```py nfl_url = #the url I have linked above driver = webdriver.Chrome(executable_path=r'C:/path/to/chrome/driver') driver.get(nfl_url) html = driver.page_source soup = BeautifulSoup(html, 'html.parser') print(soup.find(id="csv_all_plays")) ``` This just results in "None" being printed. I know that because this data isn't being displayed when the page is loaded means I can't use the Requests package and I have to use something that actually gets the whole page's source (I'm using Selenium). Is that not what I'm doing here? Is it a different reason that I can't get the CSV data?
2019/06/19
[ "https://Stackoverflow.com/questions/56674284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5657167/" ]
You can use `selenium` to hover over the "Share & more" link to display the menu, from which you can click the "Get table as csv": ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from bs4 import BeautifulSoup as soup d = webdriver.Chrome('/path/to/chromedriver') d.get('https://www.pro-football-reference.com/play-index/play_finder.cgi?request=1&match=summary_all&year_min=2018&year_max=2018&game_type=R&game_num_min=0&game_num_max=99&week_num_min=0&week_num_max=99&quarter%5B%5D=4&minutes_max=15&seconds_max=00&minutes_min=00&seconds_min=00&down%5B%5D=0&down%5B%5D=1&down%5B%5D=2&down%5B%5D=3&down%5B%5D=4&field_pos_min_field=team&field_pos_max_field=team&end_field_pos_min_field=team&end_field_pos_max_field=team&type%5B%5D=PUNT&no_play=N&turnover_type%5B%5D=interception&turnover_type%5B%5D=fumble&score_type%5B%5D=touchdown&score_type%5B%5D=field_goal&score_type%5B%5D=safety&rush_direction%5B%5D=LE&rush_direction%5B%5D=LT&rush_direction%5B%5D=LG&rush_direction%5B%5D=M&rush_direction%5B%5D=RG&rush_direction%5B%5D=RT&rush_direction%5B%5D=RE&pass_location%5B%5D=SL&pass_location%5B%5D=SM&pass_location%5B%5D=SR&pass_location%5B%5D=DL&pass_location%5B%5D=DM&pass_location%5B%5D=DR&order_by=yards') scroll = ActionChains(d).move_to_element(d.find_element_by_id('all_all_plays')) scroll.perform() spans = [i for i in d.find_elements_by_tag_name('span') if 'Share & more' in i.text] hover = ActionChains(d).move_to_element(spans[-1]) hover.perform() b = [i for i in d.find_elements_by_tag_name('button') if 'get table as csv' in i.text.lower()][0] b.send_keys('\n') csv_data = soup(d.page_source, 'html.parser').find('pre', {'id':'csv_all_plays'}).text ``` Output (shortened due to SO's character limit): ``` "\nDate,Tm,Opp,Quarter,Time,Down,ToGo,Location,Score,Detail,Yds,EPB,EPA,Diff,PYds,PRYds\n2018-09-09,Texans,Patriots,4,4:41,4,8,HTX 36,13-27,Trevor Daniel punts 47 yards muffed catch by Riley McCarron recovered by Johnson Bademosi and returned for no gain,0,-0.980,4.510,5.49,47,\n2018-09-09,Jaguars,Giants,4,0:54,4,6,JAX 40,20-15,Logan Cooke punts 41 yards muffed catch by Kaelin Clay recovered by Donald Payne and returned for no gain,0,-0.720,4.170,4.89,41,\n2018-09-09,Chiefs,Chargers,4,10:35,4,6,KAN 27,31-20,Dustin Colquitt punts 59 yards returned by JJ Jones for no gain. JJ Jones fumbles (forced by De'Anthony Thomas) recovered by James Winchester at LAC-2,0,-1.570,6.740,8.31,59,\n2018-09-23,Dolphins,Raiders,4,12:33,4,5,MIA 39,14-17,Matt Haack punts 42 yards muffed catch by Jordy Nelson recovered by Jordy Nelson and returned for no gain,0,-0.780,0.060,.84,42,\n2018-09-30,Jets,Jaguars,4,8:59,4,10,NYJ 14,12-25,Lac Edwards punts 46 yards muffed catch by Jaydon Mickens ball out of bounds at JAX-41,0,-2.470,-1.660,.81,46,\n2018-10-11,Giants,Eagles,4,12:27,4,17,NYG 33,13-34,Riley Dixon punts 50 yards muffed catch by DeAndre Carter recovered by DeAndre Carter and returned for no gain,0,-1.180,-0.040,1.14,50,\n2018-10-28,Jets,Bears,4,5:37,4,13,NYJ 37,10-24,Lac Edwards punts 48 yards muffed catch by Tarik Cohen recovered by Tarik Cohen and returned for no gain,0,-0.910,0.320,1.23,48,\n2018-11-25,Vikings,Packers,4,6:00,4,13,GNB 37,24-14,Matt Wile punts 21 yards muffed catch by Tramon Williams recovered by Marcus Sherels and returned for no gain,0,0.790,4.580,3.79,21,\n2018-12-13,Chiefs,Chargers,4,2:47,4,15,KAN 6,28-21,Dustin Colquitt punts 55 yards muffed catch by Desmond King recovered by Desmond King and returned for no gain,0,-2.490,-1.600,.89,55, ``` --- To write the csv data to a file: ``` import csv with open('individual_stats.csv', 'w') as f: write = csv.writer(f) write.writerows([list(filter(None, i.split(','))) for i in filter(None, csv_data.split('\n'))]) ``` Output (first 16 rows): ``` Date,Tm,Opp,Quarter,Time,Down,ToGo,Location,Score,Detail,Yds,EPB,EPA,Diff,PYds,PRYds 2018-09-09,Texans,Patriots,4,4:41,4,8,HTX 36,13-27,Trevor Daniel punts 47 yards muffed catch by Riley McCarron recovered by Johnson Bademosi and returned for no gain,0,-0.980,4.510,5.49,47 2018-09-09,Jaguars,Giants,4,0:54,4,6,JAX 40,20-15,Logan Cooke punts 41 yards muffed catch by Kaelin Clay recovered by Donald Payne and returned for no gain,0,-0.720,4.170,4.89,41 2018-09-09,Chiefs,Chargers,4,10:35,4,6,KAN 27,31-20,Dustin Colquitt punts 59 yards returned by JJ Jones for no gain. JJ Jones fumbles (forced by De'Anthony Thomas) recovered by James Winchester at LAC-2,0,-1.570,6.740,8.31,59 2018-09-23,Dolphins,Raiders,4,12:33,4,5,MIA 39,14-17,Matt Haack punts 42 yards muffed catch by Jordy Nelson recovered by Jordy Nelson and returned for no gain,0,-0.780,0.060,.84,42 2018-09-30,Jets,Jaguars,4,8:59,4,10,NYJ 14,12-25,Lac Edwards punts 46 yards muffed catch by Jaydon Mickens ball out of bounds at JAX-41,0,-2.470,-1.660,.81,46 2018-10-11,Giants,Eagles,4,12:27,4,17,NYG 33,13-34,Riley Dixon punts 50 yards muffed catch by DeAndre Carter recovered by DeAndre Carter and returned for no gain,0,-1.180,-0.040,1.14,50 2018-10-28,Jets,Bears,4,5:37,4,13,NYJ 37,10-24,Lac Edwards punts 48 yards muffed catch by Tarik Cohen recovered by Tarik Cohen and returned for no gain,0,-0.910,0.320,1.23,48 2018-11-25,Vikings,Packers,4,6:00,4,13,GNB 37,24-14,Matt Wile punts 21 yards muffed catch by Tramon Williams recovered by Marcus Sherels and returned for no gain,0,0.790,4.580,3.79,21 2018-12-13,Chiefs,Chargers,4,2:47,4,15,KAN 6,28-21,Dustin Colquitt punts 55 yards muffed catch by Desmond King recovered by Desmond King and returned for no gain,0,-2.490,-1.600,.89,55 2018-12-16,Bears,Packers,4,2:51,4,6,CHI 12,24-14,Pat O'Donnell punts 51 yards muffed catch by Josh Jackson recovered by Josh Jackson and returned for no gain,0,-2.490,-1.660,.83,51 2018-12-16,Eagles,Rams,4,3:03,4,12,PHI 15,30-23,Cameron Johnston punts 52 yards returned by Jojo Natson for 3 yards. Jojo Natson fumbles recovered by D.J. Alexander at LAR-36,0,-2.440,3.180,5.62,52,3 2018-12-02,Giants,Bears,4,12:46,4,18,NYG 12,24-14,Riley Dixon punts 53 yards returned by Tarik Cohen for 8 yards (tackle by Rhett Ellison). Tarik Cohen fumbles (forced by Rhett Ellison) recovered by Tarik Cohen at CHI-45. Penalty on Josh Bellamy: Illegal Block Above the Waist 10 yards,-2,-2.490,-0.670,1.82,53,8 2018-11-25,Jaguars,Bills,4,13:33,4,25,JAX 15,14-21,Logan Cooke punts 55 yards returned by Isaiah McKenzie for 9 yards (tackle by Jarrod Wilson). Isaiah McKenzie fumbles (forced by Jarrod Wilson) recovered by Isaiah McKenzie at BUF-43. Penalty on Marcus Murphy: Illegal Block Above the Waist 10 yards,-4,-2.440,-0.670,1.77,55,9 2018-09-06,Eagles,Falcons,4,7:42,4,14,PHI 21,10-12,Cameron Johnston punts 46 yards out of bounds,-1.960,-1.140,.82,46 2018-09-06,Falcons,Eagles,4,5:04,4,14,ATL 29,12-10,Matthew Bosher punts 52 yards returned by Darren Sproles for 12 yards (tackle by Eric Saubert). Penalty on Eric Saubert: Face Mask (15 Yards) 15 yards,-1.440,-1.990,-0.55,52,12 ```
You could just use pandas ``` import pandas as pd table = pd.read_html('https://www.pro-football-reference.com/play-index/play_finder.cgi?request=1&match=summary_all&year_min=2018&year_max=2018&game_type=R&game_num_min=0&game_num_max=99&week_num_min=0&week_num_max=99&quarter%5B%5D=4&minutes_max=15&seconds_max=00&minutes_min=00&seconds_min=00&down%5B%5D=0&down%5B%5D=1&down%5B%5D=2&down%5B%5D=3&down%5B%5D=4&field_pos_min_field=team&field_pos_max_field=team&end_field_pos_min_field=team&end_field_pos_max_field=team&type%5B%5D=PUNT&no_play=N&turnover_type%5B%5D=interception&turnover_type%5B%5D=fumble&score_type%5B%5D=touchdown&score_type%5B%5D=field_goal&score_type%5B%5D=safety&rush_direction%5B%5D=LE&rush_direction%5B%5D=LT&rush_direction%5B%5D=LG&rush_direction%5B%5D=M&rush_direction%5B%5D=RG&rush_direction%5B%5D=RT&rush_direction%5B%5D=RE&pass_location%5B%5D=SL&pass_location%5B%5D=SM&pass_location%5B%5D=SR&pass_location%5B%5D=DL&pass_location%5B%5D=DM&pass_location%5B%5D=DR&order_by=yards')[4] table.to_csv(r'C:\Users\User\Desktop\Data.csv', sep=',', encoding='utf-8-sig',index = False ) ```
44,299,462
I run below commands after unzipping that python 3.6 tar.xz file. ``` ./configure make make install ``` Error log: ``` ranlib libpython3.6m.a gcc -pthread -Xlinker -export-dynamic -o python Programs/python.o libpython3.6m.a -lpthread -ldl -lutil -lrt -lm if test "no-framework" = "no-framework" ; then \ /usr/bin/install -c python /usr/local/bin/python3.6m; \ else \ /usr/bin/install -c -s Mac/pythonw /usr/local/bin/python3.6m; \ fi /usr/bin/install: cannot create regular file `/usr/local/bin/python3.6m': Read-only file system make: *** [altbininstall] Error 1 ``` When i run ./configure followed by make , and then make install i run into this error!
2017/06/01
[ "https://Stackoverflow.com/questions/44299462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4909084/" ]
Have you tried running the above commands using `sudo` powers? original answer: <https://askubuntu.com/q/865554/667903> `sudo make install` **or** If you are using Ubuntu 16.10 or 17.04, then Python 3.6 is in the universe repository, so you can just run ``` sudo apt-get update sudo apt-get install python3.6 ```
Try after installing build essentials whic contains compilers,package dev tools and libs: sudo apt-get install build-essential
44,299,462
I run below commands after unzipping that python 3.6 tar.xz file. ``` ./configure make make install ``` Error log: ``` ranlib libpython3.6m.a gcc -pthread -Xlinker -export-dynamic -o python Programs/python.o libpython3.6m.a -lpthread -ldl -lutil -lrt -lm if test "no-framework" = "no-framework" ; then \ /usr/bin/install -c python /usr/local/bin/python3.6m; \ else \ /usr/bin/install -c -s Mac/pythonw /usr/local/bin/python3.6m; \ fi /usr/bin/install: cannot create regular file `/usr/local/bin/python3.6m': Read-only file system make: *** [altbininstall] Error 1 ``` When i run ./configure followed by make , and then make install i run into this error!
2017/06/01
[ "https://Stackoverflow.com/questions/44299462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4909084/" ]
Your filesystem seems to be read-only. You have to remount the partition where `/usr/local/bin/` is located with write permissions The syntax for `mount` is ``` mount -o remount,rw /partition/identifier /mount/point ``` Let's say you have `/` on `/dev/sda2` ``` mount -o remount,rw / /dev/sda2 ``` should fix your problem. To check your mount points: `cat /etc/fstab` or `df` To check the permissions: `cat /proc/mounts`
Try after installing build essentials whic contains compilers,package dev tools and libs: sudo apt-get install build-essential
52,929,872
I am trying to read the text in a cheque using pytesseract OCR. I have installed the required python packages required for this task e.g. pip install pytesseract. However when I try to use the package to read the file I get the following error: ``` pytesseract.image_to_string(im, lang='eng') Traceback (most recent call last): File "<ipython-input-17-d7d9f430493b>", line 1, in <module> pytesseract.image_to_string(im, lang='eng') File "C:\Users\BRIGHT\Anaconda3\lib\site-packages\pytesseract\pytesseract.py", line 294, in image_to_string return run_and_get_output(*args) File "C:\Users\BRIGHT\Anaconda3\lib\site-packages\pytesseract\pytesseract.py", line 202, in run_and_get_output run_tesseract(**kwargs) File "C:\Users\BRIGHT\Anaconda3\lib\site-packages\pytesseract\pytesseract.py", line 172, in run_tesseract raise TesseractNotFoundError() TesseractNotFoundError: tesseract is not installed or it's not in your path ``` This error dosent make sense because I actually import the package without getting any error. But when I try to use it I get the error. Here is my code: ``` from PIL import Image import pytesseract im=Image.open('BritishChequeAnnotated.jpg') text=pytesseract.image_to_string(im, lang='eng') ```
2018/10/22
[ "https://Stackoverflow.com/questions/52929872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10122096/" ]
The documentation for tesseract makes this clear. <https://pypi.org/project/pytesseract/> ``` # If you don't have tesseract executable in your PATH, include the following: pytesseract.pytesseract.tesseract_cmd = r'<full_path_to_your_tesseract_executable>' ```
You need to install teserract executable file and include the path into the program then it won't gives any error
41,419,093
I am fairly new to Python and started learning. I am trying to automate data entry. I am stuck at the "save" button. How do I find the right information and click it to save? Thank you so much PyGuy --- Element ``` <input type="submit" value="Save"> ``` Xpath ``` //*[@id="decorated-admin-content"]/div/div/form/div[10]/div/input ``` Selector ``` #decorated-admin-content > div > div > form > div.buttons-container > div > input[type="submit"] ``` --- On my python script, I have entered ``` from selenium import webdriver from selenium.webdriver.common.by import By driver.findElement(By.xpath("//input[@type='submit'and @value='save']")).click() # I also tried below # driver.findElement(By.xpath("//input[@type='submit'][@value='Save']")).click(); # driver.findElement(By.xpath("//*[@id="decorated-admin-content"]")) ```
2017/01/01
[ "https://Stackoverflow.com/questions/41419093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7363397/" ]
If you're using python, the syntax is not right. Python uses snake\_case and By uses CONSTANT convention ``` from selenium import webdriver from selenium.webdriver.common.by import By driver.find_element(By.XPATH, "//input[@type='submit' and @value='save']").click() ``` It's actually suggested to use the individual methods for each By if you don't need to be dynamic: ``` driver.find_element_by_xpath("//input[@type='submit' and @value='save']").click() ``` Or css: ``` driver.find_element_by_css_selector('input[type="submit"]').click() ``` If that doesn't work, can you post the error traceback you are getting?
Did you try with other parameter than xpath ? I also had some difficulties with selenium, you can try the following line : ``` driver.findElement(By.tagName("form")).submit() ``` It's works for me and is useful to validate forms
57,567,892
Previously I asked a similar question: [cx\_Freeze unable fo find mkl: MKL FATAL ERROR: Cannot load mkl\_intel\_thread.dll](https://stackoverflow.com/questions/57493584/cx-freeze-unable-fo-find-mkl-mkl-fatal-error-cannot-load-mkl-intel-thread-dll) But now I have a subtle difference. I want to run the program without installing anaconda, just within a `cmd.exe` terminal, but it seems I am doing something wrong or that it is not possible. After generating my application with `python setup.py bdist_msi` using `cx-freeze`, I am able to install and then run it within an anaconda environment, but if I simply open a `cmd.exe` terminal and run it, I get ``` INTEL MKL ERROR: The specified module could not be found. mkl_intel_thread.dll. Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll. ``` However, when running ``` where mkl_intel_thread.dll ``` the dll is found, so I think this means it's registered in the system (I am more used to use Linux, so may be I am wrong). How could I solve this problem?
2019/08/20
[ "https://Stackoverflow.com/questions/57567892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1612432/" ]
Maybe another DLL necessary for MKL, such as `libiomp5md.dll` for example, is missing and causes the error. See [Cannot load mkl\_intel\_thread.dll on python executable](https://stackoverflow.com/q/54337644/8516269), my answer there and its comments. If this still does not solve your problem, try to manually copy other DLLs from the anaconda environment's library path into the app installation directory and its `lib` subdirectory. Once you have found which dependency is missing, you can use the `include_files` option of cx\_Freeze to automatize this step in the setup (as you know). Another possible issue would be that you have an incompatible version of MKL installed on your system and that the frozen application finds this wrong one, but this is unlikely unless you have a 32-bit Python installation on a 64-bit system or have installed the application on another system. EDIT: It could still also simply be that the frozen application does not find `mkl_intel_thread.dll` although `where` finds it. `where` looks in the system search path given by the `PATH` environment variable, while Python looks in the modules search path given by `sys.path`, which usually does not include the content of `PATH`, see [Where is Python's sys.path initialized from?](https://stackoverflow.com/q/897792/8516269) But on Windows there is a fallback mechanism for registered DLLs (I don't know how it works). Anyway, one should not rely on this fallback as soon as one intends to install and run the application on another system, because the necessary DLL may not be installed there. Thus the necessary dependencies should always be included in the installation directory.
Recently I faced the same error in python3.7 . I did not have the option of moving Dll, I Solved the problem by just doing. ``` conda install cython ``` After the cython install all dll's were in proper place.
57,567,892
Previously I asked a similar question: [cx\_Freeze unable fo find mkl: MKL FATAL ERROR: Cannot load mkl\_intel\_thread.dll](https://stackoverflow.com/questions/57493584/cx-freeze-unable-fo-find-mkl-mkl-fatal-error-cannot-load-mkl-intel-thread-dll) But now I have a subtle difference. I want to run the program without installing anaconda, just within a `cmd.exe` terminal, but it seems I am doing something wrong or that it is not possible. After generating my application with `python setup.py bdist_msi` using `cx-freeze`, I am able to install and then run it within an anaconda environment, but if I simply open a `cmd.exe` terminal and run it, I get ``` INTEL MKL ERROR: The specified module could not be found. mkl_intel_thread.dll. Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll. ``` However, when running ``` where mkl_intel_thread.dll ``` the dll is found, so I think this means it's registered in the system (I am more used to use Linux, so may be I am wrong). How could I solve this problem?
2019/08/20
[ "https://Stackoverflow.com/questions/57567892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1612432/" ]
Maybe another DLL necessary for MKL, such as `libiomp5md.dll` for example, is missing and causes the error. See [Cannot load mkl\_intel\_thread.dll on python executable](https://stackoverflow.com/q/54337644/8516269), my answer there and its comments. If this still does not solve your problem, try to manually copy other DLLs from the anaconda environment's library path into the app installation directory and its `lib` subdirectory. Once you have found which dependency is missing, you can use the `include_files` option of cx\_Freeze to automatize this step in the setup (as you know). Another possible issue would be that you have an incompatible version of MKL installed on your system and that the frozen application finds this wrong one, but this is unlikely unless you have a 32-bit Python installation on a 64-bit system or have installed the application on another system. EDIT: It could still also simply be that the frozen application does not find `mkl_intel_thread.dll` although `where` finds it. `where` looks in the system search path given by the `PATH` environment variable, while Python looks in the modules search path given by `sys.path`, which usually does not include the content of `PATH`, see [Where is Python's sys.path initialized from?](https://stackoverflow.com/q/897792/8516269) But on Windows there is a fallback mechanism for registered DLLs (I don't know how it works). Anyway, one should not rely on this fallback as soon as one intends to install and run the application on another system, because the necessary DLL may not be installed there. Thus the necessary dependencies should always be included in the installation directory.
> > set CONDA\_DLL\_SEARCH\_MODIFICATION\_ENABLE=1; > > > will solve all your problems
57,567,892
Previously I asked a similar question: [cx\_Freeze unable fo find mkl: MKL FATAL ERROR: Cannot load mkl\_intel\_thread.dll](https://stackoverflow.com/questions/57493584/cx-freeze-unable-fo-find-mkl-mkl-fatal-error-cannot-load-mkl-intel-thread-dll) But now I have a subtle difference. I want to run the program without installing anaconda, just within a `cmd.exe` terminal, but it seems I am doing something wrong or that it is not possible. After generating my application with `python setup.py bdist_msi` using `cx-freeze`, I am able to install and then run it within an anaconda environment, but if I simply open a `cmd.exe` terminal and run it, I get ``` INTEL MKL ERROR: The specified module could not be found. mkl_intel_thread.dll. Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll. ``` However, when running ``` where mkl_intel_thread.dll ``` the dll is found, so I think this means it's registered in the system (I am more used to use Linux, so may be I am wrong). How could I solve this problem?
2019/08/20
[ "https://Stackoverflow.com/questions/57567892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1612432/" ]
Maybe another DLL necessary for MKL, such as `libiomp5md.dll` for example, is missing and causes the error. See [Cannot load mkl\_intel\_thread.dll on python executable](https://stackoverflow.com/q/54337644/8516269), my answer there and its comments. If this still does not solve your problem, try to manually copy other DLLs from the anaconda environment's library path into the app installation directory and its `lib` subdirectory. Once you have found which dependency is missing, you can use the `include_files` option of cx\_Freeze to automatize this step in the setup (as you know). Another possible issue would be that you have an incompatible version of MKL installed on your system and that the frozen application finds this wrong one, but this is unlikely unless you have a 32-bit Python installation on a 64-bit system or have installed the application on another system. EDIT: It could still also simply be that the frozen application does not find `mkl_intel_thread.dll` although `where` finds it. `where` looks in the system search path given by the `PATH` environment variable, while Python looks in the modules search path given by `sys.path`, which usually does not include the content of `PATH`, see [Where is Python's sys.path initialized from?](https://stackoverflow.com/q/897792/8516269) But on Windows there is a fallback mechanism for registered DLLs (I don't know how it works). Anyway, one should not rely on this fallback as soon as one intends to install and run the application on another system, because the necessary DLL may not be installed there. Thus the necessary dependencies should always be included in the installation directory.
As per <https://stackoverflow.com/a/56186333/977566> I renamed c:\windows\system32\libiomp5md.dll to .bak and that fixed it for me.
57,567,892
Previously I asked a similar question: [cx\_Freeze unable fo find mkl: MKL FATAL ERROR: Cannot load mkl\_intel\_thread.dll](https://stackoverflow.com/questions/57493584/cx-freeze-unable-fo-find-mkl-mkl-fatal-error-cannot-load-mkl-intel-thread-dll) But now I have a subtle difference. I want to run the program without installing anaconda, just within a `cmd.exe` terminal, but it seems I am doing something wrong or that it is not possible. After generating my application with `python setup.py bdist_msi` using `cx-freeze`, I am able to install and then run it within an anaconda environment, but if I simply open a `cmd.exe` terminal and run it, I get ``` INTEL MKL ERROR: The specified module could not be found. mkl_intel_thread.dll. Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll. ``` However, when running ``` where mkl_intel_thread.dll ``` the dll is found, so I think this means it's registered in the system (I am more used to use Linux, so may be I am wrong). How could I solve this problem?
2019/08/20
[ "https://Stackoverflow.com/questions/57567892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1612432/" ]
Maybe another DLL necessary for MKL, such as `libiomp5md.dll` for example, is missing and causes the error. See [Cannot load mkl\_intel\_thread.dll on python executable](https://stackoverflow.com/q/54337644/8516269), my answer there and its comments. If this still does not solve your problem, try to manually copy other DLLs from the anaconda environment's library path into the app installation directory and its `lib` subdirectory. Once you have found which dependency is missing, you can use the `include_files` option of cx\_Freeze to automatize this step in the setup (as you know). Another possible issue would be that you have an incompatible version of MKL installed on your system and that the frozen application finds this wrong one, but this is unlikely unless you have a 32-bit Python installation on a 64-bit system or have installed the application on another system. EDIT: It could still also simply be that the frozen application does not find `mkl_intel_thread.dll` although `where` finds it. `where` looks in the system search path given by the `PATH` environment variable, while Python looks in the modules search path given by `sys.path`, which usually does not include the content of `PATH`, see [Where is Python's sys.path initialized from?](https://stackoverflow.com/q/897792/8516269) But on Windows there is a fallback mechanism for registered DLLs (I don't know how it works). Anyway, one should not rely on this fallback as soon as one intends to install and run the application on another system, because the necessary DLL may not be installed there. Thus the necessary dependencies should always be included in the installation directory.
For this, it is enough to get the full version of visual c++ program and delete anaconda and folders related to anaconda such as `.anaconda` or `.conda` or `.matplotlib` or `AppData/anaconda` and ... and then install it again Of course, don't forget that all Intel services must be active <https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170>
57,567,892
Previously I asked a similar question: [cx\_Freeze unable fo find mkl: MKL FATAL ERROR: Cannot load mkl\_intel\_thread.dll](https://stackoverflow.com/questions/57493584/cx-freeze-unable-fo-find-mkl-mkl-fatal-error-cannot-load-mkl-intel-thread-dll) But now I have a subtle difference. I want to run the program without installing anaconda, just within a `cmd.exe` terminal, but it seems I am doing something wrong or that it is not possible. After generating my application with `python setup.py bdist_msi` using `cx-freeze`, I am able to install and then run it within an anaconda environment, but if I simply open a `cmd.exe` terminal and run it, I get ``` INTEL MKL ERROR: The specified module could not be found. mkl_intel_thread.dll. Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll. ``` However, when running ``` where mkl_intel_thread.dll ``` the dll is found, so I think this means it's registered in the system (I am more used to use Linux, so may be I am wrong). How could I solve this problem?
2019/08/20
[ "https://Stackoverflow.com/questions/57567892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1612432/" ]
Recently I faced the same error in python3.7 . I did not have the option of moving Dll, I Solved the problem by just doing. ``` conda install cython ``` After the cython install all dll's were in proper place.
> > set CONDA\_DLL\_SEARCH\_MODIFICATION\_ENABLE=1; > > > will solve all your problems
57,567,892
Previously I asked a similar question: [cx\_Freeze unable fo find mkl: MKL FATAL ERROR: Cannot load mkl\_intel\_thread.dll](https://stackoverflow.com/questions/57493584/cx-freeze-unable-fo-find-mkl-mkl-fatal-error-cannot-load-mkl-intel-thread-dll) But now I have a subtle difference. I want to run the program without installing anaconda, just within a `cmd.exe` terminal, but it seems I am doing something wrong or that it is not possible. After generating my application with `python setup.py bdist_msi` using `cx-freeze`, I am able to install and then run it within an anaconda environment, but if I simply open a `cmd.exe` terminal and run it, I get ``` INTEL MKL ERROR: The specified module could not be found. mkl_intel_thread.dll. Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll. ``` However, when running ``` where mkl_intel_thread.dll ``` the dll is found, so I think this means it's registered in the system (I am more used to use Linux, so may be I am wrong). How could I solve this problem?
2019/08/20
[ "https://Stackoverflow.com/questions/57567892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1612432/" ]
Recently I faced the same error in python3.7 . I did not have the option of moving Dll, I Solved the problem by just doing. ``` conda install cython ``` After the cython install all dll's were in proper place.
For this, it is enough to get the full version of visual c++ program and delete anaconda and folders related to anaconda such as `.anaconda` or `.conda` or `.matplotlib` or `AppData/anaconda` and ... and then install it again Of course, don't forget that all Intel services must be active <https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170>
57,567,892
Previously I asked a similar question: [cx\_Freeze unable fo find mkl: MKL FATAL ERROR: Cannot load mkl\_intel\_thread.dll](https://stackoverflow.com/questions/57493584/cx-freeze-unable-fo-find-mkl-mkl-fatal-error-cannot-load-mkl-intel-thread-dll) But now I have a subtle difference. I want to run the program without installing anaconda, just within a `cmd.exe` terminal, but it seems I am doing something wrong or that it is not possible. After generating my application with `python setup.py bdist_msi` using `cx-freeze`, I am able to install and then run it within an anaconda environment, but if I simply open a `cmd.exe` terminal and run it, I get ``` INTEL MKL ERROR: The specified module could not be found. mkl_intel_thread.dll. Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll. ``` However, when running ``` where mkl_intel_thread.dll ``` the dll is found, so I think this means it's registered in the system (I am more used to use Linux, so may be I am wrong). How could I solve this problem?
2019/08/20
[ "https://Stackoverflow.com/questions/57567892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1612432/" ]
As per <https://stackoverflow.com/a/56186333/977566> I renamed c:\windows\system32\libiomp5md.dll to .bak and that fixed it for me.
> > set CONDA\_DLL\_SEARCH\_MODIFICATION\_ENABLE=1; > > > will solve all your problems
57,567,892
Previously I asked a similar question: [cx\_Freeze unable fo find mkl: MKL FATAL ERROR: Cannot load mkl\_intel\_thread.dll](https://stackoverflow.com/questions/57493584/cx-freeze-unable-fo-find-mkl-mkl-fatal-error-cannot-load-mkl-intel-thread-dll) But now I have a subtle difference. I want to run the program without installing anaconda, just within a `cmd.exe` terminal, but it seems I am doing something wrong or that it is not possible. After generating my application with `python setup.py bdist_msi` using `cx-freeze`, I am able to install and then run it within an anaconda environment, but if I simply open a `cmd.exe` terminal and run it, I get ``` INTEL MKL ERROR: The specified module could not be found. mkl_intel_thread.dll. Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll. ``` However, when running ``` where mkl_intel_thread.dll ``` the dll is found, so I think this means it's registered in the system (I am more used to use Linux, so may be I am wrong). How could I solve this problem?
2019/08/20
[ "https://Stackoverflow.com/questions/57567892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1612432/" ]
As per <https://stackoverflow.com/a/56186333/977566> I renamed c:\windows\system32\libiomp5md.dll to .bak and that fixed it for me.
For this, it is enough to get the full version of visual c++ program and delete anaconda and folders related to anaconda such as `.anaconda` or `.conda` or `.matplotlib` or `AppData/anaconda` and ... and then install it again Of course, don't forget that all Intel services must be active <https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170>
62,501,832
I was using following code to download the NSE stock data(indian stocks) : ``` from alpha_vantage.timeseries import TimeSeries ts = TimeSeries(key='my api key',output_format='pandas') data, meta_data = ts.get_daily_adjusted(symbol='VEDL.NS', outputsize='full') data.to_csv('/content/gdrive/My Drive/ColabNotebooks/NSEDATA/VEDL.NS.csv') ``` Now i am getting ``` ValueError Traceback (most recent call last) <ipython-input-11-d1a160a06338> in <module>() 1 i='VEDL' ----> 2 data, meta_data = ts.get_daily_adjusted(symbol='{0}.NS'.format(i), outputsize='full') 3 data.to_csv('/content/gdrive/My Drive/Colab Notebooks/NSEDATA/{0}.csv'.format(i)) 2 frames /usr/local/lib/python3.6/dist-packages/alpha_vantage/alphavantage.py in _handle_api_call(self, url) 333 if not json_response: 334 raise ValueError( --> 335 'Error getting data from the api, no return was given.') 336 elif "Error Message" in json_response: 337 raise ValueError(json_response["Error Message"]) ValueError: Error getting data from the api, no return was given. ``` I have been using above api for 3 months and it has been working since then. Please help me
2020/06/21
[ "https://Stackoverflow.com/questions/62501832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13787047/" ]
there are several ways to do this, and the one I will offer are not the best or the nicest ones, but hope that they will help **1) Simply write all your data to table** You can just insert all your data to the table setting the [ConflictAlgorithm](https://pub.dev/documentation/sqflite_common/latest/sql/ConflictAlgorithm-class.html) to ***replace*** or ***ignore*** ``` db.insert(table, data, conflictAlgorithm: ConflictAlgorithm.replace); ``` This will replace/ignore same entries **2) Query, compare, replace** This is a less 'elegant' solution, you can first query all your data from table ``` db.query(table, columns: availableColumns, where: 'columnToQueryBy = ?', whereArgs: [neededValue]); ``` Then compare to the data you have Then write using `db.insert()` as above I think that in your case the first option suits better, [this](https://flutter.dev/docs/cookbook/persistence/sqlite) example pretty much covers most things that might help you Hope it helps!
WHAT ABOUT Read Data from Sqflite and Show in datatable?
39,067,203
This seems to work fine - ``` %time a = "abc" print(a) CPU times: user 0 ns, sys: 0 ns, total: 0 ns Wall time: 19.1 µs abc ``` This doesn't - ``` def func(): %time b = "abc" print(b) func() CPU times: user 0 ns, sys: 0 ns, total: 0 ns Wall time: 31 µs --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-8-57f7d48952b8> in <module>() 3 print(b) 4 ----> 5 func() <ipython-input-8-57f7d48952b8> in func() 1 def func(): 2 get_ipython().magic(u'time b = "abc"') ----> 3 print(b) 4 5 func() NameError: global name 'b' is not defined ``` Here's a link to a [notebook](https://gist.github.com/jayantj/2ead360ffb326f5e5e78e9e58b8a153e) I'm using python 2.7, haven't tried it with python3 yet. Is this expected behaviour?
2016/08/21
[ "https://Stackoverflow.com/questions/39067203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1500929/" ]
POST data is given in a protected Map getParams () and not the URL: ``` @Override protected Map<String,String> getParams(){ Map<String,String> params = new HashMap<String, String>(); params.put("parametr1","value1"); params.put("parametr2","value2"); params.put("parametr3","value3"); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String,String> params = new HashMap<String, String>(); params.put("Content-Type","application/x-www-form-urlencoded"); return params; } ``` Fix your url and use JsonObjectRequest
You want to parse a array into a boolean, you have to loop through the array like this: ``` JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray= jsonObject.getJSONArray("example"); if (jsonArray.length() != 0) { for (int i = 0; i < jsonArray.length(); i++) { JSONObject jo = jsonArray.getJSONObject(i); boolean isLoginSuccess = Boolean.parseBoolean(jo.getString("exampleString")); } } ```
70,582,851
I'm trying to create a webscraping Flask app that creates a new Webdriver instance for each user session, so that different users can scrape content from different pages. This would be simpler if the `driver.get()` and data collection happened in the same API call, but they can't due to the nature of the scraping I'll be doing. Here's what I have so far: ```python from flask import Flask, session from flask_session import Session app = Flask(__name__) SESSION_TYPE = 'filesystem' app.config.from_object(__name__) Session(app) @app.route('/get_site/<link>', methods=['GET']) def get_site(link): session['driver'] = webdriver.Chrome(options=options) session['driver'].get(link) return 'link opened!' # confirmation message @app.route('/scrape_current_site', methods=['GET']) def scrape_current_site(): return session['driver'].title # collecting arbitrary data from page app.run() ``` This doesn't work, though: `AttributeError: Can't pickle local object '_createenviron.<locals>.encode'` Conceptually a flask session *feels* like it's what I'm looking for (a new, unique object for each session), but I can't figure out how to get it to work.
2022/01/04
[ "https://Stackoverflow.com/questions/70582851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13592179/" ]
I advise you to follow many good techniques when developing a responsive webpage, here I explain to you: * **Replacing in your CSS absolute units such as px for percentages or em**. It is always much better to work with relative measurements rather than absolute ones. From my experience, I always try to work with em, [here](https://www.w3schools.com/TAGS/ref_pxtoemconversion.asp) is a conversion from px to em. * **Using responsive layouts like [flex](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox) or [grid](https://developer.mozilla.org/es/docs/Web/CSS/CSS_Grid_Layout)**. * **Adding metadata related to the viewport in the HTML head tag**. I can see you haven't written it. As we can read in W3Schools viewport is the user's visible area of a web page. It varies with the device so it will be smaller on a mobile phone than on a computer screen. You should include the following element in all your web pages: `<meta name="viewport" content="width=device-width, initial-scale=1.0">` In conclusion, try to avoid absolute positioning because it is not the best option. Try to follow this advice and I am sure your webpage will turn so much better. :D.
This is a common problem I would advise that you read up on what `viewports` are on [w3schools.com](https://www.w3schools.com/css/css_rwd_viewport.asp). A viewport is basically the visible area on a user’s device. As we both know, the visible area of a desktop is different from that of a notebook, tablet, and mobile phone. The HTML, CSS you have displayed on your PC is not responsive to other viewports. The way you can go about this is by writing the HTML and CSS in such a way that it will respond to all devices. You need to use relative and absolute units like `em` and `%`, that way the code you have written will scale with respect to the viewport. Media queries are also very functional. Media queries will help customize for a particular viewport. W3schools.com will give you a great direction on these topics. I hope you enjoy yourself while learning.
70,582,851
I'm trying to create a webscraping Flask app that creates a new Webdriver instance for each user session, so that different users can scrape content from different pages. This would be simpler if the `driver.get()` and data collection happened in the same API call, but they can't due to the nature of the scraping I'll be doing. Here's what I have so far: ```python from flask import Flask, session from flask_session import Session app = Flask(__name__) SESSION_TYPE = 'filesystem' app.config.from_object(__name__) Session(app) @app.route('/get_site/<link>', methods=['GET']) def get_site(link): session['driver'] = webdriver.Chrome(options=options) session['driver'].get(link) return 'link opened!' # confirmation message @app.route('/scrape_current_site', methods=['GET']) def scrape_current_site(): return session['driver'].title # collecting arbitrary data from page app.run() ``` This doesn't work, though: `AttributeError: Can't pickle local object '_createenviron.<locals>.encode'` Conceptually a flask session *feels* like it's what I'm looking for (a new, unique object for each session), but I can't figure out how to get it to work.
2022/01/04
[ "https://Stackoverflow.com/questions/70582851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13592179/" ]
I advise you to follow many good techniques when developing a responsive webpage, here I explain to you: * **Replacing in your CSS absolute units such as px for percentages or em**. It is always much better to work with relative measurements rather than absolute ones. From my experience, I always try to work with em, [here](https://www.w3schools.com/TAGS/ref_pxtoemconversion.asp) is a conversion from px to em. * **Using responsive layouts like [flex](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox) or [grid](https://developer.mozilla.org/es/docs/Web/CSS/CSS_Grid_Layout)**. * **Adding metadata related to the viewport in the HTML head tag**. I can see you haven't written it. As we can read in W3Schools viewport is the user's visible area of a web page. It varies with the device so it will be smaller on a mobile phone than on a computer screen. You should include the following element in all your web pages: `<meta name="viewport" content="width=device-width, initial-scale=1.0">` In conclusion, try to avoid absolute positioning because it is not the best option. Try to follow this advice and I am sure your webpage will turn so much better. :D.
I refactored all your code to be Responsive! with **CSS grid** and **flexbox** not only CSS but also HTML to be `semantic`, easy to read... --- the GitHub repo: <https://github.com/Laaouatni/stackoverflow-my-answers/tree/main/79> --- try to see the @diego answer then copy this :) I hope it will help you **here the fixed complete code:** ```css * { --linkedin-blue: #0e76a8; } body { margin: 0; } .navbar { background-color: black; color: white; } #header { display: flex; align-items: center; justify-content: space-evenly; } #header div { display: flex; gap: 0.5vw; } #header a { color: white; text-decoration: none; } #email-div>div:first-child, #phone-div>div:first-child, #header h1, h3 { color: orange; } .container h3 { display: grid; place-content: center; } .weight { font-weight: bold; } .container { display: grid; background-color: white; margin: 0 5vw; padding: 2rem; } #skills ul, #experience ul, #education ul, #aws-section ul { display: grid; gap: 0.5rem; } .space-between { display: flex; justify-content: space-between; align-items: center; } .vertical-gap { display: grid; gap: 1rem; } .pretty { background-color: var(--linkedin-blue); color: White; padding: 20px; text-align: center; text-decoration: none; display: grid; place-content: center; cursor: pointer; } .bg-orange { background-color: orange; } ``` ```html <!DOCTYPE html> <html dir="ltr" lang="en-US"> <head> <script src="myScript.js"></script> <title> Online Resume </title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <nav class="navbar"> <header id="header"> <!-- 1- phone --> <div id="phone-div"> <div>Phone Number:</div> <div>703-400-5998</div> </div> <!-- 2- main title --> <h1>Noah Harris</h1> <!-- 3- email --> <div id="email-div"> <div>Email:</div> <div><a href="mailto:harrisspeed@gmail.com">harrisspeed@gmail.com</a></div> </div> </header> </nav> <div class="bg-orange"> <div class="container"> <!-- <img src="./Badge.jpg" alt="Badge"> --> <!-- about me --> <div id="aboutme"> <h3>About Me</h3> <p> Hello readers My name is Noah and I am partaking in the Cloud Resume Challenge <a href="https://cloudresumechallenge.dev/instructions/">To learn more about the challenge click here</a>. I have been studying Information Technology since i graduated highschool although I was not sure exactly what field I wanted to get into. I was able to get a IT helpdesk job which help me understand the fundamentals but i knew that i wanted to learn more. I later discovered the cloud and was intrigued by the freedom and creativity that could be expressed in the cloud. I began to get curious and that drove me to get my AWS Solutions Architect Associate. I am now working on more projects so that i can score real world experience and even have some fun with it. </p> </div> <!-- skills --> <section id="skills"> <h3> Skills </h3> <ul> <!-- 1 SOFTWARE--> <li> <div class="weight">Software:</div> <span> Windows 7, 8 and 10; HTML and CSS knowledge. Experience using IDE’s with C++ and Python. Virtualization troubleshooting of virtual machines and VDI’s. </span> </li> <!-- 2 HARDWARE --> <li> <div class="weight">Hardware:</div> <span> Troubleshooting HP printers; general computer builds and repairs; hardware installations and swaps. RAID Arrays, RAM and CPU replacement. Ability to troubleshoot and narrow down problems regarding hardware. </span> </li> <!-- 3 NETWORKING --> <li> <div class="weight">Networking:</div> <span> Networking experience (running cables, troubleshooting connections, activating ports, basic router configuration, switches, Wi-Fi router) Familiar with different cabling types such as CAT 5, CAT6, twisted pairs, fiber optic cables. </span> </li> <!-- 4 SUPPORT --> <li> <div class="weight">Support:</div> <span>Helpdesk: escalation and documentation on ticketing system, customer service support (email, phone, and in person). Assisting 40 customers per day.</span> </li> <!-- 5 CLOUD COMPUTING --> <li> <div class="weight">Cloud Computing:</div> <span>Amazon Web Services, Cloud Architecture, Cloud Infrastructure.</span> </li> </ul> </section> <!-- experience --> <section id="experience"> <h3> Experience </h3> <div class="vertical-gap"> <div class="space-between"> <div class="weight">Navy Federal Credit Union</div> <div class="weight">Service Desk Member</div> </div> <div class="space-between"> <div class="weight">Vienna, VA</div> <div class="weight">Feb 2018 - January 2021</div> </div> </div> <!-- LIST experience --> <ul> <li>Provided customer service to 30 customers a day. Talked to customers who needed technical support for their computers and active directory accounts.</li> <li>Alerted management team when a technical outage in the credit union occurred to ensure that the issue gets patched as efficiently as possible.</li> <li>Worked with colleagues in the event of a technical outage to minimize the call queue and effectively troubleshoot for a solution.</li> </ul> </section> <!-- education --> <section id="education"> <h3>Education</h3> <div class="space-between"> <p class="weight">George Mason University</p> <div class="weight">Fairfax, Va</div> </div> <div class="space-between"> <div class="weight">Information Technology</div> <div class="weight">August 2017 - Present</div> </div> <!-- LIST education --> <ul> <li> Year Up is a leading one-year career development program with 250 corporate partners around the country; the program includes college-level courses, professional training, and a six-month internship. </li> <li> Earned an Associate Degree from Northern Virginia Community in Information Technology with 67 credits. </li> <li> Working towards a bachelor's degree in Information Technology with 120 credits. </li> </ul> </section> <!-- Amazon Web Services --> <section id="aws-section"> <h3> AWS Solutions Architecture</h3> <div class="space-between"> <div class="weight"> Cloud Computing </div> <div class="weight"> April 2021 </div> </div> <!-- LIST Amazon Web Services --> <ul> <li> Understands cloud architecture and how to host a highly available website. Able to write simple bash scripts on EC2 instances. </li> <li> Able to execute best practices on security such as private subnets, firewalls, and security groups. </li> <li> Understanding routing on Route 53 latency-based routing geolocation-based routing etc. </li> <li> able to host a static website on S3. </li> </ul> </section> </div> </div> <footer id="footer"> <a href="https://www.linkedin.com/in/noah-harris-947b38152/" class="pretty">Check me out on Linkedin</a> </footer> </body> </html> ```
70,582,851
I'm trying to create a webscraping Flask app that creates a new Webdriver instance for each user session, so that different users can scrape content from different pages. This would be simpler if the `driver.get()` and data collection happened in the same API call, but they can't due to the nature of the scraping I'll be doing. Here's what I have so far: ```python from flask import Flask, session from flask_session import Session app = Flask(__name__) SESSION_TYPE = 'filesystem' app.config.from_object(__name__) Session(app) @app.route('/get_site/<link>', methods=['GET']) def get_site(link): session['driver'] = webdriver.Chrome(options=options) session['driver'].get(link) return 'link opened!' # confirmation message @app.route('/scrape_current_site', methods=['GET']) def scrape_current_site(): return session['driver'].title # collecting arbitrary data from page app.run() ``` This doesn't work, though: `AttributeError: Can't pickle local object '_createenviron.<locals>.encode'` Conceptually a flask session *feels* like it's what I'm looking for (a new, unique object for each session), but I can't figure out how to get it to work.
2022/01/04
[ "https://Stackoverflow.com/questions/70582851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13592179/" ]
I refactored all your code to be Responsive! with **CSS grid** and **flexbox** not only CSS but also HTML to be `semantic`, easy to read... --- the GitHub repo: <https://github.com/Laaouatni/stackoverflow-my-answers/tree/main/79> --- try to see the @diego answer then copy this :) I hope it will help you **here the fixed complete code:** ```css * { --linkedin-blue: #0e76a8; } body { margin: 0; } .navbar { background-color: black; color: white; } #header { display: flex; align-items: center; justify-content: space-evenly; } #header div { display: flex; gap: 0.5vw; } #header a { color: white; text-decoration: none; } #email-div>div:first-child, #phone-div>div:first-child, #header h1, h3 { color: orange; } .container h3 { display: grid; place-content: center; } .weight { font-weight: bold; } .container { display: grid; background-color: white; margin: 0 5vw; padding: 2rem; } #skills ul, #experience ul, #education ul, #aws-section ul { display: grid; gap: 0.5rem; } .space-between { display: flex; justify-content: space-between; align-items: center; } .vertical-gap { display: grid; gap: 1rem; } .pretty { background-color: var(--linkedin-blue); color: White; padding: 20px; text-align: center; text-decoration: none; display: grid; place-content: center; cursor: pointer; } .bg-orange { background-color: orange; } ``` ```html <!DOCTYPE html> <html dir="ltr" lang="en-US"> <head> <script src="myScript.js"></script> <title> Online Resume </title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <nav class="navbar"> <header id="header"> <!-- 1- phone --> <div id="phone-div"> <div>Phone Number:</div> <div>703-400-5998</div> </div> <!-- 2- main title --> <h1>Noah Harris</h1> <!-- 3- email --> <div id="email-div"> <div>Email:</div> <div><a href="mailto:harrisspeed@gmail.com">harrisspeed@gmail.com</a></div> </div> </header> </nav> <div class="bg-orange"> <div class="container"> <!-- <img src="./Badge.jpg" alt="Badge"> --> <!-- about me --> <div id="aboutme"> <h3>About Me</h3> <p> Hello readers My name is Noah and I am partaking in the Cloud Resume Challenge <a href="https://cloudresumechallenge.dev/instructions/">To learn more about the challenge click here</a>. I have been studying Information Technology since i graduated highschool although I was not sure exactly what field I wanted to get into. I was able to get a IT helpdesk job which help me understand the fundamentals but i knew that i wanted to learn more. I later discovered the cloud and was intrigued by the freedom and creativity that could be expressed in the cloud. I began to get curious and that drove me to get my AWS Solutions Architect Associate. I am now working on more projects so that i can score real world experience and even have some fun with it. </p> </div> <!-- skills --> <section id="skills"> <h3> Skills </h3> <ul> <!-- 1 SOFTWARE--> <li> <div class="weight">Software:</div> <span> Windows 7, 8 and 10; HTML and CSS knowledge. Experience using IDE’s with C++ and Python. Virtualization troubleshooting of virtual machines and VDI’s. </span> </li> <!-- 2 HARDWARE --> <li> <div class="weight">Hardware:</div> <span> Troubleshooting HP printers; general computer builds and repairs; hardware installations and swaps. RAID Arrays, RAM and CPU replacement. Ability to troubleshoot and narrow down problems regarding hardware. </span> </li> <!-- 3 NETWORKING --> <li> <div class="weight">Networking:</div> <span> Networking experience (running cables, troubleshooting connections, activating ports, basic router configuration, switches, Wi-Fi router) Familiar with different cabling types such as CAT 5, CAT6, twisted pairs, fiber optic cables. </span> </li> <!-- 4 SUPPORT --> <li> <div class="weight">Support:</div> <span>Helpdesk: escalation and documentation on ticketing system, customer service support (email, phone, and in person). Assisting 40 customers per day.</span> </li> <!-- 5 CLOUD COMPUTING --> <li> <div class="weight">Cloud Computing:</div> <span>Amazon Web Services, Cloud Architecture, Cloud Infrastructure.</span> </li> </ul> </section> <!-- experience --> <section id="experience"> <h3> Experience </h3> <div class="vertical-gap"> <div class="space-between"> <div class="weight">Navy Federal Credit Union</div> <div class="weight">Service Desk Member</div> </div> <div class="space-between"> <div class="weight">Vienna, VA</div> <div class="weight">Feb 2018 - January 2021</div> </div> </div> <!-- LIST experience --> <ul> <li>Provided customer service to 30 customers a day. Talked to customers who needed technical support for their computers and active directory accounts.</li> <li>Alerted management team when a technical outage in the credit union occurred to ensure that the issue gets patched as efficiently as possible.</li> <li>Worked with colleagues in the event of a technical outage to minimize the call queue and effectively troubleshoot for a solution.</li> </ul> </section> <!-- education --> <section id="education"> <h3>Education</h3> <div class="space-between"> <p class="weight">George Mason University</p> <div class="weight">Fairfax, Va</div> </div> <div class="space-between"> <div class="weight">Information Technology</div> <div class="weight">August 2017 - Present</div> </div> <!-- LIST education --> <ul> <li> Year Up is a leading one-year career development program with 250 corporate partners around the country; the program includes college-level courses, professional training, and a six-month internship. </li> <li> Earned an Associate Degree from Northern Virginia Community in Information Technology with 67 credits. </li> <li> Working towards a bachelor's degree in Information Technology with 120 credits. </li> </ul> </section> <!-- Amazon Web Services --> <section id="aws-section"> <h3> AWS Solutions Architecture</h3> <div class="space-between"> <div class="weight"> Cloud Computing </div> <div class="weight"> April 2021 </div> </div> <!-- LIST Amazon Web Services --> <ul> <li> Understands cloud architecture and how to host a highly available website. Able to write simple bash scripts on EC2 instances. </li> <li> Able to execute best practices on security such as private subnets, firewalls, and security groups. </li> <li> Understanding routing on Route 53 latency-based routing geolocation-based routing etc. </li> <li> able to host a static website on S3. </li> </ul> </section> </div> </div> <footer id="footer"> <a href="https://www.linkedin.com/in/noah-harris-947b38152/" class="pretty">Check me out on Linkedin</a> </footer> </body> </html> ```
This is a common problem I would advise that you read up on what `viewports` are on [w3schools.com](https://www.w3schools.com/css/css_rwd_viewport.asp). A viewport is basically the visible area on a user’s device. As we both know, the visible area of a desktop is different from that of a notebook, tablet, and mobile phone. The HTML, CSS you have displayed on your PC is not responsive to other viewports. The way you can go about this is by writing the HTML and CSS in such a way that it will respond to all devices. You need to use relative and absolute units like `em` and `%`, that way the code you have written will scale with respect to the viewport. Media queries are also very functional. Media queries will help customize for a particular viewport. W3schools.com will give you a great direction on these topics. I hope you enjoy yourself while learning.
15,572,171
The python syntax of `for x in y:` to iterate over a list must somehow remember what element the pointer is at currently right? How would we access that value as I am trying to solve this without resorting to `for index, x in enumerate(y):` The technical reason why I want to do this is that I assume that `enumerate()` costs performance while somehow accessing the 'pointer' which is already existing would not. I see that from the answers however this pointer is quite private and inaccessible however. The functional reason why I wanted to do this is to be able to skip for instance 100 elements if the current element float value is far off from the 'desired' float range. -- Answer -- The way this was solved was as follows (pure schematic example): ``` # foo is assumed to be ordered in this example foo = [1,2,3,4,5,6....,99,100] low = 60 high = 70 z = iter(foo) for x in z: if x < low-10 next(islice(z,10,10),None) if x > high break ```
2013/03/22
[ "https://Stackoverflow.com/questions/15572171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1093485/" ]
You cannot. `for` uses the [Python iteration protocol](http://docs.python.org/2/glossary.html#term-iterator), which for lists means it'll create a *private* iterator object. That object keeps track of the position in the list. Even if you were to create the iterator explicitly with [`iter()`](http://docs.python.org/2/library/functions.html#iter), the current position is *not* a public property on that object: ``` >>> list_iter = iter([]) >>> list_iter <listiterator object at 0x10056a990> >>> dir(list_iter) ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__length_hint__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'next'] ``` The point of the iteration protocol is that it lets you treat any sequence, even one that continues without bounds, in exactly the same way. It is trivial to create a sequence generator that *does not have a position*: ``` def toggle(): while True: yield True yield False ``` That generator will toggle between `True` and `False` values as you iterate over it. There is no position in a sequence there, so there is no point exposing a position either. Just stick to `enumerate()`. All that `enumerate()` has to do is keep a *counter*. It doesn't keep position in the wrapped iterator at all. Incrementing that integer does not cost you much performance or memory. [`enumerate()`](http://docs.python.org/2/library/functions.html#enumerate) is *basically* this, [implemented in C](http://hg.python.org/cpython/file/tip/Objects/enumobject.c#l122): ``` def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 ``` Because it is implemented in C, it'll beat trying to read an attribute on the original iterator any day, which would require more bytecode operations in each iteration.
No, it uses the underlying **iterator**, which is not forced to keep track of a current index. Unless you manually incerement a counter, this is not possible: ``` idx = 0 for x in y: idx+=1 # ... ``` so, just keep with `enumerate()`
15,572,171
The python syntax of `for x in y:` to iterate over a list must somehow remember what element the pointer is at currently right? How would we access that value as I am trying to solve this without resorting to `for index, x in enumerate(y):` The technical reason why I want to do this is that I assume that `enumerate()` costs performance while somehow accessing the 'pointer' which is already existing would not. I see that from the answers however this pointer is quite private and inaccessible however. The functional reason why I wanted to do this is to be able to skip for instance 100 elements if the current element float value is far off from the 'desired' float range. -- Answer -- The way this was solved was as follows (pure schematic example): ``` # foo is assumed to be ordered in this example foo = [1,2,3,4,5,6....,99,100] low = 60 high = 70 z = iter(foo) for x in z: if x < low-10 next(islice(z,10,10),None) if x > high break ```
2013/03/22
[ "https://Stackoverflow.com/questions/15572171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1093485/" ]
You cannot. `for` uses the [Python iteration protocol](http://docs.python.org/2/glossary.html#term-iterator), which for lists means it'll create a *private* iterator object. That object keeps track of the position in the list. Even if you were to create the iterator explicitly with [`iter()`](http://docs.python.org/2/library/functions.html#iter), the current position is *not* a public property on that object: ``` >>> list_iter = iter([]) >>> list_iter <listiterator object at 0x10056a990> >>> dir(list_iter) ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__length_hint__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'next'] ``` The point of the iteration protocol is that it lets you treat any sequence, even one that continues without bounds, in exactly the same way. It is trivial to create a sequence generator that *does not have a position*: ``` def toggle(): while True: yield True yield False ``` That generator will toggle between `True` and `False` values as you iterate over it. There is no position in a sequence there, so there is no point exposing a position either. Just stick to `enumerate()`. All that `enumerate()` has to do is keep a *counter*. It doesn't keep position in the wrapped iterator at all. Incrementing that integer does not cost you much performance or memory. [`enumerate()`](http://docs.python.org/2/library/functions.html#enumerate) is *basically* this, [implemented in C](http://hg.python.org/cpython/file/tip/Objects/enumobject.c#l122): ``` def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 ``` Because it is implemented in C, it'll beat trying to read an attribute on the original iterator any day, which would require more bytecode operations in each iteration.
That 'pointer' value is internal to whatever it is that created the iterator. Remember that is doesn't need to be a list (something that can be indexed), so if you really want the 'index', you will need to resort to using enumerate.
15,572,171
The python syntax of `for x in y:` to iterate over a list must somehow remember what element the pointer is at currently right? How would we access that value as I am trying to solve this without resorting to `for index, x in enumerate(y):` The technical reason why I want to do this is that I assume that `enumerate()` costs performance while somehow accessing the 'pointer' which is already existing would not. I see that from the answers however this pointer is quite private and inaccessible however. The functional reason why I wanted to do this is to be able to skip for instance 100 elements if the current element float value is far off from the 'desired' float range. -- Answer -- The way this was solved was as follows (pure schematic example): ``` # foo is assumed to be ordered in this example foo = [1,2,3,4,5,6....,99,100] low = 60 high = 70 z = iter(foo) for x in z: if x < low-10 next(islice(z,10,10),None) if x > high break ```
2013/03/22
[ "https://Stackoverflow.com/questions/15572171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1093485/" ]
You cannot. `for` uses the [Python iteration protocol](http://docs.python.org/2/glossary.html#term-iterator), which for lists means it'll create a *private* iterator object. That object keeps track of the position in the list. Even if you were to create the iterator explicitly with [`iter()`](http://docs.python.org/2/library/functions.html#iter), the current position is *not* a public property on that object: ``` >>> list_iter = iter([]) >>> list_iter <listiterator object at 0x10056a990> >>> dir(list_iter) ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__length_hint__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'next'] ``` The point of the iteration protocol is that it lets you treat any sequence, even one that continues without bounds, in exactly the same way. It is trivial to create a sequence generator that *does not have a position*: ``` def toggle(): while True: yield True yield False ``` That generator will toggle between `True` and `False` values as you iterate over it. There is no position in a sequence there, so there is no point exposing a position either. Just stick to `enumerate()`. All that `enumerate()` has to do is keep a *counter*. It doesn't keep position in the wrapped iterator at all. Incrementing that integer does not cost you much performance or memory. [`enumerate()`](http://docs.python.org/2/library/functions.html#enumerate) is *basically* this, [implemented in C](http://hg.python.org/cpython/file/tip/Objects/enumobject.c#l122): ``` def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 ``` Because it is implemented in C, it'll beat trying to read an attribute on the original iterator any day, which would require more bytecode operations in each iteration.
This information is internal to the iterator and cannot be accessed. See here for a description of the [iterator protocol](http://docs.python.org/2/library/stdtypes.html). Essentially, the only publicly available member of the iterator is `next()` which raises a `StopIteration` exception once the range is exhausted. Besides, `enumerate` is pretty efficient. It is the equivalent of writing ``` i = -1 for x in y: i += 1 # do something with x and i ```
52,729,841
I have only very rudimentary experience in Python. I am trying to install the package `pyslim` (see [here on the pypi website](https://pypi.org/project/pyslim/)). I did ``` $ pip install pyslim Requirement already satisfied: pyslim in ./Library/Python/2.7/lib/python/site-packages/pyslim-0.1-py2.7.egg (0.1) Requirement already satisfied: msprime in /usr/local/lib/python2.7/site-packages (from pyslim) (0.6.1) Requirement already satisfied: attrs in /usr/local/lib/python2.7/site-packages (from pyslim) (16.3.0) Requirement already satisfied: svgwrite in /usr/local/lib/python2.7/site-packages (from msprime->pyslim) (1.1.12) Requirement already satisfied: jsonschema in /usr/local/lib/python2.7/site-packages (from msprime->pyslim) (2.6.0) Requirement already satisfied: six in /usr/local/lib/python2.7/site-packages (from msprime->pyslim) (1.10.0) Requirement already satisfied: numpy>=1.7.0 in /usr/local/lib/python2.7/site-packages/numpy-1.10.4-py2.7-macosx-10.11-x86_64.egg (from msprime->pyslim) (1.10.4) Requirement already satisfied: h5py in /usr/local/lib/python2.7/site-packages (from msprime->pyslim) (2.8.0) Requirement already satisfied: pyparsing>=2.0.1 in /usr/local/lib/python2.7/site-packages (from svgwrite->msprime->pyslim) (2.2.0) Requirement already satisfied: functools32; python_version == "2.7" in /usr/local/lib/python2.7/site-packages (from jsonschema->msprime->pyslim) (3.2.3.post2) ``` But when I open python and try to import `pyslim`, it fails ``` > import pyslim Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/remi/Library/Python/2.7/lib/python/site-packages/pyslim-0.1-py2.7.egg/pyslim/__init__.py", line 4, in <module> from pyslim.slim_metadata import * # NOQA File "/Users/remi/Library/Python/2.7/lib/python/site-packages/pyslim-0.1-py2.7.egg/pyslim/slim_metadata.py", line 1, in <module> import attr ImportError: No module named attr ``` So, I did ``` $ pip install attr Requirement already satisfied: attr in /usr/local/lib/python2.7/site-packages (0.3.1) ``` and ``` $ pip install attrs Requirement already satisfied: attrs in /usr/local/lib/python2.7/site-packages (16.3.0) ``` I restarted python and tried to import `pyslim` again but I keep receiving the same error message. I also tried to download and install the files from github by doing ``` $ git clone https://github.com/tskit-dev/pyslim.git $ cd pyslim $ python setup.py install --user ``` as indicated [here on the pypi website](https://pypi.org/project/pyslim/). On this last line of code, I get a long output ending with ``` Download error on https://pypi.python.org/simple/: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) -- Some packages may not be found! No local packages or download links found for attrs error: Could not find suitable distribution for Requirement.parse('attrs') ``` --- I am using `Python 2.7.10` on a `MAC OSX 10.11.6`. Not sure if it matter but I usually install things with homebrew. I am using `pip 18.1 from /usr/local/lib/python2.7/site-packages/pip (python 2.7)`. **Edit** ``` $ which python /usr/bin/python $ which pip /usr/local/bin/pip ```
2018/10/09
[ "https://Stackoverflow.com/questions/52729841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2051137/" ]
Take a look to [this other question](https://stackoverflow.com/questions/49228744/attributeerror-module-attr-has-no-attribute-s) that is related to the `attrs` package. In your case, you have `attr` and `attrs` installed at the same time, and they are incompatible between them, so python is unable to resolve the package name on the import correctly. You should use `attrs` only, so try uninstalling `attr` and try it again: ``` python -m pip uninstall attr ``` If, in the future, you need to have some packages incompatibles between them, take a look about using [virtual environments in Python](https://help.dreamhost.com/hc/en-us/articles/215489338-Installing-and-using-virtualenv-with-Python-2), which are really easy to use and will be very useful to play with packages and packages versions without break anything.
First uninstall pyslim. Use "pip uninstall pyslim". Then try installing again using "conda install -c conda-forge pyslim" Refer <https://anaconda.org/conda-forge/pyslim>
1,075,905
My first attempt at jython is a java/jython project I'm writing in eclipse with pydev. I created a java project and then made it a pydev project by the RightClick project >> pydev >> set as... you get the idea. I then added two source folders, one for java and one for jython, and each source folder has a package. And I set each folder as a buildpath for the project. I guess I'm letting you know all this so hopefully you can tell me wether or not I set the project up correctly. But the real question is: **how do I get my jython code made into a class file so the java code can use it?** The preferred method would be that eclipse/pydev would do this for me automatically, but I can't figure it out. Something mentioned in the jython users guide implies that it's possible but I can't find info on it anywhere. EDIT: I did find some information [here](http://wiki.python.org/jython/JythonMonthly/Articles/September2006/1) and [here](http://www.jython.org/archive/22/jythonc.html#what-is-jythonc), but things are not going too smooth. I've been following the guide in the second link pretty closely but I can't figure out how to get jythonc to make a constructor for my python class.
2009/07/02
[ "https://Stackoverflow.com/questions/1075905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125946/" ]
Jythonc doesn't exist anymore, it has been forked off to another project called [Clamp](http://github.com/groves/clamp/), but with that said... > > ...you can pre-compile > your python scripts to .class files > using: > > > jython [jython home]/Lib/compileall.py > [the directory where you keep your > python code] > > > Source - [*Jython Newsletter, March 2009*](http://wiki.python.org/jython/JythonMonthly/Newsletters/March2009) When I fed it a folder with Python **2.7** code (knowing it would fail in Jython **2.5**) it did output a .class file, even though it doesn't function. Try that with your Jython scripts. If it works, please let us know, because I'll be where you are soon enough. Once you're that far, it isn't hard to convert your command line statement to an External Tool in PyDev that can be called as needed.
Following the "Accessing Jython from Java Without Using jythonc" tutorial it became possible to use the jython modules inside java code. The only tricky point is that the \*.py modules do not get compiled to \*.class files. So it turns out to be exotic scripting inside java. The performance may of course degrade vs jythonc'ed py modules, but as I got from the jython community pages they are not going to support jythonc (and in fact have already dropped it in jython2.5.1). So if you decide to follow non-jythonc approach, the above tutorial is perfect. I had to modify the JythonFactory.java code a bit: ``` String objectDef = "=" + javaClassName + "(your_constructor_params here)"; try { Class JavaInterface = Class.forName(interfaceName); System.out.println("JavaInterface=" + JavaInterface); javaInt = interpreter.get("instance name of a jython class from jython main function").__tojava__(JavaInterface); } catch (ClassNotFoundException ex) { ex.printStackTrace(); // Add logging here } ```
68,654,385
This is my code to read the LDS sensor. LDS sensor is used to estimate the distance from robot to walls. I can print the data(estimate distance) in the terminal but I cant write it in the csv file automatically. I would like to write about 1000 data into csv file by using python code [enter image description here](https://i.stack.imgur.com/FF8d8.png). ``` #! /usr/bin/env python import rospy import csv from sensor_msgs.msg import LaserScan def callback(msg): d = msg.ranges [90] print d rospy.init_node("read") sub = rospy.Subscriber('/scan', LaserScan, callback) rospy.spin() f= open("\\testread.csv", "w") c=csv.writer(f) for x in range(1000): c.writerow(d) f.close() ```
2021/08/04
[ "https://Stackoverflow.com/questions/68654385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16594158/" ]
Outputting a topic formatted as csv is built into `rostopic echo`, the -p flag [rostopic\_echo](http://wiki.ros.org/rostopic#rostopic_echo). You can redirect the terminal output to a file instead of the terminal with `>` So to save `/scan` to csv you could just run the following in a terminal: ``` rostopic echo -p /scan > scan.csv ``` That page also mentions that the -b flag can be used to echo a specific topic from a rosbag. Not sure if you are aware of [rosbag](http://wiki.ros.org/rosbag) which is purpose built for recording ros data. That way you could also record other relevant data at the same time and use other ros tools to analyze your data like [plotjuggler](http://wiki.ros.org/plotjuggler) for example.
In a more classic ROS style, do all your setup in the "main" function, have global variables for either the returned values of callbacks or for initialized parameters, and do the processing for all your received msgs in your callbacks or timers. ```py #! /usr/bin/env python # lds_to_csv_node.py import rospy import csv from sensor_msgs.msg import LaserScan # Global vars csv_writer = None def scan_callback(msg): d = msg.ranges [90] if csv_writer is not None: csv_writer.writerow(d) def main(): rospy.init_node("lds_to_csv_node") sub = rospy.Subscriber('/scan', LaserScan, scan_callback) fh = open("\\testread.csv", "wb") csv_writer = csv.writer(fh) # More constant params rospy.spin() fh.close() csv_writer = None if __name__ == '__main__': main() ```
17,891,704
What does the [None] do in this code? ``` public class Example { //Java public Example (int _input, int _outputs){ //Java scratch = [None] * (_input + _outputs); //Python Code ``` I'm porting a python implementation into Java and need to better understand what this means. Many thanks for your help.
2013/07/26
[ "https://Stackoverflow.com/questions/17891704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2624276/" ]
``` scratch = [None] * (_input + _outputs) ``` This makes a list of length `_input + _outputs`. Each element in this list is a `None` object. This list is assigned to a variable, named `scratch`
``` [value] * number ``` means list of `number` elements, each of them is `value`. So your code means list of `(_input + _outputs)` `None`'s `null` is closest thing to Python's `None` I know.
17,891,704
What does the [None] do in this code? ``` public class Example { //Java public Example (int _input, int _outputs){ //Java scratch = [None] * (_input + _outputs); //Python Code ``` I'm porting a python implementation into Java and need to better understand what this means. Many thanks for your help.
2013/07/26
[ "https://Stackoverflow.com/questions/17891704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2624276/" ]
`[None]` is a list containing one element, the singleton `None`, which is commonly used to represent "no value" in Python. This list is being multiplied by the sum of the number of inputs and outputs. The resulting list will have as many references to `None` as there are inputs and outputs.
``` [value] * number ``` means list of `number` elements, each of them is `value`. So your code means list of `(_input + _outputs)` `None`'s `null` is closest thing to Python's `None` I know.
3,330,280
I'm weaving my c code in python to speed up the loop: ``` from scipy import weave from numpy import * #1) create the array a=zeros((200,300,400),int) for i in range(200): for j in range(300): for k in range(400): a[i,j,k]=i*300*400+j*400+k #2) test on c code to access the array code=""" for(int i=0;i<200;++i){ for(int j=0;j<300;++j){ for(int k=0;k<400;++k){ printf("%ld,",a[i*300*400+j*400+k]); } printf("\\n"); } printf("\\n\\n"); } """ test =weave.inline(code, ['a']) ``` It's working all well, but it is still costly when the array is big. Someone suggested me to use a.strides instead of the nasty "a[i\*300\*400+j\*400+k]" I can't understand the document about .strides. Any ideas Thanks in advance
2010/07/25
[ "https://Stackoverflow.com/questions/3330280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389799/" ]
You could replace the 3 for-loops with ``` grid=np.ogrid[0:200,0:300,0:400] a=grid[0]*300*400+grid[1]*400+grid[2] ``` The following suggests this may result in a ~68x (or better? see below) speedup: ``` % python -mtimeit -s"import test" "test.m1()" 100 loops, best of 3: 17.5 msec per loop % python -mtimeit -s"import test" "test.m2()" 1000 loops, best of 3: 247 usec per loop ``` test.py: ``` import numpy as np n1,n2,n3=20,30,40 def m1(): a=np.zeros((n1,n2,n3),int) for i in range(n1): for j in range(n2): for k in range(n3): a[i,j,k]=i*300*400+j*400+k return a def m2(): grid=np.ogrid[0:n1,0:n2,0:n3] b=grid[0]*300*400+grid[1]*400+grid[2] return b if __name__=='__main__': assert(np.all(m1()==m2())) ``` With n1,n2,n3 = 200,300,400, ``` python -mtimeit -s"import test" "test.m2()" ``` took 182 ms on my machine, and ``` python -mtimeit -s"import test" "test.m1()" ``` has yet to finish.
The problem is that you are printing out 2.4 million numbers to the screen in your C code. This is of course going to take a while because the numbers have to be converted into strings and then printed to the screen. Do you really need to print them all to the screen? What is your end goal here? For a comparison, I tried just setting another array as each of the elements in a. This process took about .05 seconds in weave. I gave up on timing the printing of all elements to the screen after 30 seconds or so.
3,330,280
I'm weaving my c code in python to speed up the loop: ``` from scipy import weave from numpy import * #1) create the array a=zeros((200,300,400),int) for i in range(200): for j in range(300): for k in range(400): a[i,j,k]=i*300*400+j*400+k #2) test on c code to access the array code=""" for(int i=0;i<200;++i){ for(int j=0;j<300;++j){ for(int k=0;k<400;++k){ printf("%ld,",a[i*300*400+j*400+k]); } printf("\\n"); } printf("\\n\\n"); } """ test =weave.inline(code, ['a']) ``` It's working all well, but it is still costly when the array is big. Someone suggested me to use a.strides instead of the nasty "a[i\*300\*400+j\*400+k]" I can't understand the document about .strides. Any ideas Thanks in advance
2010/07/25
[ "https://Stackoverflow.com/questions/3330280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389799/" ]
You could replace the 3 for-loops with ``` grid=np.ogrid[0:200,0:300,0:400] a=grid[0]*300*400+grid[1]*400+grid[2] ``` The following suggests this may result in a ~68x (or better? see below) speedup: ``` % python -mtimeit -s"import test" "test.m1()" 100 loops, best of 3: 17.5 msec per loop % python -mtimeit -s"import test" "test.m2()" 1000 loops, best of 3: 247 usec per loop ``` test.py: ``` import numpy as np n1,n2,n3=20,30,40 def m1(): a=np.zeros((n1,n2,n3),int) for i in range(n1): for j in range(n2): for k in range(n3): a[i,j,k]=i*300*400+j*400+k return a def m2(): grid=np.ogrid[0:n1,0:n2,0:n3] b=grid[0]*300*400+grid[1]*400+grid[2] return b if __name__=='__main__': assert(np.all(m1()==m2())) ``` With n1,n2,n3 = 200,300,400, ``` python -mtimeit -s"import test" "test.m2()" ``` took 182 ms on my machine, and ``` python -mtimeit -s"import test" "test.m1()" ``` has yet to finish.
There is no way to speed up accessing a multidimensional array in C. You have to calculate the array index and you have to dereference it, this is as simple as it gets.