Is it possible to specify name of .rmd file when knitting/rendering in r-markdown? - r-markdown

After knitting to a word doc, I would like to specify the name of the .rmd file when it is saved. For instance I have set the name of the word doc to include date and time so that each word doc version is saved as a different file:
'''{r}
knit: (function(inputFile, encoding) { rmarkdown::render(inputFile, encoding =
encoding, output_file = paste0(substr(inputFile,1,nchar(inputFile)-4),'_',lubridate::today(),'_',paste0(lubridate::hour(lubridate::now()), lubridate::minute(lubridate::now())),'.docx')) })
'''
So in my directory I have the following:
FileName_2019-05-27_1741.docx
FileName.rmd
FileName_2019-05-27_1329.docx
FileName_2019-05-26_1420.docx
I'd like to have the .rmd files automatically saved the same way with date and time in case I want to go back and look at an earlier version of my .rmd file.

The below code worked for me thanks to an earlier tip to copy/rename the file (I was looking for ways to save the file as opposed to copying):
file.copy(from = "FileName.rmd",
to = paste0('FileName_',lubridate::today(),'_',paste0(lubridate::hour(lubridate::now()),
lubridate::minute(lubridate::now())),'.rmd'))
I entered this in a new code chunk as I couldn't figure out how to do it within the header (which is where I had the code to name the word file). It does exactly what I need it to do now!

Related

How to get number of lines of code of a file in a remote repo using PyGithub/ Githubsearch api?

commit = repo.get_commit(sha="0adf369fda5c2d4231881d66e3bc0bd12fb86c9a")
print(commit.stats.total)
i = commit.files[0].filename
I can get the filename, even the file sha; but can't seem to get loc of the file. Any pointers?
So let's see this line
commit = repo.get_commit(sha="0adf369fda5c2d4231881d66e3bc0bd12fb86c9a")
Here the commit is of type github.Commit.Commit
Now when you pick a file, it's of the type github.File.File
If you checked that, you'll see that there is no real way of getting lines of code directly. But there is one important field raw_url.
This will give you the raw_url of the file, which you can now get, perhaps like
url = commit.files[0].raw_url
r = requests.get(url)
r.text
This will give you the raw data of the file and you can use it to get the number of lines of code.

Directing Output Paths of Altered Files

How can I direct the destination of the output file to my db?
My models.py is structured like so:
class Model(models.Model):
char = models.CharField(max_length=50, null=False, blank=False)
file = models.FileField(upload_to=upload_location, null=True, blank=True)
I have the user enter a value for 'char', and then the value of 'char' is printed on to a file. The process of successfully printing onto the file is working, however, the file is outputting to my source directory.
My goal is to have the output file 'pdf01.pdf' output to my db and be represented as 'file' so that the admin can read it.
Much of the information in the Dango docs has been focussed on directing the path of objects imported by the user directly, not on files that have been created internally. I have been reading mostly from these docs:
Models-Fields
Models
File response objects
Outputting PDFs
I have seen it recommend to write to a buffer, not a file, then save the buffer contents to my db however I haven't been able to find many examples of how to do that relevant to my situation online.
Perhaps there is a relevant gap in my knowledge regarding buffers and BytesIO? Here is the function I have been using to alter the pdf, I have been using BytesIO to temporarily store files throughout the process but have not been able to figure out how to use it to direct the output anywhere specific.
can = canvas.Canvas(BytesIO(), pagesize=letter)
can.drawString(10, 10, char)
can.save()
BytesIO().seek(0)
text_pdf = PdfFileReader(BytesIO())
base_file = PdfFileReader(open("media/01.pdf", "rb"))
page = base_file.getPage(0)
page.mergePage(text_pdf.getPage(0))
PdfFileWriter().addPage(page)
PdfFileWriter().write(open("pdf01.pdf", "wb")
FileField does not store files directly in the database. Files get uploaded in a location on the filesystem determined by the upload_to argument. Only some metadata are stored in the DB, including the path of the file in your filesystem.
If you want to have the contents of the files in the database, you could create a new File model that includes a BinaryField to store the data and a CharField to store the URL from which the file can be fetched. To feed the data of PdfFileWriter to the binary field of Django, perhaps the most appropriate would be to use BytesIO.
I found this workaround to direct the file to a desired location (in this case both my media_cdn folder and also output it to an admin.)
I set up an admin action to perform the function that outputs the file so the admin will have access to both the output version in the form of both an HTTP response and through the media_cdn storage.
Hope this helps anyone who struggles with the same problem.
#admin.py
class edit_and_output():
def output:
author = Account.email
#alter file . . .
with open('media_cdn/account/{0}.pdf'.format(author), 'wb') as out_file:
output.write(out_file)
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment;filename="{0}.pdf"'.format(author)
output.write(response)

python matching files from one list with files from another list based on name

I am learning python and programing in general and really need some assistance.
I wrote a python script that reads one file, get unique values, opens a second file and and uses those unique values to makes some calculation(script is too long to upload)
I then created a gui using pyqt4 where I allowed the user to browse by clicking QPushButton and stored the file path in QLineEdit I then set my file in my script as f1 = self.lineedit.text() and f2 = self.lineedit2.text
everything worked perfectly however, I need to allow to user to select multiple files and match every file one with its corresponding file two since they are dependent on each other
Here are the updates I made to the widget functions to accept multiple files:
def first_file_set(self):
dlg = QFileDialog()
files = dlg.getOpenFileNames()
self.listWidget.addItems(list(files))
def second_file_set(self):
dlg = QFileDialog()
filenames = dlg.getOpenFileNames()
self.listWidget_2.addItems(list(filenames))
def clearF(self):
for item in self.listwidget2.selectedItems():
self.listWidget.clear()
def clearS(self):
for item in self.listwidget.selectedItems():
self.listWidget_2.clear()
def Calculate(self):
#code is too long this is how I am reading files
l1 = []
f1 = self.listWidget.item()
with open(f1,'r') as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
l1.append(list(line))
# more code
l2 = []
f2 = self.listWidget_2.item()[0]
with open(f2,'r') as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
l2.append(list(line))
# more code
I still want to use the code I wrote but on multiple files this time.
eg.
open one file from file path in listwidget, grab unique items, find file with same name from its path in listwidget_2 use unique items to perform calculations, repeat for every file in list
If my file one and two will have the same string in their name how do I pull and match them?
Example file one names:
filemap02.csv
filemap03.csv
filemap04.csv
Example file two names:
newmap02.csv
newmap03.csv
newmap04.csv
So I couldn't really test it since you did not post a working example, but something like this should do it:
for item in self.listwidget.selectedItems():
#First file
fn1=str(item.text())
#Get string that needs to match
matchStr=fn1.replace("file","")
#Find matching item in second listwidget
fn2=self.listwidget2.findItems(matchStr,QtCore.Qt.MatchExactly)
# Do your calculations
whateverFunc(fn1,fn2)
Hope that helps.

Remove prefix for upload image in Vtiger

When upload image, vtiger add prefix to filename.
Befor upload: IMG_NAME.png.
After upload: 26540_IMG_NAME.png.
How I can remove '26540_' prefix?
Its not recommended to change the standard of storing files with the name. Because the prefix ('26540_' in your case) is the unique identifier which will add before the filename. And if we upload same file with the same name vTiger treat as a different file.
But still if you dont want to prefix added then customize the code as per below:
Open \data\CRMEntity.php
Search function uploadAndSaveFile(
Comment the line
$upload_status = move_uploaded_file($filetmp_name, $upload_file_path .$current_id . "_" . $binFile);
Add (Removed $current_id)
$upload_status = move_uploaded_file($filetmp_name, $upload_file_path . $binFile);
Save the script and test. Cheers!

Saving xlsx file in rails

I've been trying to generate an XLSX file in my app. I'm using the gem 'acts_as_xlsx'.
The problem is that the document is generated in the background, and I don't want to render a view. It's a script that should return the XLSX file.
I'm trying to do something like:
file = File.open("report.xlsx", relation.to_xlsx, type: "application/vnd.openxmlformates-officedocument.spreadsheetml.sheet")
This returns an error as the second argument of the File.open must be a string.
Thanks in advance!
to_xlsx should return the Axlsx package. The package will save itself to a file:
relation.to_xlsx.serialize("report.xlsx")
However, if you are emailing it, all you need is to place that as the attachment. You don't need to save it as a file:
class UserMailer < ActionMailer::Base
def export(users)
content = User.to_xlsx(data: users).to_stream.string
attachments["Users.xlsx"] = {mime_type: Mime::XLSX, content: content}
...
end
end
Also, you'll notice above, acts_as_xlsx registers Mime::XLSX for you. So you can use that instead of the long mime string.