Converting AVVideoComposition initializer to Nativescript - javascript

Looking for some help on porting this objective-c class method to JS/nativescript.. every variation I've tried has resulted in a TypeError: undefined is not a function...
https://developer.apple.com/documentation/avfoundation/avvideocomposition/1389556-init
Which I've tried to write in JS as:
const videoComp = AVVideoComposition.alloc().initWithAssetApplyingCIFiltersWithHandler(asset, (request) => { ... });
//OR
const videoComp = AVVideoComposition.alloc().initAssetApplyingCIFiltersWithHandler(asset, (request) => { ... });
//OR
const videoComp = AVVideoComposition.alloc().initAssetApplyingCIFiltersWithHandlerApplier(asset, (request) => { ... });
//OR
const videoComp = new AVVideoComposition(asset, (request) => { ... });
to name a few. essentially, I am trying to port this code to nativescript/JS:
let blurRadius = 6.0
let asset = AVAsset(url: streamURL)
let item = AVPlayerItem(asset: asset)
item.videoComposition= AVVideoComposition(asset: asset) { request in
let blurred = request.sourceImage.clampedToExtent().applyingGaussianBlur(sigma: blurRadius)
let output = blurred.clampedToRect(request.sourceImage.extent)
request.finish(with: output, context: nil)
}
found in this blog post: https://willowtreeapps.com/ideas/how-to-apply-a-filter-to-a-video-stream-in-ios

It should look something like this with JavaScript / Typescript,
let blurRadius = 6.0;
let asset = AVAsset.assetWithURL(streamURL);
let item = AVPlayerItem.alloc().initWithAsset(asset);
item.videoComposition = AVVideoComposition.videoCompositionWithAssetApplyingCIFiltersWithHandler(asset, request => {
let blurred = request.sourceImage.imageByClampingToExtent().imageByApplyingGaussianBlurWithSigma(blurRadius);
let output = blurred.imageByClampingToRect(request.sourceImage.extent);
request.finishWithImageContext(output, null);
});
Note: The code is untested and merely a translation of given native code. Make use of tns-platform-declarations for IntelliSense support.

Related

Javascript working in Chrome, working in firefox locally, but not after deployment

This is part of a Spark Java app, but the error is happening in this JS part. The relevant code is as follows:
const addErrBox = async () => {
const controls = document.querySelector(".pure-controls");
const errBox = document.createElement("p");
errBox.setAttribute("id", "errBox");
errBox.setAttribute("style", "color:red");
errBox.innerHTML = "Short URL not valid or already in use!";
controls.appendChild(errBox);
}
const submitForm = () => {
const form = document.forms.namedItem("new-url-form");
const longUrl = form.elements["longUrl"];
const shortUrl = form.elements["shortUrl"];
const url = `/api/new`;
fetch(url, {
method: "POST",
body: `${longUrl.value};${shortUrl.value}`
})
.then((res) => {
if (!res.ok) {
if (document.getElementById("errBox") == null) {
addErrBox();
}
}
else {
document.getElementById("errBox")?.remove();
longUrl.value = "";
shortUrl.value = "";
refreshData();
}
});
};
(async () => {
await refreshData();
const form = document.forms.namedItem("new-url-form");
form.onsubmit = e => {
e.preventDefault();
submitForm();
}
})();
Basically, "/api/new" checks for validity of input, adds the data to database if valid and prints error otherwise. Now, when the input is valid, it seems to work. The "/api/new" code is in Java, which seems to work properly as well since I do get a 400 error. All of it works properly when built inside a docker locally, but when accessed over internet using Nginx reverse proxy, it stops working inside firefox. Chrome still works. I'm not sure what's happening.
The code for "/api/new" is this:
public static String addUrl(Request req, Response res) {
var body = req.body();
if (body.endsWith(";")) {
body = body + "$";
}
var split = body.split(";");
String longUrl = split[0];
if (split[1].equals("$")) {
split[1] = Utils.randomString();
}
String shortUrl = split[1];
shortUrl = shortUrl.toLowerCase();
var shortUrlPresent = urlRepository
.findForShortUrl(shortUrl);
if (shortUrlPresent.isEmpty() && Utils.validate(shortUrl)) {
return urlRepository.addUrl(longUrl, shortUrl);
} else {
res.status(HttpStatus.BAD_REQUEST_400);
return "shortUrl not valid or already in use";
}
}
Update: it suddenly started working, without any change on the server side. I think it was some kind of issue with caching, either in firefox, cloudflare or Nginx's part.

Async JS validation issues for html textarea

I'm trying to replicate the code in this article:
https://depth-first.com/articles/2020/08/24/smiles-validation-in-the-browser/
What I'm trying to do different is that I'm using a textarea instead of input to take multi-line input. In addition to displaying an error message, I also want to display the entry which doesn't pass the validation.
The original validation script is this:
const path = '/target/wasm32-unknown-unknown/release/smival.wasm';
const read_smiles = instance => {
return smiles => {
const encoder = new TextEncoder();
const encoded = encoder.encode(`${smiles}\0`);
const length = encoded.length;
const pString = instance.exports.alloc(length);
const view = new Uint8Array(
instance.exports.memory.buffer, pString, length
);
view.set(encoded);
return instance.exports.read_smiles(pString);
};
};
const watch = instance => {
const read = read_smiles(instance);
document.querySelector('input').addEventListener('input', e => {
const { target } = e;
if (read(target.value) === 0) {
target.classList.remove('invalid');
} else {
target.classList.add('invalid');
}
});
}
(async () => {
const response = await fetch(path);
const bytes = await response.arrayBuffer();
const wasm = await WebAssembly.instantiate(bytes, { });
watch(wasm.instance);
})();
For working with a textarea, I've changed the watch function to this and added a <p id="indicator"> element to the html to display an error:
const watch = instance => {
const read = read_smiles(instance);
document.querySelector("textarea").addEventListener('input', e => {
const { target } = e;
var lines_array = target.value.split('/n');
var p = document.getElementById("indicator");
p.style.display = "block";
p.innerHTML = "The size of the input is : " + lines_array.length;
if (read(target.value) === 0) {
target.classList.remove('invalid');
} else {
target.classList.add('invalid');
}
});
}
I'm not even able to get a count of entries that fail the validation. I believe this is async js and I'm just a beginner in JavaScript so it's hard to follow what is happening here, especially the part where the function e is referencing itself.
document.querySelector("textarea").addEventListener('input', e => {
const { target } = e;
Can someone please help me in understanding this complicated code and figuring out how to get a count of entries that fail the validation and also printing the string/index of the same for helping the user?
There is a mistake in you code to count entries in the textarea:
var lines_array = target.value.split('\n'); // replace /n with \n
You are asking about the function e is referencing itself:
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. You can find more informations Mdn web docs - Destructuring object

How does one parent a channel to a category with a discord bot?

Basically there is no errors in the output but at the same time it's not doing what I'm trying to achieve.
Ive been tinkering with the script for 5 hours straight mixing up line positioning and now I got it to where it gives me the promise (my initial issue) but I cant parent the channel.
I've tried discord.js server and site, youtube, 2 other sites i forgot the name of but i cant crack it.
function setup(arguments, message){
var server = message.guild;
var name = message.author.username;
let searchquery = arguments.join("")
let cat = server.createChannel("Important", "category");
async function Channelmaker(Sent, obj){
try {
let chan = await server.createChannel(Sent, "Text");
//console.log(obj);
return chan
} catch(prom){
var chan2 = await server.createChannel(Sent, "Text");
return new Promise(resolve => {
var chan2 = server.createChannel(Sent, "Text", parent = obj);
resolve(chan2)
});
}
}
var holding
var chan = Channelmaker("⚖️ rules ⚖️", cat).then(value => {
console.log(value)
holding = value
value.parentID = cat
chan.setParent(cat.Id)
}).catch(error => {
// s
});
console.log("holding")
console.log(holding)
}
The category is not the parent of the "⚖️ rules ⚖️" channel that is created which is the opposite of what I'm trying to achieve
In Guild.createChannel(), use the options parameter including ChannelData, like so:
await server.createChannel(Sent, {
// You can omit the 'type' property; it's 'text' by default.
parent: obj
});

I get a undefined in my React API component

I am getting an undefined when trying to use the search bar in my app. The components compile fine in webpack. I am not sure if I am having an es6 syntax issue or am missing something inside the operation of the components.
const axios = require('axios');
const OPEN_WEATHER_MAP_URL =
'http://samples.openweathermap.org/data/2.5/weather?appid=5d0a2ef2cca550311d7015dc03763d54&units=imperial';
module.exports = {
getTemp(location) {
var encodedLocation = encodedURIComponent(location);
var requestUrl = `${OPEN.WEATHER_MAP_URL}&q=${encodedLocation}`;
axios.get(requestUrl).then((res) => {
if (res.data.cod && res.data.message) {
throw new Error(res.data.message)
} else {
return res.data.main.temp;
}
((res) => {
throw new Error(res.data.message);
})
})
}
};
I get the error when I trigger the search in the search bar I get the undefined at var encodedLocation = encodedURIComponent(location);
I have tried using let and const instead of var, but this also did not help
Fix a small typo:
Change
var encodedLocation = encodedURIComponent(location);
to
var encodedLocation = encodeURIComponent(location);

RegExp working in JSFiddle but not in nodejs

I have the regular expression:
/(?:!!)(.+)(?:!!)(?:\(zoomOn )([\S,]+)(?:\))/g
It matches something like !!some text!!(zoomOn 1,2,3).
This works okay in the browser (JSFiddle here) but not in Node. I am writing in ES2015, using Babel and the es2015 preset.
For extra insight this is for a Showdown extension. I noticed the twitter extension add some extra \ to the RegExps. Is this a quirk of Node/ES5 I'm not aware of?
Update
I was hoping I wouldn't need to post the code for Node since I thought it would just be a node quirk.
Anyway, the code is for an extension to Showdown:
# extensions.js
export const manipulationAPIExtensions = () => [
{
// [zoomOn node1,node2,node3,...](some text)
type: 'lang',
filter: (text, converter, options) => {
const toReturn = text.replace(/(?:!!)(.+)(?:!!)(?:\(zoomOn )([\S,]+)(?:\))/g, (match, innerText, nodeString) => {
const nodes = nodeString.split(/\s*,\s*/);
let nodeArrayAsString = '[';
nodes.forEach(node => {
nodeArrayAsString += `'${node}',`;
});
nodeArrayAsString += ']';
return `<a onclick="pathwayInstance.manipulator.zoomOn(${nodeArrayAsString})">${text}</a>`;
});
return toReturn;
},
},
];
This is used in Showdown as follows:
export const getShowdown = (KaavioInstance) => {
window.diagram = KaavioInstance;
Showdown.extension('kaavio', manipulationAPIExtensions());
return new Showdown.Converter({
extensions: ['kaavio'],
});
};
And then in my unit test:
describe('CustomMarkdown', () => {
// Don't really need Kaavio since we are only checking the output HTML
const mockKaavioInstance = {};
const converter = getShowdown(mockKaavioInstance);
console.log(converter.getAllExtensions())
describe('Kaavio', () => {
it('should return the correct HTML from the markdown', () => {
const markdown = normalize(fs.readFileSync(`${__dirname}/extensions/Kaavio.md`, 'utf8'));
const HTML = normalize(fs.readFileSync(`${__dirname}/extensions/Kaavio.html`, 'utf8'));
const output = converter.makeHtml(markdown);
assert.equal(output, HTML);
});
});
});
The unit test fails since no match is found.
If I do something simple like the below it works. Of course the unit test doesn't work but if I console.log it out then I get the expected result of matched.
# extensions.js
export const manipulationAPIExtensions = () => [
{
// [zoomOn node1,node2,node3,...](some text)
type: 'lang',
filter: (text, converter, options) => {
const toReturn = text.replace(/./g, (match) => {
return 'matched';
});
return toReturn;
},
},
];
That works for me in Node, just tried it, but that fiddle uses an alert(). You need to use something like console.log() that Node understands.
var text = '!!some text!!(zoomOn node1)';
text.replace(/(?:!!)(.+)(?:!!)(?:\(zoomOn )([\S,]+)(?:\))/g, function (match, innerText, nodeString) {
console.log("matched!");
})
Maybe you have some other code you didn't post which is interfering?
This is embarrassing but a lesson in checking all called functions learned. The normalize() function that is called in these lines:
const markdown = normalize(fs.readFileSync(`${__dirname}/extensions/Kaavio.md`, 'utf8'));
const HTML = normalize(fs.readFileSync(`${__dirname}/extensions/Kaavio.html`, 'utf8'));
was replacing white spaces with bullet characters... Thanks for the help regardless!

Categories

Resources