Record syntax `parse error on input ‘=’` - haskell

I have a do block in my Yesod tests and I want to be test the response with an expected response.
I attempted to create an expected response in this do block
let expectedUser = User [authorized = true, ident = "AdminUser", displayName = Nothing, id = 1, avatar = Nothing]
On this line I get the error
parse error on input ‘=’
Perhaps you need a 'let' in a 'do' block?
on the = after authorized. How would I rewrite this line so that it would work inside a do block?

The advice you're getting in the compile error is mostly irrelevant, because the parser really has no idea what you're trying to do here. Record syntax uses curly braces { and }, not [ and ]. So it should look like:
let expectedUser = User {authorized = true, ident = "AdminUser", displayName = Nothing, id = 1, avatar = Nothing}
and I would suggest some line breaks :)
let expectedUser = User { authorized = true
, ident = "AdminUser"
, displayName = Nothing
, id = 1
, avatar = Nothing
}

Related

Escaping Dollar Sign Inside Snowflake Javascript Stored Procedure within Terraform

I am trying to incorporate Stored Procedure written in Javascript into Terraform for Snowflake, when I tried to apply script as it was developed I was getting bellow error:
A reference to a resource type must be followed by at least one attribute access, specifying the resource name
Based on the line numbers which raised the error message it does not like the dollar sign, so it seems like it needs to get escaped, example of such un-altered lines are below:
if (rowCount == 0) return `Error: Script with SCRIPT_TYPE = ${SCRIPT_TYPE} and ACCES_TYPE = ${ACCES_TYPE} does not exist.`;
var sql = `select PARAMETER_NAMES, TEMPLATE from administration.utils.SCRIPT_TEMPLATE where SCRIPT_TYPE = ''${SCRIPT_TYPE}'' AND ACCES_TYPE = ''${ACCES_TYPE}''`
What I am after is to know how to escape it and have this logic using the replace function incorporated in procedure resource creation resource "snowflake_procedure" as to be seen below, so that any future changes to the logic or introduction of new procedures does not have to be manually altered, my attempt was to use '\$' for escaping in the function, however not successful:
resource "snowflake_procedure" "GENERATE_SCRIPT_FROM_TEMPLATE" {
name = "GENERATE_SCRIPT_FROM_TEMPLATE"
database = "ADMINISTRATION"
schema = "UTILS"
language = "JAVASCRIPT"
arguments {
SCRIPT_TYPE = "arg1"
type = "VARCHAR(250)"
}
arguments {
ACCES_TYPE = "arg2"
type = "VARCHAR(250)"
}
arguments {
PARAMETER_VALUES = "arg3"
type = "VARCHAR(5000)"
}
return_type = "VARCHAR"
execute_as = "OWNER"
statement = replace(
<<EOT
try
{
var parameterValues = JSON.parse(PARAMETER_VALUES);
}
catch (err) {
return `Failed to parse PARAMETER_VALUES: ${PARAMETER_VALUES}. Correct format is: {"DATABASE": "ADMINISTRATOR", "SCHEMA": "UTILS"}.`;
}
var sql = `select PARAMETER_NAMES, TEMPLATE from administration.utils.SCRIPT_TEMPLATE where SCRIPT_TYPE = ''${SCRIPT_TYPE}'' AND ACCES_TYPE = ''${ACCES_TYPE}''`
var stmt = snowflake.createStatement({ sqlText: sql });
var result = stmt.execute();
var rowCount = result.getRowCount();
if (rowCount == 0) return `Error: Script with SCRIPT_TYPE = ${SCRIPT_TYPE} and ACCES_TYPE = ${ACCES_TYPE} does not exist.`;
result.next();
var parameterNames = result.getColumnValue(1);
var scriptTemplate = result.getColumnValue(2);
var parameterNamesArray = parameterNames.split('','');
parameterNamesArray.forEach(parameterName => {
if (!parameterValues[parameterName]) return `Failed: Cannot find parameter ${parameterName} in PARAMETER_VALUES: ${PARAMETER_VALUES}.`
});
var oldStrimg = '''';
var newString = '''';
var script = scriptTemplate;
parameterNamesArray.forEach(parameterName => {
oldStrimg = `<${parameterName}>`;
newString = parameterValues[parameterName];
script = script.replace(oldStrimg,newString);
});
return script;
EOT
, "$", "'\$'")
}
What I did to escape $$ was to use another sign
For example (sql scripting)
let q := $$ ... ## something ## $$
q := replace(:q, '##', '$$')

Microsoft.Sharepoint.Client.Context.Load error using F#

I am trying to pull some documents from Sharepoint using the CSDOM Microsoft.Sharepoint.Client SDK.
I have a basic query set up like this:
let uri = #"XXXXXX"
let userName = XXXXXX
let password = XXXXXX
let networkCredential = new NetworkCredential(userName, password)
let context = new ClientContext(uri)
context.Credentials <- networkCredential
let list = context.Web.Lists.GetByTitle("XXXXXX")
let listItemCollection = list.GetItems(CamlQuery.CreateAllItemsQuery())
context.Load(listItemCollection)
context.ExecuteQuery()
I am getting this error message on the load method
error FS0193: internal error: GenericArguments[0],
'Microsoft.SharePoint.Client.ListItemCollection', on 'Void Load[T](T,
System.Linq.Expressions.Expression1[System.Func2[T,System.Object]][])'
violates the constraint of type 'T'.
I think I have to pass in the linq expression also? This seems like a lot of unneeded steps as all I want to do is get a list of documents from a folder to iterate.
Anyone have any alternative code?
OK, I was able to get this to work using this answer. Here's my working code:
open System
open System.Linq.Expressions
type Expr =
static member Quote(e:Expression<System.Func<_, _>>) = e
// ...
// Authentication logic goes here. Personally, I had to use
// SharePointOnlineCredentials instead of NetworkCredential.
// ...
let items =
let list = context.Web.Lists.GetByTitle("Documents")
list.GetItems(CamlQuery())
let getDisplayName =
Expr.Quote(
fun (item : ListItem) ->
item.DisplayName :> obj)
context.Load(
items,
fun (items : ListItemCollection) ->
items.Include(getDisplayName) :> obj)
context.ExecuteQuery()
for item in items do
printfn "%s" item.DisplayName
It ain't pretty, but it gets the job done.

Terraform - aws_cloud_watch_log_metric_filter

Has anyone had experience of trying to set metric filters on cloudwatch logs? Wondering if I have found a bug in Terraform?
So this is what I am trying to do;
resource "aws_cloudwatch_log_metric_filter" "AWS_Console_Login" {
name = "${var.aws_account_id}_Console_Login_Failure"
pattern = "{ ($.eventName = ConsoleLogin) && ($.errorMessage = "Failed authentication") }"
log_group_name = "${var.aws_cloudtrail_name}"
metric_transformation {
name = "${var.aws_account_id}_Console_Login_Failure"
namespace = "AccountMonitoring${var.aws_account_id}"
value = "1"
}
}
When I run a Terraform apply or validate I am getting this response;
Error: Error parsing cloudwatch.tf At 157:19: nested object expected: LBRACE got: ASSIGN
To be clear 157:19 relates to the line of code containing log_group_name with 19 being before the = symbol.
However I think this is to do with my pattern, if I remove log group.. and run a validate I get;
aws_cloudwatch_log_metric_filter.AWS_Console_Login: : invalid or unknown key: Failed
Am I asking too much with the AWS filter pattern I have?
Thanks
Stephen
Try escaping your quotes. This is a failure with syntax. The issue isn't the log_group_name line. It's the one above it.
resource "aws_cloudwatch_log_metric_filter" "AWS_Console_Login" {
name = "${var.aws_account_id}_Console_Login_Failure"
pattern = "{ ($.eventName = ConsoleLogin) && ($.errorMessage = \"Failed authentication\") }"
log_group_name = "${var.aws_cloudtrail_name}"
metric_transformation {
name = "${var.aws_account_id}_Console_Login_Failure"
namespace = "AccountMonitoring${var.aws_account_id}"
value = "1"
}
}
This appears to be fine. You should look at tflint. It's a part of the Terraform plugin for Visual Studio Code which helped me track down where the error was.

Get rid of these Optional values

Using Xcode 7 beta, Swift 2.0
I'm saving and loading credentials to keychain, somehow when loading I get "Optional(value)" back, it looks like this is really part of the string as it also displayed like so in a textbox or when sending to API
This is how I save and load credentials now, as you see I've done a lot of extra nil checking to make sure it is not nil or Optional, it is indeed a overuse of explanation marks...
func SaveCredentials(credentials : [String : String!]!) -> Bool
{
if(credentials.count == 2)
{
//only proceed when we have two keys: username and password
let username = credentials["username"]
let password = credentials["password"]
if let usernameStr = username
{//also tried username!=nil && password != nil
if let passwordStr = password
{ //usernameStr and passwordStr is of type String!
let NsDataUsername = usernameStr!.dataUsingEncoding(NSUTF8StringEncoding)
let NsDataPassword = passwordStr!.dataUsingEncoding(NSUTF8StringEncoding)
if(NsDataUsername != nil && NsDataPassword != nil)
{
LocalStorage.saveToKeyChain("username", data: NsDataUsername!)
LocalStorage.saveToKeyChain("password", data: NsDataPassword!)
return true
}
}
}
}
return false
}
func LoadCredentials() -> [String : String!]?
{
let NsDataUsername = LocalStorage.loadFromKeyChain("username")
let NsDataPassword = LocalStorage.loadFromKeyChain("password")
if(NsDataUsername != nil && NsDataPassword != nil)
{
let username : String! = String(NSString(data: NsDataUsername!, encoding: NSUTF8StringEncoding))
let password : String! = String(NSString(data: NsDataPassword!, encoding: NSUTF8StringEncoding))
if let usernameStr = username
{
if let passwordStr = password
{ // password is of type String!, passwordStr is of type String
var credentials : [String: String!] = [String : String]()
credentials["username"] = usernameStr
credentials["password"] = passwordStr
return credentials
}
}
}
return nil
}
And when I send to Api, this is my method that also requires a non-optional string. This method does work when logging in, getting strings from text fields, but does not filter out that Optional when coming from keychain.
func LoginUser(email : String!, password : String!)
{
print("LoginUser(email : \(email), password: \(password))")
var parameters = [String : AnyObject]()
parameters["UserName"] = email
parameters["Password"] = password
......
The strings that I send to the SaveCredentials method, are the same that the user logged in with:
func LoginLocalAccount(email : String!, password : String!)
{
databaseAPI.LoginUser(email!, password: password!) //login goes just fine
saveCredentials(email!, password: password!) //manages to get Optional in it..
}
I suspect it has something to do with saving and loading from keychain, for interests, this is what I use to save and load from keychain.
I want to get rid of them because when the app starts, it loads the credentials and tries to login at my API. Ofcourse I get an error back that the username is not a valid e-mail, because it is Optional(email#adress.com)
You're overusing !. You don't need them. Try to learn more about implicitly unwrapped optionals, optionals, ... Your code is a mess (no offense, everybody's learning).
Back to your optional problem, it's caused by this line:
let username : String! = String(NSString(data: NsDataUsername!, encoding: NSUTF8StringEncoding))
convenience init?(data: NSData, encoding: UInt) - inner part utilizes failable initializer, so, NSString? is the result. Then initialization of String with optional NSString? produces optional as well. But, it has no sense at all do it in this way.
First part - remove optional
Utilizing new guard:
guard let loadedPassword = NSString(data: passwordData, encoding: NSUTF8StringEncoding) else {
fatalError("Ooops")
}
loadedPassword contains NSString (not NSString?) now.
Second part - NSString -> String
You did probably read (if not, read) Strings and Characters about bridging, ... If you can freely exchange NSString with String, you can think that you're done:
var dict = [String:String]()
dict["password"] = loadedPassword
Nope. It produces following error:
NSString is not implicitly convertible to String; did you mean to
use 'as' to explicitly convert?
Slight change and now you're done:
var dict = [String:String]()
dict["password"] = loadedPassword as String
Complete example
let password = "Hallo"
guard let passwordData = password.dataUsingEncoding(NSUTF8StringEncoding) else {
fatalError("Ooops")
}
// save/load to/from keychain
guard let loadedPassword = NSString(data: passwordData, encoding: NSUTF8StringEncoding) else {
fatalError("Ooops")
}
var dict = [String:String]()
dict["password"] = loadedPassword as String
print(dict) // "[password: Hallo]\n"

Issue with InsertOnly command in Ormlite

I am using the Servicestack.ormlite package. Everything has been working perfectly, but last night, all of a sudden, my InsertOnly command stopped working. This is the format of the InsertOnly command I am using, straight from the docs: https://github.com/ServiceStack/ServiceStack.OrmLite
Here is the command:
DB.InsertOnly(new ppNomination
{
PortalID = clientID,
NOM_sOtherExperience = nom.Title,
NOM_sExperienceDescription = nom.Description,
NOM_nWitness = nom.Witness,
NOM_dLastUpdated = DateTime.Now,
NOM_WrittenBy = nom.WrittenBy,
NOM_nSteward = nom.Nominee,
NOM_dDeliveredOn = nom.DeliveredOn,
NOM_dCreatedOn = nom.CreatedOn,
NOM_nApprovedBy = nom.ApproverId == -1 ? (int?)null : nom.ApproverId,
NOM_lActive = nom.Active,
NOM_lResubmitted = nom.IsResubmitted,
NOM_lReturned = nom.IsReturned,
NOM_lManagerApproved = nom.IsManagerApproved
},
a => a.Insert(p => new { p.PortalID, p.NOM_sOtherExperience, p.NOM_sExperienceDescription,
p.NOM_nWitness, p.NOM_dLastUpdated, p.NOM_WrittenBy, p.NOM_nSteward, p.NOM_dDeliveredOn,
p.NOM_dCreatedOn, p.NOM_nApprovedBy, p.NOM_lActive, p.NOM_lResubmitted, p.NOM_lReturned,
p.NOM_lManagerApproved }));
nom is the object being passed to the function, and I am just filling it up. This is the error I see:
variable 'p' of type 'Obsidian.Domain.DomainModel.ppNomination' referenced from scope '', but it is not defined
Any ideas as to what I might be doing wrong?

Resources