problem when wanting to return a null listtitle using
hello I've been trying return an empty listtitle using Firebase values the code worked fine before but when i try to add a container with border for my listitle the border still remain on screen I'm now to flutter and this my first time using if statement how do i make the border stops appearing enter image description here
Container(
child: ListView.builder(
shrinkWrap: true,
itemCount: 1,
itemBuilder: (context, index) {
if (widget.info.data() != null) {
return Container(
height: 200,
width: 200,
child: ListView(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
children: [
Container(
width: 200,
height: 150,
child: Padding(
padding: EdgeInsets.all(8.0),
child: ListTile(
title: Text(widget.info.data()['test']),
subtitle:
Text(widget.info.data()['test1']),
key: Key("${6}"),
onTap: () {
Clipboard.setData(new ClipboardData(
text: widget.info.data()['test']));
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text('text copied')));
}),
),
),
Container(
width: 150,
height: 150,
child: Padding(
padding: EdgeInsets.all(8.0),
child: Card(
color: Colors.white,
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.black, width: 3),
borderRadius: BorderRadius.circular(10),
),
child: ListTile(
title:
Text(widget.info.data()['test3']),
key: Key("${7}"),
subtitle:
Text(widget.info.data()['test4']),
onTap: () {
Clipboard.setData(new ClipboardData(
text:
widget.info.data()['test3']));
Scaffold.of(context).showSnackBar(
SnackBar(
content:
Text('text copied')));
}),
),
),
),
]),
);
} else {
return Container();
}
}),
),
See also questions close to this topic
-
Can I update the ejs template when I get a new snapshot from Firebase without refreshing (using nodejs,express and Firebase)?
I am using Node.js and express on my website and I get the data that I represent from firebase (real-time database). I render the ejs file. When I change the data in firebase I can see the updated data in console.log() but I can't see the updated data on the website without refreshing the page. Is there a way for me to update the ejs template when I get a new snapshot?
-
Error: The getter 'documents' isn't defined for the class 'QuerySnapshot'
I followed the same code as instructed by my instructor but I think due to update im getting this error attached in this image link :- Error documents
please suggest me what to use instead of this code.
-
TITLE of crash in firebase crashlytics is obfuscated (Stacktrace isn't obfuscated) (Android app)
We have an android app in production and we use the Firebase Crashlytics. On the Firebase Crashlytics page the crash stacktrace ISN'T obfuscated, only the TITLE is obfuscated. Loot at the screenshot http://prntscr.com/xm0g6s . What is the problem and how to fix that?
Dependencies I used:
implementation platform('com.google.firebase:firebase-bom:26.2.0') implementation 'com.google.firebase:firebase-messaging' implementation 'com.google.firebase:firebase-analytics' implementation 'com.google.firebase:firebase-crashlytics'
ProGuard is ON in the release build. My proguard-rules.pro file: https://gist.github.com/SergeyKharuk/f7bc59c328662fd39232c80bfd87eba8
-
Undismissible dialog in Flutter
What I want to achieve is to make dialog that's impossible to dismiss by clicking back button in android.
I know about
barrierDismissible
property ofshowDialog
method, but it only does what the name suggests. With it set tofalse
and clicking on back button the dialog still disappears.I also tried to wrap my code in
WillPopScope
to intercept back button click, butonWillPop
is never called if the dialog is shown. Maybe I messed up withcontext
or something, or there's another way to achieve this behavior? Any help is appreciated.I've modified the default counter app a bit to show at which stage my research is currently
void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; bool _isLocationWarningActive = false; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { // this is never called if the dialog is shown if (_isLocationWarningActive) return true; return false; }, child: Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: LocationChecker( isLocationWarningActive: _isLocationWarningActive, setIsLocationWarningActive: (value) { setState(() { _isLocationWarningActive = value; }); }, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ), ); } } class LocationChecker extends StatefulWidget { final bool isLocationWarningActive; final Function(bool) setIsLocationWarningActive; final Widget child; const LocationChecker({Key key, this.setIsLocationWarningActive, this.isLocationWarningActive, this.child}) : super(key: key); @override _LocationCheckerState createState() => _LocationCheckerState(); } class _LocationCheckerState extends State<LocationChecker> with WidgetsBindingObserver { @override void initState() { WidgetsBinding.instance.addObserver(this); super.initState(); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { print("state: $state"); if (state == AppLifecycleState.resumed && !_isCheckingLocation) { _showLocationSettingsAlertIfNeeded(); } } bool _isCheckingLocation = false; Future _showLocationSettingsAlertIfNeeded() async { if (!mounted) return; _isCheckingLocation = true; if (await checkLocationPermission) { if (widget.isLocationWarningActive) { widget.setIsLocationWarningActive(false); _isCheckingLocation = false; Navigator.of(context).pop(true); } } else if (!widget.isLocationWarningActive) { print("should show notification"); widget.setIsLocationWarningActive(true); await showDialog( context: context, barrierDismissible: false, builder: (BuildContext context) => OneActionDialog( title: "Location Settings", child: Text("Click OK to goto settings"), btnTitle: "OK", action: () { widget.setIsLocationWarningActive(false); _isCheckingLocation = false; SystemSetting.goto(SettingTarget.LOCATION); Navigator.of(context).pop(true); }, ), ); } } @override Widget build(BuildContext context) { return Container( child: widget.child, ); } } Future<bool> get checkLocationPermission async { ServiceStatus serviceStatus = await LocationPermissions().checkServiceStatus(); if (serviceStatus != ServiceStatus.enabled) return false; final access = await LocationPermissions().checkPermissionStatus(); switch (access) { case PermissionStatus.unknown: case PermissionStatus.denied: case PermissionStatus.restricted: final permission = await LocationPermissions().requestPermissions( permissionLevel: LocationPermissionLevel.locationAlways, ); if (permission == PermissionStatus.granted) { return true; } else { return false; } break; case PermissionStatus.granted: return true; break; default: return false; break; } }
-
Flutter - Navigator.pushReplacementNamed show the same page
I have a simple app that has a OnBoarding section and at the end I just want to replace the current screen with the home.
I have installed this package to avoid to recreate myself the onboarding logic and seems to work well, but can't figured out why at the end when I implement the
onDone
function it shows me the same screen.Here my main.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:sizer/sizer.dart'; // Application import './theme.dart'; import './routes.dart'; import './screens/home/home.dart'; import './screens/onboarding/onboarding.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); bool shoudShowOnboardingPage = sharedPreferences.getBool('shoudShowOnboardingPage') ?? true; runApp( MyApp( shouldShowOnBoardingScreen: shoudShowOnboardingPage, ), ); } class MyApp extends StatelessWidget { final bool shouldShowOnBoardingScreen; MyApp({ this.shouldShowOnBoardingScreen, }); @override Widget build(BuildContext context) { return LayoutBuilder(builder: (context, constraints) { return OrientationBuilder( builder: (context, orientation) { SizerUtil().init(constraints, orientation); return MaterialApp( debugShowCheckedModeBanner: false, title: 'My app', theme: themeData, home: shouldShowOnBoardingScreen ? OnBoardingScreen() : HomePageScreen(), onGenerateRoute: RouteGenerator.generateRoute, ); }, ); }); } }
Here my routes.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; // Application import './screens/home/home.dart'; import './screens/onboarding/onboarding.dart'; class RouteGenerator { static const String homePage = '/'; static const String onBoardingPage = '/onboarding'; RouteGenerator._(); static Route<dynamic> generateRoute(RouteSettings settings) { switch (settings.name) { case homePage: return MaterialPageRoute( builder: (_) => HomePageScreen(), ); case onBoardingPage: return MaterialPageRoute( builder: (_) => OnBoardingScreen(), ); default: throw FormatException('Route not found'); } } }
My onBoarding (the repository just define title, body and image for the pages):
import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:introduction_screen/introduction_screen.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:sizer/sizer.dart'; // Application import '../../repositories/onboarding/onboarding_repository.dart'; import '../../models/onboarding/onboarding_page.dart'; import '../../routes.dart'; class OnBoardingScreen extends StatelessWidget { final Future<SharedPreferences> _prefs = SharedPreferences.getInstance(); @override Widget build(BuildContext context) { OnBoardingRepository onBoardingRepository = OnBoardingRepository(); return Scaffold( body: IntroductionScreen( globalBackgroundColor: Colors.black, pages: List.generate( onBoardingRepository.pages.length, (index) => buildPageViewModel(onBoardingRepository.pages[index], context), ), showSkipButton: true, skip: Text( 'Salta', style: TextStyle( color: Colors.white, ), ), next: const Icon( Icons.arrow_forward, color: Colors.white, ), done: Container( padding: const EdgeInsets.symmetric( horizontal: 20, vertical: 6, ), decoration: BoxDecoration( color: Theme.of(context).primaryColor, border: Border.all( color: Theme.of(context).primaryColor, ), borderRadius: BorderRadius.all( Radius.circular(20), ), ), child: Text( 'Fine', style: TextStyle( color: Colors.white, ), ), ), onDone: () async { final SharedPreferences sharedPreferences = await _prefs; sharedPreferences.setBool('shoudShowOnboardingPage', false).then((_) { Navigator.of(context).pushReplacementNamed(RouteGenerator.homePage); }); }, dotsDecorator: DotsDecorator( activeColor: Theme.of(context).primaryColor, size: const Size.square(10.0), activeSize: const Size(20.0, 10.0), color: Colors.white, spacing: const EdgeInsets.symmetric(horizontal: 3.0), activeShape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(25.0), ), ), ), ); } PageViewModel buildPageViewModel( OnBoardingPage onBoardingPage, BuildContext context) { return PageViewModel( title: onBoardingPage.title, body: onBoardingPage.body, image: Padding( padding: EdgeInsets.only(top: 10.0.h), child: Center( child: SvgPicture.asset( onBoardingPage.image, height: 60.0.w, ), ), ), decoration: PageDecoration( titleTextStyle: TextStyle( fontSize: 16.0.sp, fontWeight: FontWeight.w700, color: Theme.of(context).primaryColor, ), bodyTextStyle: TextStyle(fontSize: 13.0.sp, color: Colors.white), ), ); } }
And here the home.dart
import 'package:flutter/material.dart'; class HomePageScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text('hello'), ), ); } }
The onboarding section works well, I can see the pages, navigate them. The problem is when I press the
done
button and invoke theonDone
function it shows again and again the onboarding screen from the beginning.
What I expect is to remove the onBoarding screen and replace it with the home just after I set the boolean value for myshoudShowOnboardingPage
setting.Here the piece of code that do not work as I expect:
onDone: () async { final SharedPreferences sharedPreferences = await _prefs; sharedPreferences.setBool('shoudShowOnboardingPage', false).then((_) { Navigator.of(context).pushReplacementNamed(RouteGenerator.homePage); }); },
What am I missing?
-
Time limit Exceeded in if-else
Following is a function which change the value of array according to conditions : 1.If the difference between the array element and the next multiple of 5 is less than 3, round up to the next multiple of 5. 2 If the value of array element is less than 38, no rounding occurs. Code :
vector gradingStudents(vector grades) {
int n = grades.size(); int i = 0; while(i<n) { if(grades.at(i)<38) { i++; } else if( (grades.at(i)+1) % 5==0 ) { grades.at(i) += 1; i++; } else if( (grades.at(i)+2) % 5 == 0) { grades.at(i) += 2 ; i++; } } return grades;
}
Hackerrank site saying " Time Limit Exceeded". I dont understand how can time limit exceeded when there is no loop (except the essential while loop). If I remove i++ from each if statement and put it outside all if statements then its working fine, but the no. of statements remain same. please help me out
-
How to chain several if conditions in php without error?
I know how to chain several
if's
in php in a row. I'm asking you because I have a mistake and I can't figure out where it comes from. I have a PHP code that allows me to query an API and retrieve a decoded PDF document depending on the user's country.It's almost 3 times the same block but depending on the client's country the PDF changes.
- When I test the code blocks individually I have no errors.
- When I put two in a row it works fine, but if I add the third block "
elseif
", although in my form I choose "United States
" the code never executes and I don't understand why. If I execute this third if only the code works well.
I put the braces to delimit my 3 blocks, so I don't know where it can come from... if someone can help me to know why the 3rd
elseif
never executes despite the condition being true ?<?php if ($_POST['adresse'][5] == "France"){ $PAYS = $_POST['adresse'][5]; $PAYS = "FR"; } elseif ($_POST['adresse'][5] == "Allemagne"){ $PAYS = $_POST['adresse'][5]; $PAYS = "DE"; } elseif ($_POST['adresse'][5] == "Suisse"){ $PAYS = $_POST['adresse'][5]; $PAYS = "CH"; } elseif ($_POST['adresse'][5] == "United States"){ $PAYS = $_POST['adresse'][5]; $PAYS = "US"; } if ( $PAYS == 'FR') //first if { // the soap operation which is called $action = 'euExpressRateBook_providerServices_ShipmentHandlingServices_Binder_createShipmentRequest'; // the xml input of the service $xmlrequest = '<?xml version="1.0" encoding="ISO-8859-1"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> .................... </ShipmentRequest> </soapenv:Body> </soapenv:Envelope>'; try { $options = array(); $options['wrapper'] = array( 'soap_version' => 'SOAP_1_1', 'encoding' => 'UTF-8', 'user_agent' => 'PHPSoapClient', // The exceptions option is a boolean value defining whether soap errors throw exceptions of type SoapFault. 'exceptions' => true, // The trace option enables tracing of request so faults can be backtraced. 'trace' => true ); $context = stream_context_create($options); // create the soapclient and invoke __doRequest method //WSDL URL is called on init $client = new \SoapClient($wsdlUrl, $options); //Here we call REQUEST URL $output = $client->__doRequest($xmlrequest, $requestUrl, $action, 1); } catch (SoapFault $fault) { var_dump($fault); echo "<h2>SOAP Fault!</h2><p>"; echo "FaultCode: {$fault->faultcode} <br/>"; echo "FaultString: {$fault->faultstring} <br/>"; echo("</p/>"); } if (is_soap_fault($output)) { echo "<h2>SOAP Fault!</h2><p>"; echo "FaultCode: {$output->faultcode} <br/>"; echo "FaultString: {$output->faultstring} <br/>"; } else { function multiSplit($string) { $output = array(); $cols = explode("<GraphicImage>", $string); foreach ($cols as $col) { $dashcols = explode("</GraphicImage>", $col); $output[] = $dashcols[0]; } return $output; } $DHL = multiSplit($output); $filename1 = uniqid(rand(), true) . '.txt'; $filename2 = uniqid(rand(), true) . '.pdf'; $file1 = "C:/wamp64/www/Dylan/SAV/API_label/TXT/$filename1"; file_put_contents($file1, print_r($DHL[1], true) . PHP_EOL, FILE_APPEND | LOCK_EX); $pdf_base64 = $file1; //Get File content from txt file $pdf_base64_handler = fopen($pdf_base64,'r'); $pdf_content = fread ($pdf_base64_handler,filesize($pdf_base64)); fclose ($pdf_base64_handler); //Decode pdf content $pdf_decoded = base64_decode ($pdf_content); //Write data back to pdf file $pdf = fopen ("C:/wamp64/www/Dylan/SAV/API_label/PDF/$filename2",'w'); fwrite ($pdf,$pdf_decoded); //close output file fclose ($pdf); // echo 'Done'; } } elseif ( $PAYS == 'DE' || 'BE') //Second if { // the soap operation which is called $action = 'euExpressRateBook_providerServices_ShipmentHandlingServices_Binder_createShipmentRequest'; // the xml input of the service $xmlrequest = '<?xml version="1.0" encoding="ISO-8859-1"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Header> <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="1"> <wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="UsernameToken-5"> <wsse:Username>'.$LOGIN.'</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">'.$PASSWORD.'</wsse:Password> </wsse:UsernameToken> </wsse:Security> </soapenv:Header> <soapenv:Body> <ShipmentRequest xmlns="http://scxgxtt.phx-dc.dhl.com/euExpressRateBook/ShipmentMsgRequest"> ................ </RequestedShipment> </ShipmentRequest> </soapenv:Body> </soapenv:Envelope>'; try { $options = array(); $options['wrapper'] = array( 'soap_version' => 'SOAP_1_1', 'encoding' => 'UTF-8', 'user_agent' => 'PHPSoapClient', // The exceptions option is a boolean value defining whether soap errors throw exceptions of type SoapFault. 'exceptions' => true, // The trace option enables tracing of request so faults can be backtraced. 'trace' => true ); $context = stream_context_create($options); // create the soapclient and invoke __doRequest method //WSDL URL is called on init $client = new \SoapClient($wsdlUrl, $options); //Here we call REQUEST URL $output = $client->__doRequest($xmlrequest, $requestUrl, $action, 1); } catch (SoapFault $fault) { var_dump($fault); echo "<h2>SOAP Fault!</h2><p>"; echo "FaultCode: {$fault->faultcode} <br/>"; echo "FaultString: {$fault->faultstring} <br/>"; echo("</p/>"); } if (is_soap_fault($output)) { echo "<h2>SOAP Fault!</h2><p>"; echo "FaultCode: {$output->faultcode} <br/>"; echo "FaultString: {$output->faultstring} <br/>"; } else { function multiSplit($string) { $output = array(); $cols = explode("<GraphicImage>", $string); foreach ($cols as $col) { $dashcols = explode("</GraphicImage>", $col); $output[] = $dashcols[0]; } return $output; } $DHL = multiSplit($output); $filename1 = uniqid(rand(), true) . '.txt'; $filename2 = uniqid(rand(), true) . '.pdf'; $file1 = "C:/wamp64/www/Dylan/SAV/API_label/TXT/$filename1"; file_put_contents($file1, print_r($DHL[1], true) . PHP_EOL, FILE_APPEND | LOCK_EX); $pdf_base64 = $file1; //Get File content from txt file $pdf_base64_handler = fopen($pdf_base64,'r'); $pdf_content = fread ($pdf_base64_handler,filesize($pdf_base64)); fclose ($pdf_base64_handler); //Decode pdf content $pdf_decoded = base64_decode ($pdf_content); //Write data back to pdf file $pdf = fopen ("C:/wamp64/www/Dylan/SAV/API_label/PDF/$filename2",'w'); fwrite ($pdf,$pdf_decoded); //close output file fclose ($pdf); // echo 'Done'; } } elseif ( $PAYS == 'US' || 'GB'|| 'NO'|| 'CH') //Third if { $xmlrequest = '<?xml version="1.0" encoding="ISO-8859-1"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> </soapenv:Header> ............................... </ShipmentRequest> </soapenv:Body> </soapenv:Envelope>'; try { $options = array(); $options['wrapper'] = array( 'soap_version' => 'SOAP_1_1', 'encoding' => 'UTF-8', 'user_agent' => 'PHPSoapClient', // The exceptions option is a boolean value defining whether soap errors throw exceptions of type SoapFault. 'exceptions' => true, // The trace option enables tracing of request so faults can be backtraced. 'trace' => true ); $context = stream_context_create($options); // create the soapclient and invoke __doRequest method //WSDL URL is called on init $client = new \SoapClient($wsdlUrl, $options); //Here we call REQUEST URL $output = $client->__doRequest($xmlrequest, $requestUrl, $action, 1); } catch (SoapFault $fault) { var_dump($fault); echo "<h2>SOAP Fault!</h2><p>"; echo "FaultCode: {$fault->faultcode} <br/>"; echo "FaultString: {$fault->faultstring} <br/>"; echo("</p/>"); } if (is_soap_fault($output)) { echo "<h2>SOAP Fault!</h2><p>"; echo "FaultCode: {$output->faultcode} <br/>"; echo "FaultString: {$output->faultstring} <br/>"; } else { function multiSplit($string) { $output = array(); $cols = explode("<GraphicImage>", $string); foreach ($cols as $col) { $dashcols = explode("</GraphicImage>", $col); $output[] = $dashcols[0]; } return $output; } function multiSplit2($string) { $output = array(); $cols = explode("<DocumentImage>", $string); foreach ($cols as $col) { $dashcols = explode("</DocumentImage>", $col); $output[] = $dashcols[0]; } return $output; } $DHL = multiSplit($output); $DHL2 = multiSplit2($output); $filename1 = uniqid(rand(), true) . '.txt'; $filename2 = uniqid(rand(), true) . '.pdf'; $filename3 = uniqid(rand(), true) . '.txt'; $filename4 = uniqid(rand(), true) . '.pdf'; $file1 = "C:/wamp64/www/Dylan/SAV/API_label/TXT/$filename1"; file_put_contents($file1, print_r($DHL[1], true) . PHP_EOL, FILE_APPEND | LOCK_EX); $file2 = "C:/wamp64/www/Dylan/SAV/API_label/TXT/$filename3"; file_put_contents($file2, print_r($DHL2[1], true) . PHP_EOL, FILE_APPEND | LOCK_EX); $pdf_base64 = $file1; //Get File content from txt file $pdf_base64_handler = fopen($pdf_base64,'r'); $pdf_content = fread ($pdf_base64_handler,filesize($pdf_base64)); fclose ($pdf_base64_handler); //Decode pdf content $pdf_decoded = base64_decode ($pdf_content); //Write data back to pdf file $pdf = fopen ("C:/wamp64/www/Dylan/SAV/API_label/PDF/$filename2",'w'); fwrite ($pdf,$pdf_decoded); //close output file fclose ($pdf); // echo 'Done'; $pdf_base642 = $file2; //Get File content from txt file $pdf_base64_handler = fopen($pdf_base642,'r'); $pdf_content = fread ($pdf_base64_handler,filesize($pdf_base642)); fclose ($pdf_base64_handler); //Decode pdf content $pdf_decoded = base64_decode ($pdf_content); //Write data back to pdf file $pdf2 = fopen ("C:/wamp64/www/Dylan/SAV/API_label/Commercial invoice/$filename4",'w'); fwrite ($pdf2,$pdf_decoded); //close output file fclose ($pdf2); } } ?>
-
JS: Test elements existence and tag name as a one liner
I am trying to find the correct a-tag within a DOM. For this I need to parse its direct neighbors:
let strongTags = document.querySelectorAll('div.entry p strong'); for (let i = 0; i < strongTags.length; i++) { if (strongTags[i].textContent.toLowerCase().match("size")) { let dbATag; if (strongTags[i].nextElementSibling) { if (strongTags[i].nextElementSibling.tagName == "A") { dbATag = strongTags[i].nextElementSibling; } else if (strongTags[i].nextElementSibling.nextElementSibling) { if (strongTags[i].nextElementSibling.nextElementSibling.tagName == "A") { dbATag = strongTags[i].nextElementSibling.nextElementSibling; } } } } }
As you can see, I don't know if the a tag is in nextElementSibling or in the second nextElementSibling. Theoretically there could be a third one, but I never saw it in the data. I'd like something like a querySelector('a') directly from the strongTags[i] position within the current parent. But that's another one of my don't knows.
My current main problem is that I can't test if strongTags[i].nextElementSibling exists and if tagName is A, like this:
if (strongTags[i].nextElementSibling && strongTags[i].nextElementSibling.tagName == "A").
Even though it doesn't exist, the interpreter still tries to test for tagName as well. This results in an error that stops further execution of my script. That's why I split it into two lines for now.
How can I solve this a bit more beautiful? :)
EDIT: I have no influence on DOM creation. I do page modification with Tampermonkey.
And I can not post the page itself. But I can post a part of DOM from the section if it helps:
<div id="content"> <div class="post"> <h1 id="post-1243629">Post-Header</h2> <div class="entry"> <p></p> <blockquote> <p></p> <p></p> </blockquote> <p><strong>Date: </strong>ddmmyyy / <strong>Format: </strong>$ / <strong>Optional strong tag: </strong>Data / <strong>Size: </strong>MB / <strong>Db:</strong><a href="">xyz</a> <strong>Optional strong tag: </strong>Data / </p> <p><strong></strong><br /> <strong></strong> <a href=""></a><br /> <span> <strong></strong> <a href=""></a><br /> </span> <span id=""> <strong></strong> <a href=""></a><br /> <strong></strong> <a href=""></a><br /> <strong></strong> <a href=""></a><br /> </span> <strong></strong> </p> </div> </div> </div>