I have to prepare a GUI , where the Perl/Tk should invoke a batch command (a local one with path hardcoded) and passing argument (which is the .csv file selected by the user) -When user presses the GENERATE button-here simplified as just opening the .csv file in notepad . Can someone help me ?
use Tk;
my $my_MW=MainWindow->new();
$my_MW->title("Sample application");
$my_MW->geometry("350x180-500+500");
$my_MW->resizable( 'no', 'no' );
my $my_Button=$my_MW->Button(-text=>"Select CSV Input File",-command=> \&get_file);
$my_Button->pack(-side=>"top",-expand=>1,-anchor=>"w",-padx => 20,-pady => 20);
my $filepath=" .... ";
my $my_Entry=$my_MW->Entry(-textvariable=> \$filepath);
$my_Entry->pack(-side=>"top",-expand=>1,-anchor=>"w",-padx => 20,-pady => 0,-fill=>"x");
my $my_Button1=$my_MW->Button(-text=>"GENERATE",-width => 12,-command=>sub{\&gen_rslt()});
$my_Button1->pack(-side=>"left",-expand=>1,,-pady => 20);
$my_Button1->configure(-state => 'disabled');
my $my_Button2=$my_MW->Button(-text=>"RESET",-width => 12,-command=>sub{\&clear_field()});
$my_Button2->pack(-side=>"left",-expand=>1,,-pady => 20);
my $my_Button3=$my_MW->Button(-text=>"EXIT",-width => 12,-command=>sub{exit()});
$my_Button3->pack(-side=>"left",-expand=>1,,-pady => 20);
MainLoop();
sub gen_rslt{
#Call the batch file and pass the file path as an argument!
#batch file to open the file in notepad
}
sub clear_field{
$my_Entry->delete(0,'end');
$my_Entry->insert(0," .... ");
$my_Button1->configure(-state => 'disabled');
}
sub get_file
{
$my_Entry->delete(0,'end');
my #types =
(["comma seperated files", [qw/.csv/]],
["All files", '*'],
);
$filepath = $my_MW->getOpenFile(-filetypes => \#types) or return();
$my_Button1->configure(-state => 'normal');
}
using system command you can open the file.
example is
system("notepad.exe myfile.txt");
or also you can use as follows
system(notepad.exe, $filepath);
Related
I want to process a text file locally and the output I want to save in a file as log/text. This is my code but this does not work.
input {
file {
path => "C:/Users/USERNAME/Documents/Projects/test_data.txt"
start_position => beginning
}
}
filter {
}
output {
stdout { codec => rubydebug }
file {
path => "C:/Users/USERNAME/Documents/Projects/out.log"
}
}
In the terminal I have noticed
incedb_path set, generating one based on the "path" setting
{:sincedb_path=>"C:/Users/..
I made an encryption tool for encoding texts and txt files. The tool gets 8 bit binary code of input char then encrypts it with other functions for ex:
a.txt file has:
xxyz
reader = fs.createReadStream('./a.txt', {
flag: 'r',
encoding: 'UTF-8',
highWaterMark: 1
})
reader.on('data', function (chunk) {
console.log( chunk + " --> " + toBin(chunk) )
//writer.write( toStr(reverse(toBin(chunk))) );
});
////////////// TRANSLATORS //////////////
function toBin(text)
return (
Array
.from(text)
.reduce((acc, char) => acc.concat(char.charCodeAt().toString(2)), [])
.map(bin => '0'.repeat(8 - bin.length) + bin )
.join('')
);
}
function toStr(bin) {
return String.fromCharCode(parseInt(bin, 2))
}
OUTPUT:
x --> 01111000
x --> 01111000
y --> 01111001
z --> 01111010
--> 00001010
The last one is EOL, I think.
To encrypt this I basically use my functions like:
function swap(bin) {
return bin.slice(4, 8) + bin.slice(0, 4)
}
function reverse(bin) {
return bin.split("").reverse().join("")
}
Then these functions works well for txt files. I can decrypt and encrypt.
When I try the same way on a png file for ex, there is a problem:
console.log( chunk + " --> " + toStr(toBin(chunk)) )
writer.write( toStr(toBin(chunk)) );
/* OUT
® --> ®
B --> B
` --> `
-->
*/
That looks nice when we look the output, but when we try to open the file it created and not empty it says: "Couldn't load image , unrecognized image file format.
When I try to open image with text editor:
Original png image
Just used string to binary, binary to string, wrote to new file.
As you can see, they are not same. I think I shouldn't read it like reading a text file. So how should I read it?
NOTE: Tried more tobin functions but that's the most true one because some of them were saying range error because of reading a big file than txt files, some of them were giving 7 bit codes, and some of them was giving 000 or undefined sometimes.
Thanks.
I think it is about how you write the image file. I hope this helps.
You need write it as: buffer or binary
// in this states data must be as binary
fs.writeFile("file.png", data, "binary", cb)
// other case you can write with streams
fs.createWriteStream("file.png", {
encoding: "binary"
})
writer.write(chunks);
I have a running manifest, where I create a folder and a file from a setting (exerpt):
define ffnord::mesh(
$mesh_if_id = "low",
$mesh_mtu_low = 1280,
$fastd_low_port = 11280, # fastd port
) {
ffnord::fastd { "fastd_${mesh_code}":
mesh_if_id => $mesh_if_id,
mesh_mtu_low => $mesh_mtu_low,
fastd_low_port => $fastd_low_port,
}
}
and
define ffnord::fastd( $mesh_if_id
, $mesh_code
, $mesh_mtu_low = 1280
, $fastd_low_port
) {
file {
"/etc/fastd/${mesh_code}-mesh-low-vpn/":
ensure =>directory,
require => Package[ffnord::resources::fastd];
"/etc/fastd/${mesh_code}-mesh-low-vpn/fastd.conf":
ensure => file,
notify => Service[ffnord::resources::fastd],
content => template('ffnord/etc/fastd/fastd-low.conf.erb');
}
}
How can I define a variable amount of those configs:
$mesh_if_id = "low",
$mesh_mtu_low = 1280,
$fastd_low_port = 11280, # fastd port
$mesh_if_id = "something",
$mesh_mtu_low = 12345,
$fastd_low_port = 112345, # fastd port
...
and loop through those blocks to create a folder and file inside ffnord/etc/fastd/ for each block automatically?
(I want to solve this problem: https://github.com/ffnord/ffnord-puppet-gateway/pull/116#issuecomment-100619610 )
In Puppet 3.x there is no "looping", but there are a few tricks. You can pass a Hash of data that represents N number of ffnord::fastd instances:
define define ffnord::mesh($fastd_hash) {
create_resources('ffnord::fastd', $fastd_hash)
}
define ffnord::fastd($mesh_code, $fastd_low_port, $mesh_mtu_low = 1280) {
file {
"/etc/fastd/${mesh_code}-mesh-low-vpn/":
ensure =>directory,
require => Package[ffnord::resources::fastd];
"/etc/fastd/${mesh_code}-mesh-low-vpn/fastd.conf":
ensure => file,
notify => Service[ffnord::resources::fastd],
content => template('ffnord/etc/fastd/fastd-low.conf.erb');
}
}
$hash_of_fastds = {
"low_id" => {
mesh_code => 'low,
mesh_mtu_low => 1280,
fastd_low_port => 11280,
},
"some_id" => {
mesh_code => 'something',
mesh_mtu_low => 12345,
fastd_low_port => 112345,
},
}
ffnord::mesh { 'foo': fastd_hash => $hash_of_fastds, }
Note I've modified define ffnord::fastd slightly, where you had a $mesh_if_id parameter I've turned this into the $namevar of ffnord::fastd.
The first level of $hash_of_fastds translates to the names of the ffnord::fastd instances, the second level of the hash are the parameters for each ffnord::fastd.
See the documentation on the create_resources function for more information.
In Puppet 4 you could use the each function to achieve a similar result.
I am trying to send a email with an attached xlsx file using Excel::Writer::XLSX and MIME::Lite. The generation of the excel file works, as i can scp and open the file in Excel without any problems. When i try to open the attachment from my email client (Outlook 2013) i get this error:
"Excel cannot open the file "from_2014-06_to_2014-07.xlsx" because the
file format or file extension is not valid. Verify that the file has
not been corrupted and that the file extension matches the format of
the file."
The file size that outlook displays is 444B but its actually 95K. I have been sending xls files using Spreadsheet::WriteExcel and mime type "application/vnd.ms-excel" without any problems before.
Here is what I have tried to send the email:
sub send_mail{
my $filename = shift;
my $to_email = shift;
my $from_email = shift;
my $date = shift;
$filename = shift;
my $mail = MIME::Lite->new(
'From' => '$from_email',
'To' => $to_email,
'Subject' => "Radio/TV stats $date",
'Type' => 'multipart/mixed',
#'content-type' => 'application/zip',
#'Data' => "Here is your stuff",
);
$mail->attach(
'Type' => 'TEXT',
'Data' => "Here is your stuff",
);
$mail->attach(
#'Type' => 'application/vnd.ms-excel',
'Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Path' => $filepath,
'Filename' => $filename,
'Disposition' => 'attachement',
);
$mail->send('sendmail');
}
Can anyone please help my attach the xlsx file?
You shift twice to $filename (2nd and 6th strings) and variable $filepath is not declared. May be here error?
I am handling file upload field in a form using Drupal 6 form APIs. The file field is marked as required.
I am doing all the right steps in order to save and rename files in proper locations.
upload form
$form = array();
....
$form['image'] = array(
'#type' => 'file',
'#title' => t('Upload photo'),
'#size' => 30,
'#required' => TRUE,
);
$form['#attributes'] = array('enctype' => "multipart/form-data");
...
form validate handler
$image_field = 'image';
if (isset($_FILES['files']) && is_uploaded_file($_FILES['files']['tmp_name'][$image_field])) {
$file = file_save_upload($image_field);
if (!$file) {
form_set_error($image_field, t('Error uploading file'));
return;
}
$files_dir = file_directory_path();
$contest_dir = 'contest';
if(!file_exists($files_dir . '/' . $contest_dir) || !is_dir($files_dir . '/' . $contest_dir))
mkdir($files_dir . '/' . $contest_dir);
//HOW TO PASS $file OBJECT TO SUBMIT HANDLER
$form_state['values'][$image_field] = $file;
file_move($form_state['values'][$image_field], $files_dir."/" . $contest_dir . "/contest-". $values['email']. "-" . $file->filename);
}
else {
form_set_error($image_field, 'Error uploading file.');
return;
}
On submiting form
Form always reports an error Upload photo field is required. although files are getting uploaded. How to deal with this issue?
How to pass file information to submit handler?
your handler is wrong. You never should touch $_FILES or $_POST variables in drupal, instead you should only use the drupal tools. Said that, the implementation you should is like that:
function my_form_handler(&$form,&$form_state){/** VALIDATION FILE * */
$extensions = 'jpeg jpg gif tiff';
$size_limit = file_upload_max_size();
$validators = array(
'my_file_validate_extensions' => array($extensions),
'my_file_validate_size' => array($size_limit),
);
$dest = file_directory_path();
if ($file = file_save_upload('image', $validators, $dest)) {
//at this point your file is uploaded, moved in the files folder and saved in the DB table files
}
}
I think you'll want to use the filefield module and append it to a form, as described in:
Drupal Imagfield/Filefield in custom form
The question has a link to the solution:
http://sysadminsjourney.com/content/2010/01/26/display-cck-filefield-or-imagefield-upload-widget-your-own-custom-form
From the Drupal 6 Form API docs:
"Note: the #required property is not supported (setting it to true will always cause a validation error). Instead, you may want to use your own validation function to do checks on the $_FILES array with #required set to false. You will also have to add your own required asterisk if you would like one."
Old post, but I'm looking for something similar and figured I add that.