Nativescript : camera photo asset with nativescript-ocr - ocr

I'm trying to take a picture with the nativescript camera module and to run
the nativescript-ocr module (https://github.com/EddyVerbruggen/nativescript-ocr) on it .
Here is my code :
public saveToGallery: boolean = true;
public keepAspectRatio: boolean = true;
public width: number = 300;
public height: number = 300;
private ocr: OCR;
constructor() {
this.ocr = new OCR();
}
ngOnInit(): void {
}
onTakePhoto() {
let options = {
width: this.width,
height: this.height,
keepAspectRatio: this.keepAspectRatio,
saveToGallery: this.saveToGallery
};
takePicture(options).
then((imageAsset) => {
console.log("Result is an image asset instance");
let img: ImageSource = new ImageSource();
img.fromAsset(imageAsset).then((success) => {
if (success) {
this.ocr.retrieveText({
image: img,
whitelist: "ABCDEF",
blacklist: "0123456789",
onProgress: (percentage: number) => {
console.log(`Decoding progress: ${percentage}%`);
}
}).then(
(result: RetrieveTextResult) => {
console.log(`Result: ${result.text}`);
}, (error: string) => {
console.log(`Error: ${error}`);
})
}
});
}).catch((err) => {
console.log("Error -> " + err.message);
});
}
onRequestPermissions() {
requestPermissions();
}
}
Camera plugin works fine, takes and saves a picture, but when i'm running onTakePhoto i get this error message :
"Error in ocr.retrieveText: Error: java.lang.IllegalArgumentException: Data path does not exist!"
i'm not sure to use the .fromAsset the right way,
but i try a lot of thing to solve this problem
what i'm doing wrong?
Resolve : i didn't create corectly my tesseract/tessdata folder

Related

Pass JSON Object with REST

I have a rest-api-service with the following call to a REST method that returns a very complex JSON object in the body of its response. This code is from the rest-api-service.ts file.
getLocalObjectsFromREST(): Observable<LocalObjects> {
return this.http.get<LocalObjects>(this.apiURL + '/api/GetLocalObjects')
.pipe(
retry(1),
catchError(this.handleError)
)
}
handleError(error: { error: { message: string; }; status: any; message: any; }) {
let errorMessage = '';
if(error.error instanceof ErrorEvent) {
// Get client-side error
errorMessage = error.error.message;
} else {
// Get server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(errorMessage);
}
I am attempting to grab that response in a component with the following that is in my app.component.ts file:
export class AppComponent implements OnInit {
_restApi: RestApiService | undefined;
_localObjects: LocalObjects | undefined;
contructor(restApi: RestApiService) {
this._restApi = restApi;
}
ngOnInit() {
this.getLocalObjectsFromService();
console.log("Main object has a name of: " + this._localObjects?.mainObject.objName)
console.log("Data Returned is " + this._localObjects);
}
getLocalObjectsFromService() {
return this._restApi?.getLocalObjectsFromREST().subscribe((data: {}) => {
this._localObjects = <LocalObjects> data;
})
}
}
I am receiving no errors and yet the console logs are showing undefined return values.
Can somebody please help me out?
ngOnInit() {
this.getLocalObjectsFromREST();
console.log("Main object has a name of: " + this._localObjects?.mainObject.objName)
console.log("Data Returned is " + this._localObjects);
}
getLocalObjectsFromService() {
return this._restApi?.getLocalObjectsFromREST().subscribe((data: {}) => {
this._localObjects = <LocalObjects> data;
})
}
In your ngOnInit() you are not calling your getLocalObjectsFromService() function and as you are not adding a subscribe() after getLocalObjectsFromREST you are not seeing any data...

Flutter: Trying to access location data in background using location and workManager plugin

Issue in brief:
trying to access location data of the user in background using location and workManager plugin.
Currently with the code mentioned below i am able to access the location information if the application is open, Since callbackDispatcher is a top level function i am not able to call the location plugin.
location plugin works when a call is done inside of the class. I am trying a way to access _getlocation() from callbackDispatcher, I am getting PlatformException(NO_ACTIVITY).
Things I have tried:
found few other guys facing similar issue here, here and here
Tired all these steps and no luck.
import 'package:flutter/material.dart';
import 'package:location/location.dart';
import 'package:workmanager/workmanager.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
Location location = new Location();
void callbackDispatcher() {
Workmanager.executeTask((task, inputData) {
if (task == "simplePeriodicTask") {
print("task working");
_getLocation();
}
return Future.value(true);
});
}
LocationData _location;
String _error;
double lat;
double long;
_getLocation() async {
_error = null;
try {
var _locationResult = await location.getLocation();
_location = _locationResult;
lat = _location.latitude;
long = _location.longitude;
} on PlatformException catch (err) {
_error = err.code;
}
if (_error == null) {
// _check();
print(lat);
} else {
//dialog
print(_error);
}
}
class _MyAppState extends State<MyApp> {
#override
void initState() {
super.initState();
Workmanager.initialize(
callbackDispatcher, // The top level function, aka callbackDispatcher
isInDebugMode:
true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks
);
_checkPermissions();
}
// Permission for location
PermissionStatus _permissionGranted;
// final Location location = new Location();
_checkPermissions() async {
PermissionStatus permissionGrantedResult = await location.hasPermission();
setState(() {
_permissionGranted = permissionGrantedResult;
});
if (_permissionGranted == PermissionStatus.DENIED) {
_requestPermission();
} else if (_permissionGranted == PermissionStatus.GRANTED) {
_checkService();
}
}
_requestPermission() async {
if (_permissionGranted != PermissionStatus.GRANTED) {
PermissionStatus permissionRequestedResult =
await location.requestPermission();
setState(() {
_permissionGranted = permissionRequestedResult;
});
if (permissionRequestedResult != PermissionStatus.GRANTED) {
return;
} else if (permissionRequestedResult == PermissionStatus.GRANTED) {
_checkService();
}
}
}
//Permission ends
//services enabled function
bool _serviceEnabled;
_checkService() async {
bool serviceEnabledResult = await location.serviceEnabled();
setState(() {
_serviceEnabled = serviceEnabledResult;
});
if (_serviceEnabled == false) {
_requestService();
} else {
// _getLocation();
}
}
_requestService() async {
if (_serviceEnabled == null || !_serviceEnabled) {
bool serviceRequestedResult = await location.requestService();
setState(() {
_serviceEnabled = serviceRequestedResult;
});
if (!serviceRequestedResult) {
return;
} else {
// _getLocation();
}
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dart'),
),
body: Column(children: <Widget>[
RaisedButton(
child: Text('get Location'),
onPressed: () {
Workmanager.registerPeriodicTask(
"2",
"simplePeriodicTask",
// When no frequency is provided the default 15 minutes is set.
// Minimum frequency is 15 min. Android will automatically change your frequency to 15 min if you have configured a lower frequency.
);
print('task registered');
_getLocation();
}),
RaisedButton(
onPressed: () async {
await Workmanager.cancelAll();
print('task Destroyd');
},
child: Text("cancel"),
),
]),
);
}
}
Trying to access _getlocation() from callbackDispatcher();
Any help on this is greatly appreciated.
I was facing same issue recently. location package not work with WorkManager plugin, I dont know the reason but here is my solution;
/// This Function calls only from WorkManager
/// Used GeoLocator instead of Location package due to PlatformException(NO_ACTIVITY) error throwing
Future<String> getPlaceMarkLocationWhileAppOff() async {
Geolocator geoLocator = Geolocator()..forceAndroidLocationManager = true;
var _position = await geoLocator.getCurrentPosition(
// desiredAccuracy: LocationAccuracy.high,
);
var value = await geoLocator.placemarkFromCoordinates(_position.latitude, _position.longitude);
return _placeMark = "${value.first.subLocality}\n${value.first.subAdministrativeArea}";
}
Used Geolocator package when app offline and used Location package when app online..
I hope it will help..

How to fix DOMException error in google chrome?

I work with sounds in a browser game. I wrote sound manager. everything works fine, but not in Google chrome. I handled the error "uncaught (in promise) domexception", after the sounds were played in 50 percent of cases, in other cases it returns the error DOMException. What could be the problem?
export class AudioFile{
private audio: HTMLAudioElement;
private fileMP3: string;
private fileOGG: string;
private volume = 1;
private loop = false;
constructor(MP3:string, OGG:string) {
this.audio = new Audio();
this.fileMP3 = MP3;
this.fileOGG = OGG;
this.audio.canPlayType('audio/mpeg') ? this.audio.src = this.fileMP3 : this.audio.src = this.fileOGG;
this.audio.load();
this.audio.volume = this.volume;
this.audio.loop = this.loop;
}
public play() {
this.audio.currentTime = 0;
const playPromise = this.audio.play();
if (playPromise !== undefined) {
playPromise.then(_ => {
})
.catch(error => {
console.log(error);
});
}
}
public stop() {
this.audio.pause();
}
}
``````````````sound manager`````````````
export class SoundManager {
private sounds = new Map();
private static _soundManager: SoundManager;
constructor(){
if (SoundManager._soundManager) {
throw new Error("Instantiation failed: "+
"use Singleton.getInstance() instead of new.");
}
SoundManager._soundManager = this;
}
public static get instance(): SoundManager {
if (this._soundManager)
return this._soundManager;
else
return this._soundManager = new SoundManager();
}
preload() {
const pathMP3 = SoundConfig.PATHMP3;
const pathOGG = SoundConfig.PATHOGG;
for (const item in SoundConfig.SOUNDS) {
const name = SoundConfig.SOUNDS[item].NAME;
this.sounds.set(name, new AudioFile(pathMP3 + name + '.mp3', pathOGG + name + '.ogg'));
}
}
getSound(id: string): AudioFile {
return this.sounds.get(id);
}
}
Thank you spendr.
error: DOMException
code: 0
message: "play() failed because the user didn't interact with the document first.
Game runs through the iframe and I was needed to add a feature policy for autoplay.
<iframe src="..." allow="autoplay">
The article that helped me in solving the problem

nested Mat-dialogBox closing issue

I have one parent raster component from where I am opening my first dialog box and from that dialog box component, i am opening second dialog box. I want to pass data from last dialog box to my parent raster and meanwhile need to close all the dialog boxes but I am not able to get data from second dialog box to first dialog box and because of this, i dont get data in raster component.
Can someone help me to solve this? I have tried to do all the things but still getting undefined. Any kind of help would be nice.
Kindly find my below code.
raster.component.ts
openDialogbox(value): void {
this.emptyTile = value;
const dialogRef = this.dialog.open(AddNewFlyerComponent, {
width: '100em',
height: '50em',
data: {
flyerArray: this.flyers,
emptyPosition: this.emptyTile,
page: this.flyers[0].Seite,
year: this.flyers[0].Jahr,
week: this.flyers[0].KW,
}
});
dialogRef.afterClosed().subscribe(result => {
console.log('The raster dialog was closed', result);
});
}
AddNewFlyerComponent.ts
openDialog(werbenumber): void {
const dialogRef = this.dialog.open(CreateNewFlyerComponent, {
width: '100em',
height: '50em',
data: {
flyerArray: this.data.flyerArray,
werbenumber: werbenumber,
emptyTile: this.data.emptyPosition,
page: this.data.page,
week: this.data.week,
year: this.data.year
}
});
dialogRef.afterClosed().subscribe(result => {
console.log('The 1st dialog was closed', result); // getting undefined
});
}
CreateNewFlyerComponent.ts
addFlyerToEmptyPosition(werbedata: WerbeData) {
const newFlyer = {
ArtNr: this.werbedata.ArtNr,
Filiale: this.werbedata.FILIALE,
Jahr: this.data.flyerArray[0].Jahr,
KW: this.data.flyerArray[0].KW,
Pos: this.data.emptyTile,
Raster: this.data.flyerArray[0].Raster,
Seite: this.data.flyerArray[0].Seite,
WERBE_NR: this.werbedata.WERBE_NR,
EUR_VK: this.a,
EUR_VK_Einheit: this.b,
VK_Einheit: this.c
};
this.flyerHammService.createNewFlyer(newFlyer)
.then(
(response: any) => {
this.returnFlyer = response.data[0]; // This returnFlyer, I want to pass
this.matSnackBar.open('Neuer Flyer wurde erstellt', 'Undo', {
duration: 3000
});
}
).catch(
error => console.log(error)
);
}
CreateNewFlyerComponent.ts
<button mat-dialog-close mat-raised-button [color]="'success'" [mat-dialog-close]="returnFlyer" (click)="addFlyerToEmptyPosition(werbedata)">
{{ 'SPEICHERN' }}
<mat-icon>save</mat-icon>
</button>
Use the same data object for both dialogs. Instead of creating a new object, update the original data object with additional data and pass it into the second dialog:
AddNewFlyerComponent.ts
openDialog(werbenumber): void {
this.data.emptyTile = this.data.emptyPosition; // or was that a typo?
this.data.werbenumber = werbenumber; // or use Object.defineProperty()
const dialogRef = this.dialog.open(CreateNewFlyerComponent, {
width: '100em',
height: '50em',
this.data
});
dialogRef.afterClosed().subscribe(result => {
console.log('The 1st dialog was closed', result); // getting undefined
});
}
To pass the data back to raster, use the same approach:
raster.component.ts
data;
openDialogbox(value): void {
this.emptyTile = value;
this.data = {
flyerArray: this.flyers,
emptyPosition: this.emptyTile,
page: this.flyers[0].Seite,
year: this.flyers[0].Jahr,
week: this.flyers[0].KW,
}
const dialogRef = this.dialog.open(AddNewFlyerComponent, {
width: '100em',
height: '50em',
data: this.data
});
dialogRef.afterClosed().subscribe(result => {
console.log('The raster dialog was closed', result);
});
}

Delete row data from Firebase

I want to delete one clicked row from Firebase in my smart table. I am using Angular 4.
The smart table code:
<ng2-smart-table [settings]="settings" [source]="bicycleData"
(deleteConfirm)="onDeleteConfirm($event)">
</ng2-smart-table>
My constructor component code:
constructor(
db: AngularFireDatabase, ) {
this.bicyclesList = db.list('bicycle-list')
.snapshotChanges()
.map(changes => {
return changes.map(c => ({
key: c.payload.key,
...c.payload.val()
}))
});
this.bicyclesList.subscribe((data) => {
this.bicycleData = data;
});
}
and component.ts code:
settings = {
delete : {
deleteButtonContent: '<i class="nb-trash"></i>',
confirmDelete: true,
},
}
onDeleteConfirm() function and deleteEnquiry function in service:
onDeleteConfirm(event) {
console.log(event.data);
if (window.confirm('Are you sure you want to delete?')) {
this.deleteEnquiry(event.data);
event.confirm.resolve();
} else {
event.confirm.reject();
}
}
deleteEnquiry(data) {
console.log(data.$key);
this.db.list(`bicycle-list${data.$key}`).remove(data);
}
But it keeps showing me the following error in console:
ERROR TypeError: Cannot read property 'list' of undefined
How can I fix this error ?
Looks like an error in deleteEnquiry.
According to the docs is should be:
deleteEnquiry(data) {
console.log(data.$key);
this.db.list('bicycle-list').remove(data.$key);
}