I would like to create a lint rule to block the usage of window.location.href but allow using any other window.location properties.
This one is working for all location sub methods:
"no-restricted-properties": \["error", {
"object": "window",
"property": "location",
}\]
But I would like to block only the href method.
Ok i got it:
"no-restricted-properties": ["error", { "object": ['window']['location'], "property": "href", }]
Related
I'm using Azure functions with javascript, and i would like to modify the out binding of path in my functions. For example this is my function.json:
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
},
{
"name": "outputBlob",
"path": "container/{variableCreatedInFunction}-{rand-guid}",
"connection": "storagename_STORAGE",
"direction": "out",
"type": "blob"
}
]
I Would like to set {variableCreatedInFunction} in index.js, for example:
module.exports = async function (context, req) {
const data = req.body
const date = new Date().toISOString().slice(0, 10)
const variableCreatedInFunction = `dir/path/${date}`
if (data) {
var responseMessage = `Good`
var statusCode = 200
context.bindings.outputBlob = data
} else {
var responseMessage = `Bad`
var statusCode = 500
}
context.res = {
status: statusCode,
body: responseMessage
};
}
Couldn't find any way to this, is it possible?
Bindings are resolved before the function executes. You can use {DateTime} as a binding expression. It will by default be yyyy-MM-ddTHH-mm-ssZ. You can use {DateTime:yyyy} as well (and other formatting patterns, as needed).
Imperative bindings (which is what you want to achieve) is only available in C# and other .NET languages, the docs says:
Binding at runtime In C# and other .NET languages, you can use an
imperative binding pattern, as opposed to the declarative bindings in
function.json and attributes. Imperative binding is useful when
binding parameters need to be computed at runtime rather than design
time. To learn more, see the C# developer reference or the C# script developer reference.
MS might've added it to JS as well by now, since I'm pretty sure I read that exact section more than a year ago, but I can't find anything related to it. Maybe you can do some digging yourself.
If your request content is JSON, the alternative is to include the path in the request, e.g.:
{
"mypath":"a-path",
"data":"yourdata"
}
You'd then be able to do declarative binding like this:
{
"name": "outputBlob",
"path": "container/{mypath}-{rand-guid}",
"connection": "storagename_STORAGE",
"direction": "out",
"type": "blob"
}
In case you need the name/path to your Blob, you'd probably have to chain two functions together, where one acts as the entry point and path generator, while the other is handling the Blob (and of course the binding).
It would go something like this:
Declare 1st function with HttpTrigger and Queue (output).
Have the 1st function create your "random" path containing {date}-{guid}.
Insert a message into the Queue output with the content {"mypath":"2020-10-15-3f3ecf20-1177-4da9-8802-c7ad9ada9a33", "data":"some-data"} (replacing the date and guid with your own generated values, of course...)
Declare 2nd function with QueueTrigger and your Blob-needs, still binding the Blob path as before, but without {rand-guid}, just {mypath}.
The mypath is now used both for the blob output (declarative) and you have the information available from the queue message.
It is not possiable to set dynamic variable in .js and let the binding know.
The value need to be given in advance, but this way may achieve your requirement:
index.js
module.exports = async function (context, req) {
context.bindings.outputBlob = "This is a test.";
context.done();
context.res = {
body: 'Success.'
};
}
function.json
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
},
{
"name": "outputBlob",
"path": "test/{test}",
"connection": "str",
"direction": "out",
"type": "blob"
}
]
}
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "node",
"str":"DefaultEndpointsProtocol=https;AccountName=0730bowmanwindow;AccountKey=xxxxxx;EndpointSuffix=core.windows.net"
}
}
Or you can just put the output logic in the body of function. Just use the javascript sdk.
Trying to add hovers to add hovers to my VS Code extension. I was able to syntax highlighting and commands to work, but stuck on adding this hover feature.
I think my blocker is how to properly implement the HoverProvider API. I'm doing a simple test below for a hover provider that activates when a series of tokens are recognized as the keyword HELLO. The hover I've implemented in my testing. I'm using vsce package to package and test my extension locally.
My command for the extension works, but when I hover over the word "HELLO", my hover does not appear.
./client/extension.js
const vscode = require('vscode');
function activate(context) {
console.log('Congratulations, your extension "star-rod" is now active!');
let disposable = vscode.commands.registerCommand('extension.mamar', () => {
vscode.window.showInformationMessage("The Star Rod... is powerful beyond belief. It can grant any wish. For as long as we can remember, Bowser has been making wishes like, for instance... 'I'd like to trounce Mario' or 'I want Princess Peach to like me.' Of course, Stars ignore such selfish wishes. As a result, his wishes were never granted.");
});
context.subscriptions.push(disposable);
vscode.languages.registerHoverProvider('javascript', {
provideHover(document, position, token) {
const range = document.getWordRangeAtPosition(position);
const word = document.getText(range);
if (word == "HELLO") {
return new vscode.Hover({
language: "Hello language",
value: "Hello Value"
});
}
}
});
}
function deactivate() { }
module.exports = {
activate,
deactivate
}
./package.json
{
"name": "star-rod-script",
"publisher": "sonicspiral",
"displayName": "Star Rod Script",
"description": "Syntax highlighting for Paper Mario 64 ROM patching tool",
"version": "1.0.1",
"repository": {
"type": "git",
"url": "https://github.com/gregdegruy/star-rod.git"
},
"categories": [
"Programming Languages"
],
"activationEvents": [
"onCommand:extension.mamar",
"onLanguage:star-rod-script"
],
"engines": {
"vscode": "^1.31.0"
},
"main": "./client/extension.js",
"contributes": {
"capabilities": {
"hoverProvider": "true"
},
"commands": [
{
"command": "extension.mamar",
"title": "Mamar"
}
],
"languages": [
{
"id": "star-rod-script",
"extensions": [
".bpat",
".bscr",
".mpat",
".mscr"
],
"aliases": [
"Star Rod Script",
"mscr"
],
"configuration": "./language-configuration.json"
}
],
"grammars": [
{
"language": "star-rod-script",
"scopeName": "source.mscr",
"path": "./syntaxes/mscr.tmLanguage.json"
}
]
},
"devDependencies": {
"js-yaml": "^3.12.1",
"vscode": "^1.1.29"
}
}
Your code allowed me to get Hovers working in my first extension. I think your mistake is having javascript as the selector: vscode.DocumentSelector. Is that there from code you copied? That should probably be set to star-rod-script for your extension.
I also don't have "capabilities": {"hoverProvider": "true"} in mine. I changed your code to:
disposable = vscode.languages.registerHoverProvider('star-rod-script', { // or 'star rod script'
//....
});
context.subscriptions.push(disposable);
I don't know the nuances of how you apply your extension to certain documents, but it doesn't look like you're trying to apply the hover to javascript docs. You need the selector to include the docs your extension works with. In my case that's covered by my extension name which is the language mode that shows up in the vscode status bar. More info on document-selectors.
Not sure if it's needed, but I also took the return and pushed it onto the subscriptions array. Works without that, but I think that's proper??
Your package.json looks a bit odd. I bet your extension is not activated. The "contributes/capabilites" value is something I haven't seen before. Remove that and instead change your activationEvents to:
"activationEvents": [
"onLanguage:star-rod-script"
],
I am having problem that I cannot solve. I need to print out response objects with javascript and I don't know how to do that. I have response like.this:
{
"#context": "/contexts/Client",
"#id": "/clients",
"#type": "hydra:Collection",
"hydra:member": [
{
"#id": "/clients/1",
"#type": "Client",
"uuid": "e3rer445",
"number": " 0483",
"name": "Tom Beringer",
"adresses": [
{
"#id": "/client_addresses/1",
"#type": "http://schema.org/Thing",
"address": {
"#id": "/addresses/1",
"#type": "http://schema.org/Thing",
"address": "Postbus 1d425"
}
},
]
},
And now I need to print out the result of all client details, so when I do this:
axios.get('/clients')
.then(res => {
this.users = res.data['hydra:member']
})
I successfully print out the name, number, but when I try to print out addresses i get.this as a result:
<td><span>[
{
"#id": "/client_addresses/3",
"#type": "http://schema.org/Thing",
"address": {
"#id": "/addresses/3",
"#type": "http://schema.org/Thing",
"address": "niet meer gebruiken"
}
}
</span></td>
But what I need is just.this address: niet meer gebruiken
Is it possible to do that?
Yes, It is possible.
Try with this:
res.data['hydra:member'][0]['adresses'][0]['address']['address']
or
res.data['hydra:member'][0]['adresses'][0].address.address
That will work fine if you only have one address object nested. In case you have more objects inside you should iterate over the array of addresses.
This will be/contain your array of addresses:
res.data['hydra:member'][0]['adresses']
In addition to Jonathan's answer, here's some explanation.
You don't have to create a default config, but make sure when making a request to the api generated by Api platform, to add an 'Accept' header. The default seems to be 'application/ld+json'.
Adding 'Accept': 'application/json' to your headers will make sure you only get your objects without all the extra tags Api platform adds.
Just add a config default.
./main.js
axios.defaults.headers.common['Accept'] = 'application/json';
axios.defaults.headers.put['Content-Type'] = 'application/json';
axios.defaults.headers.get['Content-Type'] = 'application/json';
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.delete['Content-Type'] = 'application/json';
Vue.prototype.$http = axios;
Have you tried accessing the property like this?
res.data['hydra:member']['addresses][0]['address']['address']
If there is more than one address object nested within your addresses array, you might need to iterate over it.
Here's my situation, I have a JSON that looks somewhat like this:
{
"items": [{
"type": "condition",
"data": {
"type": "comparison",
"value1": {
"source": "MyType1",
"component": "Attribute1"
},
"value2": {
"source": "MyType2",
"component": "Attribute2"
},
"operator": "gt"
}
},
{
"type": "then",
"data": {
"result": "failed",
"message": "value1 is too high"
}
}
]
}
and would want it to translate to:
if (MyType1.Attribute1 > MyType2.Attribute2) {
result = "failed";
console.log("value1 is too high");
}
Now my problem is, I don't know how I would translate the entries of value1 and value2 to actual code, or rather, how I could access the Object MyType1(maybe through something like getAttribute("MyType1")).
Since I am going to have a whole bunch of sources which each have different components, I cant really write a huge dictionary. Or I would like to avoid it.
The goal is to allow creating if - then - statements via some interactive UI, and I figured it'd be best to save that code as .json files. (Think rule management system).
So, TL,DR, How would I access a Class Attribute this.MyType, if I only have a String MyType to go from? And how would I access the value this.MyType.MyValue, if I get another String MyValue?
Thanks in advance.
Edit:
I'd really like to avoid using eval, for obvious reasons. And if I have to - I guess I would need to create Dictionaries for possible JSON Values, to validate the input?
You need some kind of parser. At first we need some way to store variables and maybe flags:
const variables = {};
var in = false;
Then we go through the code and execute it:
for(const command of items){
switch( command.type ){
case "condition":
//...
case "then":
//...
}
}
To access a variable we can simply do
var current = variables[ identifier ];
To store its the other way round:
variables[ identifier ] = current;
This is what I'd like to achieve (t is selected in editor):
Before snippet:
var t = 'Foobar';
After snippet:
var t = 'Foobar';
console.log('t', t);
How can I do that?
Here is what I tried to do:
"log_selection": {
"prefix": "cls",
"body": [
"console.log('$TM_SELECTED_TEXT', $TM_SELECTED_TEXT);"
],
"description": "Logs selected text"
}
But this just replace selected text with snippet. I think that I could use TM_CURRENT_LINE here but I have no idea what to do with remaining text in the line.
Do you have any idea for this? Maybe it's impossible with snippet? If so, how can I achieve desired effect?
Thank you.
Extension macros (executing multiple commands in 1 keybinding).
settings.json:
"macros": {
"snippetWithDescription": [
"editor.action.clipboardCopyAction",
"editor.action.insertLineAfter",
{
"command": "editor.action.insertSnippet",
"when": "editorTextFocus",
"args": {
"snippet": "console.log('$CLIPBOARD', $CLIPBOARD)$0"
}
}
]
}
keybindings.json:
{
"key": "ctrl+shift+;",
"command": "macros.snippetWithDescription"
}
P.S. you can even omit the selection part if you add another command at the beginning of snippetWithDescription: "editor.action.addSelectionToNextFindMatch",. Just place cursor beside the word and hit hotkey.
I came to this question looking for a solution other than installing a macro extension. Yours can be done with a snippet though as long as the cursor is at the end of your var declaration line. The snippet would use regex:
"log_selection": {
"prefix": "cls",
"body": [
"",
"console.log('${TM_CURRENT_LINE/var (.+?) =.*$/$1', $1/});"
],
"description": "Logs selected text"
}
The capturing group (.+?) holds your variable name and is placed in $1. I've tested it (and a good thing, because it took a lot of edits to get a working regex). You'd probably want to set up a key binding in your settings to trigger the snippet (but it also works typing the snippet prefix):
"key": "alt+c alt+l", // some key combo
"command": "editor.action.insertSnippet",
"when": "editorTextFocus && !editorHasSelection",
"args": {
"langId": "js", // ?? optional?
"name": "log_selection" // your snippet name
}
Unfortunately, in my case I'm trying to alter the current line so it seems I may need a macro to select the line so that it is replaced.
this worked for me:
"macros": {
"logCurrentVariable": [
"editor.action.addSelectionToNextFindMatch",
"problems.action.copy",
"editor.action.clipboardCopyAction",
{
"command": "editor.action.insertSnippet",
"when": "editorTextFocus",
"args": {
"snippet": "console.log('$CLIPBOARD', $CLIPBOARD)$0"
}
}
]
},
from https://medium.com/#copperfox777/how-to-console-log-variable-under-the-cursor-in-visual-studio-code-ba25feadb00a