How to use elm reactor to access files via http request? - elm

elm 0.19
$ mkdir myprj; cd myprj; elm init; elm install elm/http
then create src/test.elm and src/test.txt:
$ tree
.
├── elm.json
└── src
├── test.elm
└── test.txt
$ elm reactor
then navigate to:
http://localhost:8000/src/test.elm
so the browser window shows:
This is a headless program, meaning there is nothing to show here.
I started the program anyway though, and you can access it as `app` in the developer console.
but the browser console shows:
Failed to load resource: the server responded with a status of 404 (Not Found) test.text:1
Why can't elm reactor locate test.txt?
test.txt:
hi
test.elm:
import Http
init () =
( "", Http.send Resp <| Http.getString "test.text" )
type Msg
= Resp (Result Http.Error String)
update msg model =
case msg of
Resp result ->
case result of
Ok body ->
( Debug.log "ok" body, Cmd.none )
Err _ ->
( "err", Cmd.none )
subscriptions model =
Sub.none
main =
Platform.worker
{ init = init
, update = update
, subscriptions = subscriptions
}
Solved
In test.elm, the url "test.txt" was falsely spelled to "test.text".

Your comment has different file extensions. You said you created src/test.txt but you are getting a 404 because you are asking for a .text extension.
Try going to http://localhost:8000/src/test.txt

Related

Dynamically using testdata based on env in karate framework

I have test data based on environments. Need to use respecitive environment test data for webservice testing in karate framework.
So I have config file which load variable based on environment. I have edited my feature file as runtime variable to get the path accordingly something like below. It looks I am missing something or might not using right way.
I have kept testdata based on environment in my folders as like below
TestData
|->DEV
|-> applicationFeature_scenorio1_Req.json
|->SIT
|-> applicationFeature_scenorio1_Req.json
|->UAT
|-> applicationFeature_scenorio1_Req.json
|->PROD
|-> applicationFeature_scenorio1_Req.json
Please help me on this how to pick data based on environment.
Config file
dev: {
baseUrl: 'https://applicationsit.company.com',
TestData : 'TestData/DEV'
},
sit: {
baseUrl: 'https://applicationsit.company.com',
TestData : 'TestData/SIT'
},
uat: {
baseUrl: 'https://applicationuat2.company.com',
TestData : 'TestData/UAT'
},
prod: {
baseUrl: 'https://applicationnewprod.company.com',
TestData : 'TestData/PROD'
}
Feature file
Background:
* def testdata = TestData
      
#smoke #prod
Scenario: This is success scenario
Given url baseUrl
Given path '/cryptoService'
And request read('#(testdata)/applicationFeature_scenorio1_Req.json')
When method POST
Then status 200
* def encryptedPayload = response
Error found in karate
And request read('#(testdata)/applicationFeature_scenorio1_Req.json')
js failed:
>>>>
01: read('#(testdata)/applicationFeature_scenorio1_Req.json')
<<<<
org.graalvm.polyglot.PolyglotException: java.io.FileNotFoundException: /tmp/workspace/application-prod-test/Continous_Testing/KarateConfigDir/#(testdata)/applicationFeature_scenorio1_Req.json (No such file or directory)
- com.intuit.karate.resource.FileResource.getStream(FileResource.java:98)
- com.intuit.karate.core.ScenarioFileReader.readFileAsStream(ScenarioFileReader.java:99)
- com.intuit.karate.core.ScenarioFileReader.readFileAsString(ScenarioFileReader.java:95)
- com.intuit.karate.core.ScenarioFileReader.readFile(ScenarioFileReader.java:53)
- com.intuit.karate.core.ScenarioEngine.lambda$new$0(ScenarioEngine.java:124)
- <js>.:program(Unnamed:1)
The '#(var)' system works only for JSON: https://github.com/karatelabs/karate#rules-for-embedded-expressions
Karate syntax is mostly JS and variables just work normally. With that in mind please make this change:
And request read(testdata + '/applicationFeature_scenorio1_Req.json')

How to add basic auth to Scotty middleware?

I'm currently making a Scotty API and I couldn't find any examples of basicAuth implementations (Wai Middleware HttpAuth).
Specifically, I want to add basic auth headers (user, pass) to SOME of my endpoints (namely, ones that start with "admin"). I have everything set up, but I can't seem to make the differentiation as to which endpoints require auth and which ones don't. I know I need to use something like this, but it uses Yesod, and I wasn't able to translate it to Scotty.
So far, I have this:
routes :: (App r m) => ScottyT LText m ()
routes = do
-- middlewares
middleware $ cors $ const $ Just simpleCorsResourcePolicy
{ corsRequestHeaders = ["Authorization", "Content-Type"]
, corsMethods = "PUT":"DELETE":simpleMethods
}
middleware $ basicAuth
(\u p -> return $ u == "username" && p == "password")
"My Realm"
-- errors
defaultHandler $ \str -> do
status status500
json str
-- feature routes
ItemController.routes
ItemController.adminRoutes
-- health
get "/api/health" $
json True
But it adds authentication to all my requests. I only need it in some of them.
Thank you so much!
You can use the authIsProtected field of the AuthSettings to define a function Request -> IO Bool that determines if a particular (Wai) Request is subject to authorization by basic authentication. In particular, you can inspect the URL path components and make a determination that way.
Unfortunately, this means that the check for authorization is completely separated from the Scotty routing. This works fine in your case but can make fine-grained control of authorization by Scotty route difficult.
Anyway, the AuthSettings are the overloaded "My Realm" string in your source, and according to the documentation, the recommended way of defining the settings is to use the overloaded string to write something like:
authSettings :: AuthSettings
authSettings = "My Realm" { authIsProtected = needsAuth }
That looks pretty horrible, but anyway, the needsAuth function will have signature:
needsAuth :: Request -> IO Bool
so it can inspect the Wai Request and render a decision in IO on whether or not the page needs basic authentication first. Calling pathInfo on the Request gives you a list of path components (no hostname and no query parameters). So, for your needs, the following should work:
needsAuth req = return $ case pathInfo req of
"admin":_ -> True -- all admin pages need authentication
_ -> False -- everything else is public
Note that these are the parsed non-query path components, so /admin and /admin/ and /admin/whatever and even /admin/?q=hello are protected, but obviously /administrator/... is not.
A full example:
{-# LANGUAGE OverloadedStrings #-}
import Web.Scotty
import Network.Wai.Middleware.HttpAuth
import Data.Text () -- needed for "admin" overloaded string in case
import Network.Wai (Request, pathInfo)
authSettings :: AuthSettings
authSettings = "My Realm" { authIsProtected = needsAuth }
needsAuth :: Request -> IO Bool
needsAuth req = return $ case pathInfo req of
"admin":_ -> True -- all admin pages need authentication
_ -> False -- everything else is public
main = scotty 3000 $ do
middleware $ basicAuth (\u p -> return $ u == "username" && p == "password") authSettings
get "/admin/deletedb" $ do
html "<h1>Password database erased!</h1>"
get "/" $ do
html "<h1>Homepage</h1><p>Please don't <a href=/admin/deletedb>Delete the passwords</a>"

Gitlist Error: Filename, directory name, or volume label syntax is incorrect

I am using gitlist for the first time and am kind of new to it and im still not the best at git. I have been trying to setup gitlist but I get this error:
Oops!The filename, directory name, or volume label syntax is incorrect.
Is there a way to fix this?
My config.ini file:
[git]
; ; client = '/usr/bin/git' ; Your git executable path
default_branch = 'main' ; Default branch when HEAD is detached
; ; repositories[] = '/repos/' ; Path to your repositories
; ; If you wish to add more repositories, just add a new line
; WINDOWS USERS
client = '"C:\Program Files\Git\bin\git.exe"' ; Your git executable path
repositories[] = 'C:\xampp\htdocs\gitlist\repos' ; Path to your repositories
; You can hide repositories from GitList, just copy this for each repository you want to hide or add a regex (including delimiters), eg. hidden[] = '/(.+)\.git/'
; hidden[] = '/home/git/repositories/BetaTest'
[app]
debug = false
cache = true
theme = "default"
title = "html title"
[clone_button]
; ssh remote
show_ssh_remote = false ; display remote URL for SSH
ssh_host = '' ; host to use for cloning via HTTP (default: none => uses gitlist web host)
ssh_url_subdir = '' ; if cloning via SSH is triggered using special dir (e.g. ssh://example.com/git/repo.git)
; has to end with trailing slash
ssh_port = '' ; port to use for cloning via SSH (default: 22 => standard ssh port)
ssh_user = 'git' ; user to use for cloning via SSH
ssh_user_dynamic = false ; when enabled, ssh_user is set to $_SERVER['PHP_AUTH_USER']
; http remote
show_http_remote = false ; display remote URL for HTTP
http_host = '' ; host to use for cloning via HTTP (default: none => uses gitlist web host)
use_https = true ; generate URL with https://
http_url_subdir = 'git/' ; if cloning via HTTP is triggered using virtual dir (e.g. https://example.com/git/repo.git)
; has to end with trailing slash
http_user = '' ; user to use for cloning via HTTP (default: none)
http_user_dynamic = false ; when enabled, http_user is set to $_SERVER['PHP_AUTH_USER']
; If you need to specify custom filetypes for certain extensions, do this here
[filetypes]
; extension = type
; dist = xml
; If you need to set file types as binary or not, do this here
[binary_filetypes]
; extension = true
; svh = false
; map = true
; set the timezone
[date]
timezone = UTC
format = 'd/m/Y H:i:s'
; custom avatar service
[avatar]
;url = '//gravatar.com/avatar/'
;query[] = 'd=identicon'
This is the folder structure:
├── gitlist/
| ├── the other stuff
│ └── repos/
| └── test/
| └── README.md
The repo is called test and it is in the repos/ folder.
I fixed this by taking away the two double quotes in the client variable:
Before:
client = '"C:\Program Files\Git\bin\git.exe"' ; Your git executable path
After:
client = 'C:\Program Files\Git\bin\git.exe' ; Your git executable path

Error parsing triggers: Cannot find module 'firebase/firestore'

I am trying to run a very basic code on google api using firebase.
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
//const {Card, Suggestion} = require('dialogflow-fulfillment');
var admin = require('firebase-admin');
require("firebase/firestore");
admin.initializeApp(functions.config().firebase);
//var firestore = admin.firestore();
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
//firestore arguments defined
/* var addRef = firestore.collection('Admissions');
var feeRef = firestore.collection('Fees');
*/
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
console.log("request.body.queryResult.parameters: ", request.body.queryResult.parameters);
// Run the proper function handler based on the matched Dialogflow intent name
var intentMap = new Map();
});
It gives me a error that says
'Error parsing triggers: Cannot find module 'firebase/firestore'.Try running "npm install" in your functions directory before deploying.
When I run npm install inside the funtions directory, I get:
audited 9161 packages in 25.878s found 292 vulnerabilities (21 low,
207 moderate, 64 high) run npm audit fix to fix them, or npm
audit for details
Its been a week, I am stuck with these errors, these errors keep fluctuating based on the solution i find. But i am not able to overcome this error. Can you please check if there is something wrong I am doing, or anything else I need to try?
Just delete the node_modules folder and run npm install again. I was also stuck on this for a week. It is a corrupt file issue.

Unable to load SWF from application storage directory

While publishing my AIR application(CurrentFile), I have also included chatFile.swf with the installation files.
In my AIR settings panel [AIR 3.7 for Desktop], under 'Include Files' I have the following:
CurrentFile.swf
CurrentFile-app.xml
chatFile.swf
Here is the AS3 code in my CurrentFile.swf:
import flash.net.URLRequest;
import flash.events.Event;
import flash.display.Loader;
import flash.filesystem.File;
var chatLoaderWindow:Loader;
function loadchat(m:MouseEvent):void
{
chatLoaderWindow = new Loader();
chatLoaderWindow.contentLoaderInfo.addEventListener(Event.COMPLETE, chatLoadComplete);
chatLoaderWindow.contentLoaderInfo.addEventListener(Event.INIT, chatInitLoad);
chatLoaderWindow.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, chatErrorLoad);
chatLoaderWindow.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, chatHttpStatus);
myclip.chatwindow.addChild(chatLoaderWindow);
var f:File = File.applicationStorageDirectory.resolvePath("chatFile.swf");
chatLoaderWindow.load(new URLRequest(f.url));
tracebox.text = "Chat URL" + f.url;
}
function chatLoadComplete(e:Event):void
{
tracebox.text = "chat loaded";
}
function chatErrorLoad(io:IOErrorEvent):void
{
tracebox.text = "chat IO Error: "+io;
}
function chatInitLoad(i:Event):void
{
tracebox.text = "chat INIT";
}
function chatHttpStatus(e:HTTPStatusEvent):void
{
tracebox.text = "chat Http"+e;
}
myclip.chatbut.addEventListener(MouseEvent.CLICK,loadchat);
/*
Output:
chat IO Error: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2035" errorID=2035]
EDIT: I figured it out. It was really simple
This is not required:
var f:File = File.applicationStorageDirectory.resolvePath("chatFile.swf");
chatLoaderWindow.load(new URLRequest(f.url));
Insert this:
chatLoaderWindow.load(new URLRequest("app:/chatFile.swf"));
So now my question is:
What is the purpose of File.applicationStorageDirectory.resolvePath?
There are two directories here. One is the "application" directory, where your install files are placed. One is the "application-storage" directory, which is a convenient place to write files to at runtime. To access these directories you can either use the File.resolvePath() function or use the URI-scheme shortcuts, app: or app-storage:. In your initial attempt, you were just looking in the wrong directory for your file.
File.applicationStorageDirectory.resolvePath("somefile.swf").url will equal "app-storage:/somefile.swf"
File.applicationDirectory.resolvePath("somefile.swf").url will equal "app:/somefile.swf"
The application directory is where your app was installed. The app storage directory is a folder your app can save files to.
resolvePath() returns a file object. You can use it for purposes other than getting the cross-platform url for the file location, such as fileObj.exists and fileObj.parent.createDirectory(). fileObj.url is just the url you would use with URLLoader to access the file in a platform-independent manner.