Change the items of JComboBox depending on File Chosen - swing

I am using Jython to create a GUI. I include a button - Upload which when clicked opens up a FileChooser and depending on the File chosen, I want to create my JComboBox. When the file is changed/ another file is uploaded, the items of JComboBox should also change.
def upload(self,event):
self.chooseFile = JFileChooser()
filter = FileNameExtensionFilter("c files", ["c"])
self.chooseFile.addChoosableFileFilter(filter)
ret = self.chooseFile.showDialog(frame_2, "Choose file")
if ret == JFileChooser.APPROVE_OPTION:
file_name = self.chooseFile.getSelectedFile().getName()
txt4.setText(file_name)
file = self.chooseFile.getSelectedFile()
global file_path
file_path = file.getCanonicalPath()
with open(file_path) as f:
first_line = f.readline()
self.list_columns = first_line.split("\t")
self.source = JComboBox(self.list_columns)
self.target = JComboBox(self.list_columns)
self.source.setBounds(200,240,200,100)
self.target.setBounds(600,240,200,100)
When the above code is made to run, the dropdown for JComboBox does not change, instead, it remains of the previous file. Can anybody help me on how to clear and update the items of JComboBox?

Related

How to get corresponding file in another folder in Octave/MATLAB?

In one of my folders (say Folder01) there are files like "IGN_A.txt", "IGN_B.txt", "IGN_C.txt".........
In another folder (say Folder02) there are files like "sim_IGN_A_M01.txt", "sim_IGN_A_M02.txt", "sim_IGN_A_M03.txt" for the corresponding file "IGN_A.txt" in Folder01.
Similarly, "sim_IGN_B_M01.txt", "sim_IGN_B_M02.txt", "sim_IGN_B_M03.txt" for corresponding file "IGN_B.txt" in Folder01.
How can I get the corresponding files from those Folders.
For example, I want to get "IGN_A.txt" along with "sim_IGN_A_M01.txt", "sim_IGN_A_M02.txt", "sim_IGN_A_M03.txt".
Here. I added my code which can only get "IGN_A.txt" along with "sim_IGN_A.txt".
Folder01 = 'Home/A1';
Folder02 = 'Home/A2';
%Going Throuh all the Folder01 files
Allfiles_Folder01 = dir(fullfile(Folder01, '*IGN*.txt'));
for k = 1:length(Allfiles_Folder01)
fullFileName = fullfile(Folder01, Allfiles_Folder01(k).name);
READ_Folder01=dlmread(fullFileName,'',2,0);
fullFileName_Sim = fullfile(Folder02, strcat('sim_',Allfiles_Folder01(k).name))
READ_Folder02=dlmread(fullFileName_Sim,'',1,0);
end
If the naming convention is consistent as provided by you, this would be my suggestion:
% Get all filenames from Folder01 in cell array.
Allfiles_Folder01 = dir(fullfile(Folder01, '*IGN*.txt'));
Allfiles_Folder01 = {Allfiles_Folder01.name}
% Iterate all filenames from Folder01.
for k = 1:numel(Allfiles_Folder01)
% Cut file extension from current filename.
filename = Allfiles_Folder01{k};
filename = filename(1:end-4);
% Get all filenames from Folder02 with specific search string in cell array.
Allfiles_Folder02 = dir(fullfile(Folder02, strcat('*', filename, '*.txt')));
Allfiles_Folder02 = {Allfiles_Folder02.name}
% Do stuff with filenames from Folder02 corresponding to filename from Folder01.
% ...
% ...
end

Samba Audit no filename appear

I'm using samba to provide shares to users. The sometimes claim their files have mysteriously disappeared so I am keen to track deletions.
Thus I set up full audit. Everything works, except the audit log is often missing the file name or has some sort of mystery code. For example;
Dec 12 17:46:04 server1 smbd_audit:
shared|shared|192.168.x.x|matt1|shared|2016/12/12
17:46:04|server1|file_id_create|ok|802:28200da:0
The last item should presumably be a file name. Why is there a number instead?
The relevant parts of smb.conf follows
[homes]
comment = Home Directories directory mask = 0775
browseable = yes
read only = no
create mask = 0775
directory mask = 0775
valid users = %S
writable = yes
vfs objects = recycle
recycle:repository = .RecycleBin
recycle:keeptree = yes
recycle:exclude = *.tmp, *.bak
vfs objects = full_audit
full_audit:prefix = %u|%U|%I|%m|%S|%T|%D
full_audit:success = mkdir rename unlink rmdir open
full_audit:failure = none
full_audit:facility = LOCAL5
full_audit:priority = NOTICE

Image uploads with Pyramid and SQLAlchemy

How one should do image file uploads with Pyramid, SQLAlchemy and deform? Preferably so that one can easily get image thumbnail tags in the templates. What configuration is needed (store images on the file system backend, so on).
This question is by no means specifically asking one thing. Here however is a view which defines a form upload with deform, tests the input for a valid image file, saves a record to a database, and then even uploads it to amazon S3. This example is shown under the links to the various documentation I have referenced.
To upload a file with deform see the documentation.
If you want to learn how to save image files to disk, see this article see the official documentation
Then if you want to learn how to save new items with SQLAlchemy see the SQLAlchemy tutorial.
If you want to ask a better question where a more precise detailed answer can be given for each section, then please do so.
#view_config(route_name='add_portfolio_item',
renderer='templates/user_settings/deform.jinja2',
permission='view')
def add_portfolio_item(request):
user = request.user
# define store for uploaded files
class Store(dict):
def preview_url(self, name):
return ""
store = Store()
# create a form schema
class PortfolioSchema(colander.MappingSchema):
description = colander.SchemaNode(colander.String(),
validator = Length(max=300),
widget = text_area,
title = "Description, tell us a few short words desribing your picture")
upload = colander.SchemaNode(
deform.FileData(),
widget=widget.FileUploadWidget(store))
schema = PortfolioSchema()
myform = Form(schema, buttons=('submit',), action=request.url)
# if form has been submitted
if 'submit' in request.POST:
controls = request.POST.items()
try:
appstruct = myform.validate(controls)
except ValidationFailure, e:
return {'form':e.render(), 'values': False}
# Data is valid as far as colander goes
f = appstruct['upload']
upload_filename = f['filename']
extension = os.path.splitext(upload_filename)[1]
image_file = f['fp']
# Now we test for a valid image upload
image_test = imghdr.what(image_file)
if image_test == None:
error_message = "I'm sorry, the image file seems to be invalid is invalid"
return {'form':myform.render(), 'values': False, 'error_message':error_message,
'user':user}
# generate date and random timestamp
pub_date = datetime.datetime.now()
random_n = str(time.time())
filename = random_n + '-' + user.user_name + extension
upload_dir = tmp_dir
output_file = open(os.path.join(upload_dir, filename), 'wb')
image_file.seek(0)
while 1:
data = image_file.read(2<<16)
if not data:
break
output_file.write(data)
output_file.close()
# we need to create a thumbnail for the users profile pic
basewidth = 530
max_height = 200
# open the image we just saved
root_location = open(os.path.join(upload_dir, filename), 'r')
image = pilImage.open(root_location)
if image.size[0] > basewidth:
# if image width greater than 670px
# we need to recduce its size
wpercent = (basewidth/float(image.size[0]))
hsize = int((float(image.size[1])*float(wpercent)))
portfolio_pic = image.resize((basewidth,hsize), pilImage.ANTIALIAS)
else:
# else the image can stay the same size as it is
# assign portfolio_pic var to the image
portfolio_pic = image
portfolio_pics_dir = os.path.join(upload_dir, 'work')
quality_val = 90
output_file = open(os.path.join(portfolio_pics_dir, filename), 'wb')
portfolio_pic.save(output_file, quality=quality_val)
profile_full_loc = portfolio_pics_dir + '/' + filename
# S3 stuff
new_key = user.user_name + '/portfolio_pics/' + filename
key = bucket.new_key(new_key)
key.set_contents_from_filename(profile_full_loc)
key.set_acl('public-read')
public_url = key.generate_url(0, query_auth=False, force_http=True)
output_dir = os.path.join(upload_dir)
output_file = output_dir + '/' + filename
os.remove(output_file)
os.remove(profile_full_loc)
new_image = Image(s3_key=new_key, public_url=public_url,
pub_date=pub_date, bucket=bucket_name, uid=user.id,
description=appstruct['description'])
DBSession.add(new_image)
# add the new entry to the association table.
user.portfolio.append(new_image)
return HTTPFound(location = route_url('list_portfolio', request))
return dict(user=user, form=myform.render())

F#: DataContractJsonSerializer.WriteObject method

I am new to programming and F# is my first language.
Here are the relevant parts of my code:
let internal saveJsonToFile<'t> (someObject:'t) (filePath: string) =
use fileStream = new FileStream(filePath, FileMode.OpenOrCreate)
(new DataContractJsonSerializer(typeof<'t>)).WriteObject(fileStream, someObject)
let dummyFighter1 = { id = 1; name = "Dummy1"; location = "Here"; nationality = "Somalia"; heightInMeters = 2.0; weightInKgs = 220.0; weightClass = "Too fat"}
let dummyFighter2 = { id = 2; name = "Dummy2"; location = "There"; nationality = "Afghanistan"; heightInMeters = 1.8; weightInKgs = 80.0; weightClass = "Just Nice"}
let filePath = #"G:\User\Fighters.json"
saveJsonToFile dummyFighter1 filePath
saveJsonToFile dummyFighter2 filePath
When I run "saveJsonToFile dummyFighter1 filePath", the information is successfully saved. My problem is this: Once I run "saveJsonToFile dummyFighter2 filePath", it immediately replaces all the contents that are already in the file, i.e., all the information about dummyFighter1.
What changes should I make so that information about dummyFighter2 is appended to the file, instead of replacing information about dummyFighter1?
Change the way you open a file setting FileMode.OpenOrCreate to FileMode.Append. Append means "create or append" :
use fileStream = new FileStream(filePath, FileMode.Append)
From MSDN (https://msdn.microsoft.com/fr-fr/library/system.io.filemode%28v=vs.110%29.aspx) :
FileMode.Append opens the file if it exists and seeks to the end of the file, or
creates a new file. This requires FileIOPermissionAccess.Append
permission. FileMode.Append can be used only in conjunction with
FileAccess.Write. Trying to seek to a position before the end of the
file throws an IOException exception, and any attempt to read fails
and throws a NotSupportedException exception.

Unable to delete file through function in Scilab

I have written the following code to plot a graph with the data present in the 'datafile'. After the graph has been plotted, I want to delete the file.
function plot_torque(datafile)
//This will call a datafile and plot the graph of net_torque vs. time
verbose = 1;
// Columns to plot
x_col = 1;
y_col = 2;
// open the datafile
file1 = file('open', datafile,'old');
data1 = read(file1, -1, 4);
time = data1(:,x_col);
torque = data1(:,y_col);
plot(time, torque, '.-b');
xtitle("Torque Generated vs. Time" ,"Time(s)" , "Torque Generated(Nm/m)");
file('close',file());
//%________________%
endfunction
In the place that I have marked as //%________% I have tried
deletefile(datafile);
and
mdelete(datafile);
None of them have worked.
And I have set the working directory to where the above '.sci' file is present and the 'datafile' is present. I am using scilab-5.4.1.
You probably leave (left) the file open. Try this:
fil="d:\Attila\PROJECTS\Scilab\Stackoverflow\file_to_delete.txt"; //change it!
fprintfMat(fil,rand(3,3),"%.2g"); //fill with some data
fd=mopen(fil,"r"); //open
//do something with the file
mclose(fd); //close
//if you neglect (comment out) this previous line, the file remains open,
//and scilab can not delete it!
//If you made this "mistake", first you should close it by executing:
// mclose("all");
//otherwise the file remains open until you close (and restart) Scilab!
mdelete(fil); //this works for me