Modelviewer as npm import - npm

I am trying Modelviewer, no issues when using in html:
<script type="module" src="https://unpkg.com/#google/model-viewer/dist/model-viewer.min.js"></script>
<model-viewer src="./3dobjects/someObject.glb">
</model-viewer>
What I want is to use javascript (along with vitejs) but I am not sure how to do it...
After adding modelviewer:
npm install #google/model-viewer
I wrote this code:
import { ModelViewerElement } from "#google/model-viewer"
const modelV = new ModelViewerElement
modelV.src = "./3dobjects/someObject.glb"
modelV.exposure = 1.25
modelV.autoRotate
modelV.autoRotateDelay = 1.0
...
...
document.querySelector('#model').insertAdjacentHTML(
'beforeend',
modelV
)
So I am trying to insert an object to my HTML? how to show my 3d on my HTML?

Related

output of predict in Tensorflow.js always show first example

I recently learning an image classifier using TensorFlow js in the browser, I made a simple image classification that can identify an image of Giorno and Jotaro, but when predicting a new image, the result always shows the first example(Jotaro) which I added, I'm trying to check the second function which added second example(Giorno), It just fine in console, and running well, this is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Giorno and Jotaro Classifier</title>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow-models/mobilenet"></script>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow-models/knn-classifier"></script>
</head>
<body>
<h1>Test Image</h1>
<img id="predict" src="anime/test_giorno.jpg" alt="" width="300">
</body>
</html>
<script>
const initScript = async function(){
const ClassifierKNN = knnClassifier.create();
const mobileneModule = await mobilenet.load();
for(let i=1; i<=3;i++){
const im = new Image(300,300);
im.src = 'anime/jotaro/'+i+'.jpg';
im.onload = ()=>{
let trainingImageJotaro = tf.browser.fromPixels(im);
let predJotaro = mobileneModule.infer(trainingImageJotaro,'conv_preds');
if(i)
ClassifierKNN.addExample(predJotaro,"Jotaro");
}
im.onload();
}
for(let i=1; i<=3;i++){
const im2 = new Image(300,300);
im2.src = 'anime/giorno/'+i+'.jpg';
im2.onload = ()=>{
let trainingImageGiorno = tf.browser.fromPixels(im2);
let predGiorno = mobileneModule.infer(trainingImageGiorno,'conv_preds');
ClassifierKNN.addExample(predGiorno,"Giorno");
}
im2.onload();
}
let imgX = document.getElementById('predict');
const tensorX = tf.browser.fromPixels(imgX);
const logitsX = mobileneModule.infer(tensorX,'conv_preds');
let result = await ClassifierKNN.predictClass(logitsX);
console.log('outout:');
console.log(result);
}
initScript();
</script>
the result of the script is always jotaro, but when I switch the loop position like this:
for(let i=1; i<=3;i++){
const im2 = new Image(300,300);
im2.src = 'anime/giorno/'+i+'.jpg';
im2.onload = ()=>{
let trainingImageGiorno = tf.browser.fromPixels(im2);
let predGiorno = mobileneModule.infer(trainingImageGiorno,'conv_preds');
ClassifierKNN.addExample(predGiorno,"Giorno");
}
im2.onload();
}
for(let i=1; i<=3;i++){
const im = new Image(300,300);
im.src = 'anime/jotaro/'+i+'.jpg';
im.onload = ()=>{
let trainingImageJotaro = tf.browser.fromPixels(im);
let predJotaro = mobileneModule.infer(trainingImageJotaro,'conv_preds');
if(i)
ClassifierKNN.addExample(predJotaro,"Jotaro");
}
im.onload();
}
the result always Giorno, can anyone help me with this problem?
Thanks #zer0sign, for sharing the solution in comments. For the benefit of community I am providing solution here (answer section)
This problem has been fixed, above issue occurs because, the second training data is executed after the testing data, therefore the code above only gets 1 label, because the second label has not been executed and therefore the output label of the predicted image always shows the label of the first training data.

reading ID3 tag in NativeScript + Vue

I am trying to read id3 tags of mp3 files in my project but it seems all the node plugins has a dependency on fs ,
since I get this error: TypeError: fs.exists is not a function
so How can I read id3 tags in NativeScript?
{N} !== Node, You will have to fetch the meta data in native iOS / Android way. Use nativescript-media-metadata-retriever plugin.
tns plugin add nativescript-media-metadata-retriever
You could try nativescript-nodeify, but I remember having problem afterwards with with bundling.
Also, I used this back in NativeScript 4. I don't know if this still works in NS 6.
I share my usage of this module in sake of noobies like me, who can waste their times just for a misunderstanding :))
requires:
import { MediaMetadataRetriever } from "nativescript-media-metadata-retriever";
const imageSourceModule = require( "tns-core-modules/image-source" );
const fs = require("tns-core-modules/file-system");
and the code:
// ------- init MediaMetadataRetriever
let mmr = new MediaMetadataRetriever();
mmr.setDataSource( newValue );
mmr.getEmbeddedPicture()
.then( ( args ) => {
// ------- show the albumArt on bgIMG
var albumArt = this.$refs.bgIMG.nativeView;
var img = new imageSourceModule.ImageSource();
// ------- setNativeSource is a **Methods** of imageSourceModule
img.setNativeSource( args );
albumArt.set( "src" , img );
console.log("ImageSource set...");
// ------- save the albumArt in root of SDCARD
// ------- fromNativeSource is a **Function** of imageSourceModule
let imageSource = imageSourceModule.fromNativeSource( args );
console.log("Here");
let fileName = "test.png";
const root = android.os.Environment.getExternalStorageDirectory().getAbsolutePath().toString();
let path = fs.path.join( root , fileName);
let saved = imageSource.saveToFile(path, "png");
if (saved) {
console.log("Image saved successfully!");
}
} );

react-native .toLocaleString() not working on android

Updated 2022: With hermes enabled you should be good now.
I'm using .toLocaleString() on react-native for my number output. All work on IOS but seems not working on Android. This is normal or? Do I need to use a function for the decimal?
rather than using a polyfill or an external dependency, change the JSC your android app builds with. For the newer versions of react-native add or override the following line in app/build.gradle
def jscFlavor = 'org.webkit:android-jsc-intl:+'
On newer versions of RN >0.62 you can change the JSC (JavaScriptCore) build variant to support/include ICU i18n library and necessary data allowing to use e.g. Date.toLocaleString and String.localeCompare
Replace this line in your android/app/build.gradle file
def jscFlavor = 'org.webkit:android-jsc:+'
with this line
def jscFlavor = 'org.webkit:android-jsc-intl:+'
Clean build and react-native run android
Note
This variant is about 6MiB larger per architecture than default.
So, expect your APK size to increase by about 4MB for each APK architecture build if using def enableSeparateBuildPerCPUArchitecture = true and a more bigger APK if separate build per architecture is disabled
You can use
number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
This is an issue with Javascript core used to run react native in Android and not with react native itself. To overcome this, you'll have to integrate latest javascript core into your android build or upgrade react native to 0.59.
The details are documented in JSC Android Buildscripts repo.
Now for people who would like to do the locale string formatting without needing to integrate the entire javascript core, Javascript has Internationalization API which lets you format numbers to language sensitive format. Documentation available at MDN
This API is not available in android and needs to be polyfilled using Intl
In your project root, install the Intl library
yarn add intl
And then in your project's index file (index.js) add the following code at the top of the file:
if(Platform.OS === 'android') { // only android needs polyfill
require('intl'); // import intl object
require('intl/locale-data/jsonp/en-IN'); // load the required locale details
}
After doing the above two steps, you can now get locale string anywhere in your project using
new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(10000000);
In case you need to format number for another locale code, all the locale code details are available under the intl/locale-data/jsonp/ directory. Simply require the ones you need in your index.js file.
The reason for this is very old version of JavaScriptCore used by react-native. iOS embeds own version which is why it is working fine there.
Issue still exists (some reading about where it's heading https://github.com/facebook/react-native/issues/19737)
And more info about this from Airbnb devs
https://medium.com/airbnb-engineering/react-native-at-airbnb-the-technology-dafd0b43838 (search for "JavaScriptCore inconsistencies")
(value) => {
if (typeof value === 'number') {
const [currency, cents] = (value / 100).toFixed(2).toString().split('.');
return `${currency.replace(/\B(?=(\d{3})+(?!\d))/g, '.')},${cents}`;
}
return '0,00';
}
it's more recent and lightweight, please check
First install:
yarn add #formatjs/intl-getcanonicallocales #formatjs/intl-locale #formatjs/intl-pluralrules #formatjs/intl-numberformat
Check if need polyfill
import {shouldPolyfill} from '#formatjs/intl-numberformat/should-polyfill'
if (shouldPolyfill()) {
require('#formatjs/intl-getcanonicallocales/polyfill');
require('#formatjs/intl-locale/polyfill');
require('#formatjs/intl-pluralrules/polyfill');
require('#formatjs/intl-numberformat/polyfill');
require('#formatjs/intl-numberformat/locale-data/en-US');
}
see source: https://formatjs.io/docs/polyfills/intl-numberformat/
A very easy and straight forward way is to use a polyfill:
First it needs to be installed:
npm i number-to-locale-string-polyfill
This has to be added in your code, best just outside the class/function where you want to use .toLocaleString().
require('number-to-locale-string-polyfill');
I solved this using a custom function
function numberToMoney(amount, simbol = '$', decimalCount = 2, decimal
= ".", thousands = ",") {
decimalCount = Math.abs(decimalCount)
decimalCount = isNaN(decimalCount) ? 2 : decimalCount
const negativeSign = amount < 0 ? "-" : ""
const i = parseInt(amount = Math.abs(Number(amount) ||
0).toFixed(decimalCount)).toString()
const j = (i.length > 3) ? i.length % 3 : 0
return simbol + negativeSign + (j ? i.substr(0, j) + thousands : '') +
i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ?
decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "")
};
No need to install extra packages
Displaying currency values in React Native A zero dependencies solution:
const parseCurr = (value) =>
Platform.OS === 'android'
? '$' + price.toFixed(2)
: price.toLocaleString('en-US', { style: 'currency', currency:'USD' });
parseCurr(25.75) // => $25.75
A real life example (money values are multiplied by 100 for better cents precision) and converting the value to Brazilian Reais (R$)
export const getBRPrice = (price: number) => {
const parsedPrice =
( price / 100 ).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
return Platform.OS === 'android'
? `R$${ ( price / 100 ).toFixed(2) }`
: parsedPrice;
};
// getBRPrice(450) => R$4,50
Solution: 1
Go to your android/app/build.gradle
Replace this line def jscFlavor = 'org.webkit:android-jsc:+'
with this
def jscFlavor = 'org.webkit:android-jsc-intl:+'
Stop the metro and rebuild your app.
Solution: 2
Otherwise, you can use this package https://www.npmjs.com/package/luxon
import import {DateTime} from 'luxon';
const date = DateTime.fromISO(new Date().toISOString());
const formatted = date.toLocaleString(DateTime.DATETIME_MED);
console.log(formatted);
Merging some responses from this thread, you can use this code where it is possible to customize the formatted response
const defaultOptions = {
significantDigits: 2,
thousandsSeparator: ',',
decimalSeparator: '.',
symbol: '$'
}
const currencyFormatter = (value, options) => {
if (typeof value !== 'number') value = 0.0
options = { ...defaultOptions, ...options }
value = value.toFixed(options.significantDigits)
const [currency, decimal] = value.split('.')
return `${options.symbol} ${currency.replace(
/\B(?=(\d{3})+(?!\d))/g,
options.thousandsSeparator
)}${options.decimalSeparator}${decimal}`
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}
This will remove commas after decimal point
If you need two digits after the decimal and always want to round down
you can use below code.
Math.floor(1233.31231231 * 100) / 100).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
To round differently check out this resource
If these solutions don't work for you... In my case, I was using React Native with the expo web simulator and wanted to format minutes with 2 characters ie. 00, 01, ... 10, 11, etc. My solution was to check if minutes contained one character, if so, prepend a "0".
... + (date.getMinutes().toString().length == 1 ? "0" : "") + date.getMinutes().toString()

Zero padding in front using Numeral.js and Aurelia

I'm trying to build a basic Aurelia app.
Suppose I got a data where id = 1.
I can't seem to find a way to have 2 leading zero padding to my id using Numeral.js (http://numeraljs.com/).
I have this code:
<span>#${book.number | numberFormat:'000'}</span>
I was expecting an output like:
#001
but all I got was just
1
Ideally, it should go:
#001
#002
#003
...
#023
#024
#025
...
#135
#136
#137
etc
Does anyone know if this is possible ?
Thanks Stevies on Aurelia Gitter,
The solution is in the formatter class, we can go:
import numeral from 'numeral';
export class NumberFormatValueConverter {
toView(value) {
var output = new Intl.NumberFormat('en', {minimumIntegerDigits: 3, useGrouping: false}).format(value);
return output;
}
}

Can Typescript consume Existing AMD's?

Dojo 1.8 already defines AMD modules. For example you can do things like this:
require(["dojo/_base/lang"], function (lang) {
var ab = lang.mixin({a: 1}, {b: 2});
});
But how to I avoid getting an error when I attempt to import this module?
import lang = module ("dojo/_base/lang");
Is is possible?
You will need a typescript definition file for lang. Assuming that lang.d.ts exists in the same directory as lang.js this code:
import lang = module('dojo/_base/lang')
var ab = lang.mixin({a: 1}, {b: 2});
compiled with
tsc --module amd yourfile.ts
generates
define(["require", "exports", 'dojo/_base/lang'], function(require, exports, __lang__) {
var lang = __lang__;
var ab = lang.mixin({a: 1}, {b: 2});
}
If you don't want to have to match up the directory structures for whatever reason do this instead. Assuming lang.d.ts is in in a subdirectory called 3rd that is a sibling of test.ts.
test.ts:
///<reference path="3rd/lang.d.ts"/>
import lang = module('dojo/_base/lang');
var ab = lang.mixin({a: 1}, {b: 2});
3rd/lang.d.ts:
declare module 'dojo/_base/lang' {
...
}
generates the same as above.
You can normally load modules via the dojo loader, you don't have to use the import statement. But if you want you have to declare the module:
declare module "dojo/_base/lang" {
export function ...
export class ...
}