Show a message, if file is not existing in the working directory in Shiny - message

I am new to R as well as to Shiny.
I would like to display a message "File not existing" , in shiny main panel, if a.csv file is not there in the working directory. Please suggest a solution.

You could do something like this:
library(shiny)
server <- shinyServer(function(input, output, session) {
# Listens for click from element with ID=chck_file
observeEvent(input$chck_file,{
# Check if file exists
if ( file.exists( isolate({input$fname}) ) ){
# Display text
output$text <- renderText({ paste("File exists in: ",getwd(),sep="") })
}
else{
output$text <- renderText({ paste("No such file in: ",getwd(),sep="") })
}
})
# Listens for click from element with ID=create_file
observeEvent(input$create_file,{
# Create file
file.create(isolate({input$fname}))
})
})
ui <- shinyUI(fluidPage(
textInput("fname","File name: ",value="myfile.txt"),
verbatimTextOutput("text"),
actionButton("chck_file", "Check for file"),
actionButton("create_file", "Create file")
))
shinyApp(ui = ui, server = server)

Related

How to capture and display a picture with camera in Jetpack Compose

This seems to be so easy that I feel embarrassed to ask. However, I have been fighting it for hours and scratching my head.
The goal is to simply launch camera, if the button is pressed and camera permission has been granted, and then take a picture and display it in an Image composable with Coil. Each time I try this, the ActivityResultContract fails to save the image. I think something with the given URI is messy, but it's beyond my magical powers to solve it.
Long story short, here's my code. Hope someone has an idea of how to remedy this issue!
#Composable
fun MyPicker() {
val context = LocalContext.current
val permissionLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.RequestPermission().apply{
}){
}
val imgUri by remember{mutableStateOf("${context.filesDir}/temp.jpg".toUri())}
val captureLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.TakePicture()){
Toast.makeText(context, "Image capture: ${if(it) "Successful" else "Failed"}", Toast.LENGTH_SHORT)
.show()
}
Column {
Button(onClick = {
if(ContextCompat.checkSelfPermission(context, android.Manifest.permission.CAMERA) != PERMISSION_GRANTED)
permissionLauncher.launch(android.Manifest.permission.CAMERA)
else captureLauncher.launch(imgUri)
}) {
Text("Load")
}
Image(painter = rememberAsyncImagePainter(imgUri), null)
}
}
The error says different things for each Uri I provide. For example, for the above uri, it says the following:
E exception while saving result to URI: Optional.of(/data/user/0/com.mycompany.activityops/files/temp.jpg)
java.io.FileNotFoundException: No content provider: /data/user/0/com.mycompany.activityops/files/temp.jpg
And then I tried to, also, provide a Uri.fromFile("${context.filesDir}/temp.jpg"), which was also frowned upon by Android throwing a huge FileUriExposedException, and then I'm clueless, with my head wandering around storage, content resolvers, Uris, etc.
In a util file create a function which returns a temporary file
fun createImageFile(context: Context): File {
// Create an image file name
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${timeStamp}_", //prefix
".jpg", //suffix
storageDir //directory
)
}
Further get uri for the file
val file = Utils.createImageFile(context = context)
val imageUri = FileProvider.getUriForFile(
context,
"application_authority",
file
)
NOTE:
The path of the image will be
val path = file.absolutePath
When starting a result contract you need to send uri
val cameraLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.TakePicture(),
onResult = {isSuccess: Boolean ->
// Handle Result
}
cameraLauncher.launch(uri)
On getting a success call back, you can get the image inside file by
File(path) // Where **path** is defined above.

How do i filter the processed files by a front-matter variable (Eleventy / 11ty)?

Actually, i want to prevent all content files (in our case markdown files) with a version set to draft to be processed by eleventy (so not rendered / copied to the output directory).
Taking an example from this blog post (https://rusingh.com/2020/05/14/eleventy-exclude-draft-collection-items-programmatically/), you can use a directory data file that examines the front matter and when drafts === 'version', returns false for permalink. This worked for me:
module.exports = {
eleventyComputed: {
permalink: (data) => {
if(data.version && data.version === 'draft') return false;
return;
}
}
}

Manually create new log file with CocoaLumberjack

I have configure CocoaLumberjack like this:
// CocoaLumberjack
DDLog.add(DDASLLogger.sharedInstance, with: DDLogLevel.debug)
DDLog.add(DDTTYLogger.sharedInstance, with: DDLogLevel.debug)
DDTTYLogger.sharedInstance.colorsEnabled = true
fileLogger = DDFileLogger.init()
fileLogger?.doNotReuseLogFiles = true // Always create a new log file when apps starts
fileLogger?.rollingFrequency = 86400 // 24 Hours
fileLogger?.maximumFileSize = 0 // Force log to only roll after 24 hours
fileLogger?.logFileManager.maximumNumberOfLogFiles = 1 // Keeps 1 log file plus active log file
DDLog.add(fileLogger!, with: DDLogLevel.debug)
In my app, I'll want to have the following log system:
The entry point to my app is a Login View Controller. I want to write log entries here so I can see if everything goes okey. If the user login correctly, I want to roll/archive that log and create a new one for that user. In this new log, I'll keep errors that occurs during user session. If users logout, I want to again roll/archive the log and create a new one. Before rolling/archiving the log I always send it to my server, so I can delete it from the device.
I'm trying the following to roll/archive the log but I'm not succecing:
Server().sendUserLog(filePath: DDFileLogger().currentLogFileInfo.filePath, onSuccess: { // This function send the log to the server, if all goes good, I want to roll it.
print(">>>>>>>>>>>>>>>>>>>>> \(DDFileLogger().currentLogFileInfo.filePath)")
DDFileLogger().rollLogFile(withCompletion: {
print("Log rolled")
print(">>>>>>>>>>>>>>>>>>>>> \(DDFileLogger().currentLogFileInfo.filePath)")
})
}, onError: { (error) in
DDLogError("LoginVC - sendUserLog Error: \(error)")
})
Both print, before roll function and after roll function, print the same path and file name. So I'm not creating a new log file.
How can I create it?
The problem is you are creating a new DDFileLogger by using DDFileLogger(). You should store your fileLogger somewhere and call rollLogFile on the same instance.
Something like this:
let fileLogger = DDFileLogger()
Server().sendUserLog(
filePath: fileLogger.currentLogFileInfo.filePath,
onSuccess: { // This function send the log to the server, if all goes good, I want to roll it.
print(">>>>>>>>>>>>>>>>>>>>> \(fileLogger.currentLogFileInfo.filePath)")
fileLogger.rollLogFile(withCompletion: {
print("Log rolled")
print(">>>>>>>>>>>>>>>>>>>>> \(fileLogger.currentLogFileInfo.filePath)")
})
},
onError: { (error) in
DDLogError("LoginVC - sendUserLog Error: \(error)")
})

How to delete a file saved in a folder via grails?

I am saving a .pdf/.docx file when creating a entry in y grails-app. Now on the click of Delete button I want to remove that entry from DB as well as I also want to delete the .pdf/.docx file from the folder.
Note : I am saving the path of the file in my DB.
Deleting file from physical location is as simple as this -
def file = new File(/C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg/)
file.delete()
String filePath = fileDomainObject.filePath
boolean fileSuccessfullyDeleted = new File(filePath).delete()
if(fileSuccessfullyDeleted ){
fileDomainObject.delete flush:true
}
else{
flash.error = "Error in deletion."
return
}

Twitter analysis Shiny App

I want to create a basic shiny app wherein I can type a keyword in the text input box and when i click submit the output should be a Data table of the recent tweets having the keyword typed in the text input box. I also need to find a way to automatically enable the handshake between my app and twitter using setup_twitter_oauth. I have created the following app.R file
library(shiny)
library(twitteR)
ui <- fluidPage(
titlePanel("Basic Twitter Search App"),
textInput("twitter", "Search Keyword"),
actionButton("click", label = "Search Tweets"),
dataTableOutput("table")
)
server <- function(input, output){
source(file = 'oauth.RData') #file containing the credentials
output$table <- renderDataTable
(
{
observeEvent(input$twitter, {searchTwitter(input$twitter, n=1500)
})
})
}
shinyApp(ui = ui, server = server)
but when I run the code (Run App), the following error occurs :
Error in orig(name = name, shinysession = self) :
unused arguments (name = name, shinysession = self)
Warning: Unhandled error in observer: client error: (400) Bad Request
observeEvent(input$twitter)
Thank You #Jimbo. After many failed experiments, the following code worked:
library(shiny)
ui <- fluidPage(
textInput("handle", "Search Tweets:"),
sliderInput("maxTweets","Number of recent tweets to use for analysis:",min=5,max=1500, value = 5),
downloadButton("download", "Download File"),
dataTableOutput("table")
)
server <- function(input, output) {
library(twitteR)
consumerKey = "My key"
consumerSecret = "My secret"
accessToken = "My token"
accessSecret = "My secret"
my_oauth <- setup_twitter_oauth(consumer_key = consumerKey, consumer_secret = consumerSecret,
access_token = accessToken, access_secret = accessSecret)
output$table <- renderDataTable({
TweetFrame<-function(searchTerm, maxTweets)
{
twtList<-searchTwitter(searchTerm,n=maxTweets)
twtList1<- do.call("rbind",lapply(twtList,as.data.frame))
twtList1$text<-iconv(twtList1$text, 'UTF-8', 'ASCII') #WILL THIS SOLVE THE UTF ENCODING PROBLEM: http://lists.hexdump.org/pipermail/twitter-users-hexdump.org/2013-May/000335.html
return(twtList1)
}
entity1<-reactive({entity1<-TweetFrame(input$handle, input$maxTweets)})
output$table <- renderDataTable({tab<-entity1()[1]})
output$download <- downloadHandler(filename = function() {paste(input$handle, '.csv', sep='')},
content = function(file){
write.csv(entity1(), file)
}
)
})
}
shinyApp(ui = ui, server = server)
Although I still haven't been able to figure out how to automatically enable the user authentication (without user intervention). Any help in this regards will be greatly appreciated.
server <- function(input, output){
source(file = 'oauth.RData') #file containing the credentials
output$table <- renderDataTable({
test <- searchTwitter(input$twitter, n=1500)
return(test)
})
}
This should work as long as searchTwitter returns a df or a matrix

Resources