Friday 31 May 2019

Android - GlSurfaceView in Fragment is running twice at the same time

I have an android app that uses a GlSurfaceView to render a 3D fullscreen scene inside a fragment. I have noticed in the profiler, that the GlSurfaceView is actually running twice (in two threads), hogging resources and tanking the FPS. I have confirmed the issue by rendering the same OpenGL scene (using the same Renderer implementation) to a live wallpaper and profiling it, which only runs it once.

Am I doing anything wrong here?


The code is as follows:

MySurfaceView

class MySurfaceView(ctx: Context): GLSurfaceView(ctx)
{
    init
    {
        setEGLContextClientVersion(3)
        preserveEGLContextOnPause = true
        setRenderer( /* instantiating the renderer class */ )
    }
}

OpenGLFragment

class OpenGLFragment: Fragment()
{
    private lateinit var glView: GLSurfaceView

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View?
    {
        this.glView = MySurfaceView(this.activity)
        return this.glView
    }
}

MainActivity

class MainActivity : FragmentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val fm = supportFragmentManager
        for (i in 0 until fm.getBackStackEntryCount()) {
            fm.popBackStack()
        }

        supportFragmentManager.beginTransaction().add(R.id.main_container, OpenGLFragment())
                    .addToBackStack(null).commit()
    }

}



from Android - GlSurfaceView in Fragment is running twice at the same time

Sending email from own server to the internets

I have set up an email server on my host. It's basically a SMTP server that listens on port 25.

const recvServer = new SMTPServer({
  requireTLS: true,
  authOptional: true,
  logger: true,      
  onConnect(session, callback) {
    return callback();
  },

  onMailFrom(address, session, callback) {
    console.log('from', address, session);
    return callback();
  },    

  onData(stream, session, callback) {
    console.log('new msg');
    let message = '';
    stream.on('data', chunk => {
      message += chunk;
    });

    stream.on('end', () => {

      callback(null, 'Message queued');
      simpleParser(message)
        .then(parsed => {
          console.log(parsed);
          // here I wish to forward the message to outside gmail addresses
        })
        .catch(err => {
          console.log(ee)
        });

    });
  }    
});

recvServer.listen(25);

recvServer.on('error', err => {
  console.log(err.message);
});

It works fine for receiving emails from outside, like gmail etc.

But I want to be able to send emails outside also, or forward emails that I receive to some gmail addresses.

I know that I can do that using Gmail SMTP servers, but then I need an gmail account and password.

I want to be able to send email with my own server, just like yahoo sends mail to gmail using their own server not gmail accounts :)



from Sending email from own server to the internets

How to represent complex POST data in python for requests

I'm trying to automate a web form. The payload when I actually run the query in Chrome looks like this on the inspect window...

    data: [{"property":"TimeQuick","value":"Active"},{"property":"TimeQuickDurationOptions","value":3},{"property":"TimeQuickStartDate","value":"05/15/2019 00:00:00"},{"property":"TimeQuickEndDate","value":"05/15/2019 23:59:59"},{"property":"ProviderCode","value":["FPL"]},{"property":"SellerCode","value":[""]},{"property":"Ref","value":""},{"property":"POR","value":["SOCO"]},{"property":"POD","value":["FPC"]},{"property":"Path","value":""},{"property":"ServiceIncrement","value":["DAILY"]},{"property":"TSClass","value":[""]},{"property":"TSType","value":[""]},{"property":"TSWindow","value":""},{"property":"TSPeriod","value":""},{"property":"TSSubClass","value":""},{"property":"Time","value":"Active"},{"property":"TimeDurationOptions","value":3},{"property":"TimeStartDate","value":"05/15/2019 00:00:00"},{"property":"TimeEndDate","value":"05/15/2019 23:59:59"},{"property":"ShowActiveData","value":true},{"property":"DaylightSavings","value":false}]
    sort: [{"property":"TOL","direction":"DESC","root":"data"}]
    pagingEnabled: 1
    page: 1
    limit: 50

I tried to represent that as a python variable like this

    datareq = [
             ('data', 
              {'property':'TimeQuick', 'value':'Active'},
              {"property":"TimeQuickDurationOptions","value":'3'},
              {"property":"TimeQuickStartDate","value":"05/15/2019 00:00:00"},
              {"property":"TimeQuickEndDate","value":"05/15/2019 23:59:59"},
              {"property":"ProviderCode","value":["FPL"]},
              {"property":"SellerCode","value":[""]},
              {"property":"Ref","value":""},
              {"property":"POR","value":["SOCO"]},
              {"property":"POD","value":["FPC"]},
              {"property":"Path","value":""},
              {"property":"ServiceIncrement","value":["DAILY"]},
              {"property":"TSClass","value":[""]},
              {"property":"TSType","value":[""]},
              {"property":"TSWindow","value":""},
              {"property":"TSPeriod","value":""},
              {"property":"TSSubClass","value":""},
              {"property":"Time","value":"Active"},
              {"property":"TimeDurationOptions","value":3},
              {"property":"TimeStartDate","value":"05/15/2019 00:00:00"},
              {"property":"TimeEndDate","value":"05/15/2019 23:59:59"},
              {"property":"ShowActiveData","value":'true'},
              {"property":"DaylightSavings","value":'false'}
              ),
             ('sort',
              {"property":"TOL","direction":"DESC","root":"data"}
              ),
             ('pagingEnabled', 1),
             ('limit', 50)

             ]

When I ran s.post(myurl, data=datareq, cert=mycerts) I got the following error:

    Traceback (most recent call last):

      File "<ipython-input-78-37ee269ebbce>", line 1, in <module>
        logblah=s.post(myurl, data= datareq, cert=mycerts)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\sessions.py", line 555, in post
        return self.request('POST', url, data=data, json=json, **kwargs)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\sessions.py", line 494, in request
        prep = self.prepare_request(req)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\sessions.py", line 437, in prepare_request
        hooks=merge_hooks(request.hooks, self.hooks),

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\models.py", line 308, in prepare
        self.prepare_body(data, files, json)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\models.py", line 499, in prepare_body
        body = self._encode_params(data)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\models.py", line 97, in _encode_params
        for k, vs in to_key_val_list(data):

    ValueError: too many values to unpack (expected 2)

I'm assuming the problem is in the way I've structured my datareq variable. What would be the proper way to make that POST?

Edit/Update: I've tried each of Alex and Ivan's suggestions but neither work. They each give me a cryptic message from the server that success=false. If I try them with json=datareq instead of data=datareq then I get a response from the server with 0 results even though it should have many so it seems like that is getting closer but still not all the way.



from How to represent complex POST data in python for requests

CamcorderProfile.videoCodec returning wrong value

According to the docs, you can use CamcorderProfile to get the devices default video codec format, then set it to MediaRecorder, like this:

CamcorderProfile mProfile = CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_HIGH);

//

mMediaRecorder.setVideoEncoder(mProfile.videoCodec);

But for some reason it is returning the wrong format.

I'm using the CameraView library and in the FullVideoRecorder class the following is defined:

switch (mResult.getVideoCodec()) {
    case H_263: mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263); break;
    case H_264: mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); break;
    case DEVICE_DEFAULT: mMediaRecorder.setVideoEncoder(mProfile.videoCodec); break;
} 

The device I'm experiencing the issue with works perfectly fine when I set the video encoder to H_263, but for some reason, when I set it to default it crashes - In this case default means that CamcorderProfile should select the devices default video codec format.


My question:

Is there any reason why CamcorderProfile.videoCodec would return the wrong value and how can this be resolved?


Edit - adding more information

I implemented the following to make sure if CamcoderProfile is returning the wrong value:

//In onCreate
CamcorderProfile camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);

//getVideoCodec method below
String profileCodec = getVideoCodec(camcorderProfile.videoCodec);    

//Log the result I get
Log.e("Video Codec =", profileCodec);


private String getVideoCodec(int videoCodec){
    switch(videoCodec){
        case MediaRecorder.VideoEncoder.H263:
            return "H263";
        case MediaRecorder.VideoEncoder.H264:
            return "H264";
        case MediaRecorder.VideoEncoder.MPEG_4_SP:
            return "MPEG_4_SP";
        case MediaRecorder.VideoEncoder.DEFAULT:
            return "DEFAULT";
        default:
            return "unknown";
    }
}

In my log I get Video Codec = H264, but this is incorrect, it should return Video Codec = H263.


If I pass the following to MediaRecorder, it works perfectly:

mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);

but not when I set any of the following:

mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
mMediaRecorder.setVideoEncoder(mProfile.videoCodec);



from CamcorderProfile.videoCodec returning wrong value

jsPDF doesn't work in Chrome, only Firefox & Safari

I'm trying to export an application to a PDF using jsPDF. After browsing around the web, grabbing a line of code here, a section there - I have managed to get it working... somewhat.

It works in Firefox & Safari, but not in Chrome.

JS-Files used (from jsPDF). Perhaps overkill. Along with Jquery.

    <script type="text/javascript" src="PDF/standard_fonts_metrics.js"></script> 
    <script type="text/javascript" src="PDF/split_text_to_size.js"></script>               
    <script type="text/javascript" src="PDF/from_html.js"></script>
    <script type="text/javascript" src="PDF/addhtml.js"></script>               
    <script type="text/javascript" src="PDF/addimage.js"></script>

The code I'm using is this:

<script type="text/javascript">
function demoFromHTML() {
  $('#listAreaPDF').css("display", "block");

  var pdf = new jsPDF('p', 'pt', 'letter');
  // source can be HTML-formatted string, or a reference
  // to an actual DOM element from which the text will be scraped.
  source = $('#listAreaPDF')[0];

  pdf.setFontSize(24);
  pdf.text(35, 40, "PDF Title here");

  pdf.setFontSize(10);
  pdf.text(500, 40, "Company Name AB");

  // we support special element handlers. Register them with jQuery-style 
  // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
  // There is no support for any other type of selectors 
  // (class, of compound) at this time.
  specialElementHandlers = {
    // element with id of "bypass" - jQuery style selector
    '#bypassme': function (element, renderer) {
      // true = "handled elsewhere, bypass text extraction"
      return true
    }
  };
  margins = {
    top: 80,
    bottom: 60,
    left: 40,
    width: 522
  };


  // all coords and widths are in jsPDF instance's declared units
  // 'inches' in this case
  pdf.fromHTML(
    source, // HTML string or DOM elem ref.
    margins.left, // x coord
    margins.top, {// y coord
      'width': margins.width, // max width of content on PDF
      'elementHandlers': specialElementHandlers
    },
    function (dispose) {
      html2canvas($("#presentationArea"), {
        onrendered: function (canvas) {
          var imgData = canvas.toDataURL(
            'image/png');

          pdf.addImage(imgData, 'PNG', 20, 300);
          pdf.save('Test.pdf');
        }
      });
      // dispose: object with X, Y of the last line add to the PDF 
      // this allow the insertion of new lines after html
      // pdf.save('Test.pdf');
    },
    margins
  );
  $('#listAreaPDF').css("display", "none");
}
</script>

Credit for the code found here. With few small changes to suit my application, I have added a connection to html2canvas to lift an image out of my application and placing it into the PDF. Which actually works OK - in Safari and Firefox.

When clicking and activating this function in Chrome I dont even recieve a blank PDF, I get nothing. Not even a pop-up or page generated.

What might be the reason Firefox&Safari works but not Chrome? I have not yet tried Internet Explorer, but I'm not holding my breath. Should you know a way for that to work I'm all for it.

Cheers for any help or suggestions you might provide.



from jsPDF doesn't work in Chrome, only Firefox & Safari

Symbol$CompletionFailure: class file for ActivityDeparturesBinding not found

I have a separate Android library in a separate project for an Android app. However I link the library directly (referencing the library module directly by path or the generated AAR) I get the following error:

A problem was found with the configuration of task ':app:kaptDevelopDebugKotlin'.
> Cannot write to file '/home/m0skit0/Repos/repo/app-android/app/build/intermediates/data-binding/develop/debug/bundle-bin' specified for property 'dataBindingArtifactOutputDir' as it is a directory.

e: error: cannot access ActivityDeparturesBinding
  class file for com.blablabla.databinding.ActivityDeparturesBinding not found
  Consult the following stack trace for details.
  com.sun.tools.javac.code.Symbol$CompletionFailure: class file for com.blablabla.databinding.ActivityDeparturesBinding not found

* What went wrong:
Execution failed for task ':app:kaptDevelopDebugKotlin'.

This shows just after the task :app:transformDataBindingWithDataBindingMergeArtifactsForDevelopDebug

However the class does exist, with full canonical name. It belongs to the the library and it is correctly auto generated (without any errors) by Android's Data Binding processor on both projects. The library compiles correctly on its own. There's no further stacktrace even if the compilation is run with --stacktrace.

I have tried linking the library with compile, implementation and api, all with the same result.

Gradle version is 4.4.


UPDATE:

Updating to Gradle 5 did not solve the problem. Renaming the XML did not solve the problem.

I've also found that the error happens only when I reference the ActivityDeparturesBinding class in my code, even if the part where it is referenced is never actually called. Only importing it without referencing it does not cause the error.


UPDATE2:

This is the activity that uses the layout:

class DeparturesActivity : BaseVinPlateActivity<DeparturesViewModel, ActivityDeparturesBinding>() {

    companion object {
        fun getStartIntent(context: Context) = Intent(context, DeparturesActivity::class.java)
    }

    @Inject
    override lateinit var viewModel: DeparturesViewModel

    override val layout: Int = R.layout.activity_departures

    override fun injectThis(component: ActivityComponent) {
        component.inject(this)
    }

    override fun getToolbarTitleId(): Int = R.string.departures_title

    override fun initializeDataBindings(dataBinding: ActivityDeparturesBinding) {
        dataBinding.viewmodel = viewModel
    }
}

abstract class BaseVinPlateActivity<T: BaseVinPlateViewModel, U: ViewDataBinding> : CompoundsBaseActivity()  {

    protected abstract var viewModel: T
    protected abstract val layout: Int

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == BARCODE_RESULT_CODE_ACTIVITY && resultCode == Activity.RESULT_OK) {
            val barcodeResult = data?.getStringExtra(BARCODE_RESULT_ACTIVITY)
            viewModel.setBarcodeResult(barcodeResult)
        }
    }

    override fun initializeView() {
        super.initializeView()
        val dataBinding = inflateDataBinding<U>(layout)
        initializeDataBindings(dataBinding)
        with (viewModel) {
            setBindValidator(Validator(dataBinding))
            loadData()
        }
    }

    protected abstract fun initializeDataBindings(dataBinding: U)
}

If I remove the initializeDataBindings() function, the error is gone. Note that commenting only the body of the function is not enough, I had to remove the whole function.

This smells like a compiler/tools bug.



from Symbol$CompletionFailure: class file for ActivityDeparturesBinding not found

Azure spatial anchors integration issues. Missing NativeLibrary implementations

I've been tinkering with Azure's spatial anchors API. I followed the docs and examples provided by Microsoft without many issues until I tried to make my own project from it. When I try to run a custom project using the Spatial anchors API it crashes looking for some functions that should be provided by the libraries specified in the gradle. The error log says this:

2019-05-28 10:32:10.642 28982-28982/com.azurelib.azureanchorsclean E/AndroidRuntime: FATAL EXCEPTION: main Process: com.azurelib.azureanchorsclean, PID: 28982 java.lang.UnsatisfiedLinkError: No implementation found for com.microsoft.azure.spatialanchors.status com.microsoft.azure.spatialanchors.NativeLibrary.ssc_cloud_spatial_anchor_session_create(com.microsoft.azure.spatialanchors.Out) (tried Java_com_microsoft_azure_spatialanchors_NativeLibrary_ssc_1cloud_1spatial_1anchor_1session_1create and Java_com_microsoft_azure_spatialanchors_NativeLibrary_ssc_1cloud_1spatial_1anchor_1session_1create__Lcom_microsoft_azure_spatialanchors_Out_2) at com.microsoft.azure.spatialanchors.NativeLibrary.ssc_cloud_spatial_anchor_session_create(Native Method) ...

The relevant ssc_cloud... functions can be found in the spatialanchors_java dependency specified in the gradle build:enter image description here

For the cloud session, I start a new activity in my MainActivity's onResume():

@Override
protected void onResume(){
    super.onResume();
    Intent intent = new Intent(this, AzureSpatialAnchorsActivity.class);
    intent.putExtra("BasicDemo", true);
    startActivity(intent);
}

And on AzureSpatialAnchorsActivity I create the ArCore Session and start the anchor manager:

    @Override
    protected void onResume() {
        super.onResume();

        if (session == null) {
            try {
                ...
                // Create the session.
                session = new Session(/* context= */ this);

            ... //Required catch statements
            } catch (Exception e) {
                message = "Failed to create AR session";
                exception = e;
            }
        }


        try {
            session.resume();
            startNewSession();
        } catch (CameraNotAvailableException e) {
            ...
        }
    }

    private void startNewSession() {
        destroySession();

        cloudAnchorManager = new AzureSpatialAnchorsManager(session);
        cloudAnchorManager.addAnchorLocatedListener(this::onAnchorLocated);
        cloudAnchorManager.addLocateAnchorsCompletedListener(this::onLocateAnchorsCompleted);
        cloudAnchorManager.addSessionUpdatedListener(this::onSessionUpdated);
        cloudAnchorManager.start();
    }

The error happens because when I try to create a CloudSpatialAnchorSession object

public AzureSpatialAnchorsManager(Session arCoreSession) {
    spatialAnchorsSession = new CloudSpatialAnchorSession();
    ...
}

the constructor calls a function from NativeLibrary

public CloudSpatialAnchorSession() {
    Out<Long> result_handle = new Out();
    status resultStatus = NativeLibrary.ssc_cloud_spatial_anchor_session_create(result_handle);
    this.handle = (Long)result_handle.value;
    NativeLibraryHelpers.checkStatus(this.handle, resultStatus);
    CookieTracker.add(this);
}

The problem seems to be that what I previously showed on the the jar screenshot is all there is. ssc_cloud_spatial_anchor_session_create gets called, the application lands on an dead end:

class NativeLibrary {
    NativeLibrary() {
    }
    ...
    static native status ssc_cloud_spatial_anchor_session_create(Out<Long> var0);
    ...
}


The gradle and other configs are copy/paste from the original Microsoft sample. I can't find what I'm missing that's causing my custom project not to find the implementations of NativeLibrary. For reference, here's the Microsoft project that I'm using to base my own project of

Here's my actual gradle files just for reference:

Project gradle

buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Module gradle:

apply plugin: 'com.android.application'
def azureSpatialAnchorsSdkVersion = '1.1.0'
android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.azurelib.azureanchorsclean"
        minSdkVersion 24
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.ar:core:1.7.0'
    implementation "com.microsoft.azure.spatialanchors:spatialanchors_jni:[${azureSpatialAnchorsSdkVersion}]"
    implementation "com.microsoft.azure.spatialanchors:spatialanchors_java:[${azureSpatialAnchorsSdkVersion}]"
    implementation 'de.javagl:obj:0.2.1'
    implementation 'com.microsoft.aad:adal:1.16.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Thanks!



from Azure spatial anchors integration issues. Missing NativeLibrary implementations

AndroidStudio 3.5 - ClassNotFoundException - View referenced from other module

The project is a multi-module project that contains a mediaplayer module with a custom view MediaCustomView inside. The module app depends on mediaplayer.

Context: In the app module...

Using AS 3.5 with android-gradle-plugin:3.5.0-beta02 makes the app crash at runtime when the LayoutInflater tries to inflate an xml using MediaCustomView

Using AS 3.5 with android-gradle-plugin:3.4.1 works just fine.

I remember reading about this somewhere but I can't find it anymore. Anybody knows what's happening and how I can fix it and still use android-gradle-plugin:3.5.0-beta02 ?



from AndroidStudio 3.5 - ClassNotFoundException - View referenced from other module

Parse an HTML template as you require it in JavaScript

I spent hours on a basic webpack configuration but I'm still not able to make it work. My aim is to perform the parsing of a html template as you import it in a JavaScript file. It looks like a common use-case, but there should be something odd in my webpack configuration or in my understanding.

I looked for configurations of html-loader, html-webpack-plugin, posthtml as well as pug and I've read all of their documentations, but none of them worked.

According to PostHTML Readme:

PostHTML is a tool for transforming HTML/XML with JS plugins. PostHTML itself is very small. It includes only a HTML parser, a HTML node tree API and a node tree stringifier.

So, since it was the most promising, I report my attempt with posthtml:

   rules: [
      {
        test: /.html$/,
        use: [
          {
            loader: "html-loader",
            options: {
              minimize: true,
              interpolation: false
            }
          },
          {
            loader: "posthtml-loader"
          }
        ]
      }
    ]

It doesn't return any error but it looks like is totally ignoring the posthtml-loader, since executing import template from 'src/test.html' I get the template as string (how is supposed to do html-loader alone).

In my understanding, loaders are supposed to compile/transform files with different formats and make them available to JavaScript, and since html is the most common type in a front-end project I supposed it was easy, but I'm not finding anything on the internet related to this question.

What I expect is to have a DOM tree object or, anyway, something that can be used by JavaScript.

Is anyone able to help me?

EDIT: My question is about getting a webpack configuration up and working. I know many solution for parsing HTML strings, but they're not applicable here



from Parse an HTML template as you require it in JavaScript

Scipy.optimize.minimize is not giving the minimum value even though it sees that value

I am using scipy.optimize.minimize to find optimal parameters for my objective function.

My code :


import numpy as np
from scipy.optimize import minimize
from scipy.optimize import Bounds

bounds = Bounds([26,26,8,6,400,100,0,25,2],[36,38,28,28,1800,800,100,50,7])

energy_history = []
x_values = []

def objective(x):
    x_trail = x.reshape(1,-1)
    x_trail = sc_X.transform(x_trail)
    y_trail = regressorSVR.predict(x_trail)
    y_trail = y_trail.reshape(1,-1)
    y_trail = sc_Y.inverse_transform(y_trail)
    return y_trail[0]


def callback(x,y):
    fobj = objective(x)
    energy_history.append(fobj)
    x_values.append(x)

x0 = np.array([26,28,15,7,400,377,40,43,4.3])
res = minimize(objective, x0, method='trust-constr',
               options={'verbose': 1}, bounds=bounds,callback=callback)

optimal_values = res.x
energy = res.fun


With the initial values given, the minimized value(res.fun) that I get is -7.1. I am creating a list(energy_history) to see how it is reaching this value. I see some values which are less than -7.1 in that list, but still, why is -7.1 being returned as the minimal value.

image

There are multiple times where objective function reached a value of -21, but why is still -7 being returned as a minimum ?



from Scipy.optimize.minimize is not giving the minimum value even though it sees that value

How to make Vue material select box showing option when the default value is empty?

I am using the vuematerial for material design framework under vue.js.

For normal HTML, let say I have a selection box like this:

<select>
    <option value="">You should initially see this</option>
    <option value="1">One</option>
    <option value="2">Two</option>
</select>

When you run the script, initially you should see a selection box with the text "You should initially see this"

However, when I am using vuematerial to do something similar:

<template>
  <div>
    <div class="md-layout md-gutter">
      <div class="md-layout-item">
        <md-field>
          <md-select v-model="movie" name="movie" id="movie">
            <md-option value="">Default film</md-option>
            <md-option value="fight-club">Fight Club</md-option>
            <md-option value="godfather">Godfather</md-option>
            <md-option value="godfather-ii">Godfather II</md-option>
            <md-option value="godfather-iii">Godfather III</md-option>
            <md-option value="godfellas">Godfellas</md-option>
            <md-option value="pulp-fiction">Pulp Fiction</md-option>
            <md-option value="scarface">Scarface</md-option>
          </md-select>
        </md-field>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'BasicSelect',
    data: () => ({
      movie: '',
    })
  }
</script>

Demo link

I would expect seeing an select box with "Default film" chosen, instead of a blank select box. I noticed that by setting the value of the first option box to be something other then an empty string (e.g. -1) solves the problem, but for my actual case I need the default value to be empty string, so this workaround is not applicable to me. With that in mind, is there a way I can make the value to be shown initially?



from How to make Vue material select box showing option when the default value is empty?

Calculate height of div based off width & maintain proportion

I am looking for a pure CSS solution to what I have here done using jQuery to help.

Basically I have 3 divs that spread evenly in width in a container. They maintain a 3/4 ration with the height being calculated off of the width. Furthermore, each div has a background image that stays proportional and some text that is centered horizontally and vertically.

$(document).ready(function() {
  function setw() {
    var footdivwidth = $('footer div').width();
    var footdivheight = footdivwidth * .75;
    $('footer div').css({
      'height': footdivheight + 'px'
    });
    $('footer div span').html('w: ' + footdivwidth + '<br>h: ' + footdivheight);
  }
  setw();
  $(window).resize(function() {
    setw();
  })
});
FOOTER {
  max-width: 1000px;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, 0.171);
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

FOOTER DIV {
  background-image: url('https://learnwebdesign.online/img/bg.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

FOOTER DIV SPAN {
  display: inline-block;
  text-align: center;
  background-color: rgba(165, 165, 165, 0.282);
  padding: 7px 15px;
  border-radius: 3px;
  color: #FFFFFF;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 2px;
  font-size: 21px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<footer>
  <div><span>left photo</span></div>
  <div><span>center photo</span></div>
  <div><span>right photo and more text</span></div>
</footer>

Here is a pen showing what I have. https://codepen.io/nom3d/pen/arGpBV

Here is a gif showing the effect when resized. Note the background image staying proportional and text staying centered. 3 box resize with proportions kept

Also wondering if it's not possible with just CSS, how to do this with plain javascript, would I need to add id's to my divs?

Update: here is a plain javaScript function to handle this task

function setHeight(el,val){
    var box = document.querySelectorAll(el);
    var i;
    for(i = 0;i < box.length;i++){
        var width = box[i].offsetWidth;
        var height = width * val;
        box[i].style.height = height + 'px';        
    }
}
// set your element to target and the ratio value
setHeight('footer div',.75);
window.onresize = function(event) {
    setHeight('footer div',.75);
};



from Calculate height of div based off width & maintain proportion

How to allow a busy working thread in Espresso

I'm trying to test the progress indicator of an app, which shows an indeterminate progress indicator while the view model is fetching data.

In order to test that, I'm mocking the provider that returns the data and make it block until my test gives tells it to go ahead. The basic setup looks like this:

@Test
public void testProgressIndicator() {
    injectProvider(mockProvider);
    startTestActivity();

    // The mock provider now runs on a worker thread and won't finish
    // until we tell it to.

    // We should now see a progress indicator.
    onView(withId(R.id.progress_indicator)).check(
        matches(withEffectiveVisibility(Visibility.VISIBLE)));

    // Tell the worker thread to finish up.
    mockProvider.setResult();

    // The worker thread now returns a result, the progress indicator
    // should be gone.
    onView(withId(R.id.progress_indicator)).check(
        matches(withEffectiveVisibility(Visibility.GONE)));
}

This code is old, so the provider is using blocking code on a worker thread using AsyncTask.

However, Espresso normally waits for all workers to finish in order to make sure the results are not dependent on the timing. In particular, it uses the AsyncTaskPoolMonitor to wait for all pending AsyncTask objects. This is normally great, but in my case, I want this thread to remain busy while Espresso continues. How can I tell Espresso not to wait for this particular thread?

The cheap cop-out would be to just a Thread and communicate via Handler or something similar, but it would be nice to find a solution while retaining the setup using AsyncTask.

When I break into the debugger, I see that my test runner thread is stuck on the first check():

wait:-1, Object (java.lang)
parkFor$:2137, Thread (java.lang)
park:358, Unsafe (sun.misc)
park:190, LockSupport (java.util.concurrent.locks)
await:2059, AbstractQueuedSynchronizer$ConditionObject (java.util.concurrent.locks)
take:442, LinkedBlockingQueue (java.util.concurrent)
gatherAnyResult:83, InteractionResultsHandler (androidx.test.espresso)
gatherAnyResult:52, InteractionResultsHandler (androidx.test.espresso)
waitForAndHandleInteractionResults:314, ViewInteraction (androidx.test.espresso)
check:300, ViewInteraction (androidx.test.espresso)
testProgressIndicator:76, MyFragmentTest (com.my.test)  <<< ***********************
invoke:-1, Method (java.lang.reflect)
runReflectiveCall:50, FrameworkMethod$1 (org.junit.runners.model)
run:12, ReflectiveCallable (org.junit.internal.runners.model)
invokeExplosively:47, FrameworkMethod (org.junit.runners.model)
evaluate:17, InvokeMethod (org.junit.internal.runners.statements)
evaluate:80, RunBefores (androidx.test.internal.runner.junit4.statement)
evaluate:531, ActivityTestRule$ActivityStatement (androidx.test.rule)
evaluate:20, RunRules (org.junit.rules)
runLeaf:325, ParentRunner (org.junit.runners)
runChild:78, BlockJUnit4ClassRunner (org.junit.runners)
runChild:57, BlockJUnit4ClassRunner (org.junit.runners)
run:290, ParentRunner$3 (org.junit.runners)
schedule:71, ParentRunner$1 (org.junit.runners)
runChildren:288, ParentRunner (org.junit.runners)
access$000:58, ParentRunner (org.junit.runners)
evaluate:268, ParentRunner$2 (org.junit.runners)
run:363, ParentRunner (org.junit.runners)
run:104, AndroidJUnit4 (androidx.test.ext.junit.runners)
runChild:128, Suite (org.junit.runners)
runChild:27, Suite (org.junit.runners)
run:290, ParentRunner$3 (org.junit.runners)
schedule:71, ParentRunner$1 (org.junit.runners)
runChildren:288, ParentRunner (org.junit.runners)
access$000:58, ParentRunner (org.junit.runners)
evaluate:268, ParentRunner$2 (org.junit.runners)
run:363, ParentRunner (org.junit.runners)
run:137, JUnitCore (org.junit.runner)
run:115, JUnitCore (org.junit.runner)
execute:56, TestExecutor (androidx.test.internal.runner)
onStart:388, AndroidJUnitRunner (androidx.test.runner)
run:2075, Instrumentation$InstrumentationThread (android.app)



from How to allow a busy working thread in Espresso

How to record a long video using AVFoundation (>1 min)?

When I record video using the following view controller:

class AVCameraViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {

    override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    initializeMotionManager()
    sessionQueue.async {
        let movieFileOutput = AVCaptureMovieFileOutput()
        if self.session.canAddOutput(movieFileOutput) {
            self.session.beginConfiguration()
            self.session.addOutput(movieFileOutput)
            self.session.sessionPreset = .high
            if let connection = movieFileOutput.connection(with: .video) {
                if connection.isVideoStabilizationSupported {
                    connection.preferredVideoStabilizationMode = .auto
                }
            }
            self.session.commitConfiguration()
            movieFileOutput.maxRecordedDuration = CMTime(seconds: 120, preferredTimescale: 60)

            self.movieFileOutput = movieFileOutput

            DispatchQueue.main.async {
                self.recordButton.isEnabled = true
                }
            }
        }
    }

    func fileOutput(_ output: AVCaptureFileOutput,
                didFinishRecordingTo outputFileURL: URL,
                from connections: [AVCaptureConnection],
                error: Error?) {
    // Note: Since we use a unique file path for each recording, a new recording won't overwrite a recording mid-

save.
        UIApplication.shared.isIdleTimerDisabled = false
        func cleanup() {
            let path = outputFileURL.path
            if FileManager.default.fileExists(atPath: path) {
                do {
                    try FileManager.default.removeItem(atPath: path)
                } catch {
                    print("Could not remove file at url: \(outputFileURL)")
                }
            }

            if let currentBackgroundRecordingID = backgroundRecordingID {
                backgroundRecordingID = UIBackgroundTaskIdentifier.invalid

                if currentBackgroundRecordingID != UIBackgroundTaskIdentifier.invalid {
                    UIApplication.shared.endBackgroundTask(currentBackgroundRecordingID)
                }
            }
        }

        var success = true

        if error != nil {
            print("Movie file finishing error: \(String(describing: error))")
            success = (((error! as NSError).userInfo[AVErrorRecordingSuccessfullyFinishedKey] as AnyObject).boolValue)!
        }

        if success {
            // Check authorization status.
            UIView.animate(withDuration: 0.5){
                self.overlay.alpha = 0.9
                self.navigationController?.navigationBar.isTranslucent = false
            }
            footageURL = outputFileURL
            performSegue(withIdentifier: "TrimFootage", sender: nil)
        } else {
            cleanup()
        }

        // Enable the Camera and Record buttons to let the user switch camera and start another recording.
        DispatchQueue.main.async {
            // Only enable the ability to change camera if the device has more than one camera.
            self.recordButton.isEnabled = true
//            self.recordButton.setImage(#imageLiteral(resourceName: "CaptureVideo"), for: [])
        }
    }
}

As you can see I am setting the maxRecordedDuration to 2 minutes. When its done recording successfully, it eventually segues to another view controller.

The problem is right now it only records for a minute and then stops recording and segues. Im not sure if Im not setting the maxRecordedDuration correctly or if I have to be doing something else instead.



from How to record a long video using AVFoundation (>1 min)?

Docker + Xdebug + VSCode Could not connect to client

PHP version: 7.1.20

XDebug version: 2.7.0

I'm using a Docker container on MacOS Mojave. On pressing "F5", it shows debug options Pause, Restart, and Stop. But Step Over, Step Into, Step Out are disabled.

I'm kind of learner because I was used to code till 2012-13 on Windows OS. After that year, I am back to coding this month. :) Even after reviewing a lot of posts on Google about how to resolve this issue, I'm not sure how to finally make it work. Please help.

My launch.json file:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for XDebug",
            "type": "php",
            "request": "launch",
            "port": 9001,
            "log": true,
            "pathMappings": {
                "/var/www/html": "${workspaceFolder}/learn"
            }
        },
        {
            "name": "Launch currently open script",
            "type": "php",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 9001
        }
    ]
}

XDebug php.ini config:

xdebug.remote_host = 172.20.0.1
xdebug.remote_port = 9001
xdebug.scream = 1
xdebug.remote_enable = 1
xdebug.show_local_vars = 1
xdebug.remote_autostart = 1
xdebug.remote_connect_back = 1
xdebug.remote_log = "/var/www/html/xdebug.log"
xdebug.idekey = "VSCODE"

XDebug logfile (from setting xdebug.remote_log in php.ini):

[12] Log opened at 2019-05-12 10:16:44
[12] I: Checking remote connect back address.
[12] I: Checking header 'HTTP_X_FORWARDED_FOR'.
[12] I: Checking header 'REMOTE_ADDR'.
[12] I: Remote address found, connecting to 172.20.0.1:9001.
[12] W: Creating socket for '172.20.0.1:9001', poll success, but error: Operation now in progress (29).
[12] E: Could not connect to client. :-(
[12] Log closed at 2019-05-12 10:16:44

Debug console:

<- launchResponse
Response {
  seq: 0,
  type: 'response',
  request_seq: 2,
  command: 'launch',
  success: true }

Here's the dockerfile.

FROM php:7.1.20-apache

RUN apt-get -y update --fix-missing
RUN apt-get upgrade -y

# Install tools & libraries
RUN apt-get -y install apt-utils nano wget dialog \
    build-essential git curl libcurl3 libcurl3-dev zip

# Install important libraries
RUN apt-get -y install --fix-missing apt-utils build-essential git curl libcurl3 libcurl3-dev zip \
    libmcrypt-dev libsqlite3-dev libsqlite3-0 mysql-client zlib1g-dev \
    libicu-dev libfreetype6-dev libjpeg62-turbo-dev libpng-dev

# Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

# PHP Extensions
RUN pecl install xdebug-2.7.0 \
    && docker-php-ext-enable xdebug \
    && docker-php-ext-install mcrypt \
    && docker-php-ext-install pdo_mysql \
    && docker-php-ext-install pdo_sqlite \
    && docker-php-ext-install mysqli \
    && docker-php-ext-install curl \
    && docker-php-ext-install tokenizer \
    && docker-php-ext-install json \
    && docker-php-ext-install zip \
    && docker-php-ext-install -j$(nproc) intl \
    && docker-php-ext-install mbstring \
    && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
    && docker-php-ext-install -j$(nproc) gd \
    && pecl install redis \
    && docker-php-ext-enable redis

# Enable apache modules
RUN a2enmod rewrite headers

ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]

Here's the docker-compose.yml file.

version: "3"

services:
  webserver:
    build: 
      context: ./bin/webserver
    container_name: '7.1.x-webserver'
    restart: 'always'
    ports:
      - "80:80"
      - "443:443"
    links: 
      - mysql
    volumes: 
      - ${DOCUMENT_ROOT-./www}:/var/www/html
      - ${PHP_INI-./config/php/php.ini}:/usr/local/etc/php/php.ini
      - ${VHOSTS_DIR-./config/vhosts}:/etc/apache2/sites-enabled
      - ${LOG_DIR-./logs/apache2}:/var/log/apache2
  mysql:
    build: ./bin/mysql
    container_name: '5.7-mysql'
    restart: 'always'
    ports:
      - "3306:3306"
    volumes: 
      - ${MYSQL_DATA_DIR-./data/mysql}:/var/lib/mysql
      - ${MYSQL_LOG_DIR-./logs/mysql}:/var/log/mysql
    environment:
      MYSQL_ROOT_PASSWORD: tiger
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: 'sc-phpmyadmin'
    links:
      - mysql
    environment:
      PMA_HOST: mysql
      PMA_PORT: 3306
    ports:
      - '8080:80'
    volumes: 
      - /sessions
  redis:
    container_name: 'sc-redis'
    image: redis:latest
    ports:
      - "6379:6379"

Thank you in advance.



from Docker + Xdebug + VSCode Could not connect to client

Programmatic Checkout from Amazon.com ( & Amazon.in )

I am trying to automate the purchase of products listed on Amazon.com in Python. We would like to make 1-click purchase with the saved payment details.

I understand Zinc enables the automated product purchase through their API. Does Amazon have a Sandbox account to test this ? Any idea how this can be done

Any suggestion, pointers in this regard will be really helpful.



from Programmatic Checkout from Amazon.com ( & Amazon.in )

Error inflating class NavigationView caused by ResourceNotFoundException

So around 1% of my daily users are haunted with the NavigationView exception which is caused by an image resource not being found. I find that strange, 99% of other users are just fine. I was hoping that updating my dependancies in version iterations will resolve the issue itself, but unfortunately, this error has stayed in my Crashlytics logs for 6 iterations already and it's the worst crash that is affecting my users.

The obvious thing would be that it is specific to older devices, but this would be a wrong assumption. It is not device specific, neither version specific. Although some specifics can be pointed out

  • Android Version
    • 90% Andorid 8
    • 10% Android 7
  • Device
    • Huawei 50%
    • Samsung 50%

Two relevant dependancies i'm using:

implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'com.google.android.material:material:1.0.0'

The relevant piece of code in the XML layout:

<com.google.android.material.navigation.NavigationView
    android:id="@+id/navigation"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:theme="@style/ThemeOverlay.AppCompat.Light"
    app:headerLayout="@layout/layout_drawer_header2"
    app:menu="@menu/navigation" />

The Header layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/authWrapper"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/windowBackground"
    android:orientation="vertical"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    tools:layout_width="240dp">


    <TextView
        android:id="@+id/number"
        style="@style/Base.TextAppearance.AppCompat.Display3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:fontFamily="sans-serif-medium"
        android:textColor="?android:textColorPrimary"
        android:textStyle="italic"
        app:layout_constraintBottom_toBottomOf="@+id/car"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/driver"
        tools:text="#01" />

    <ImageView
        android:id="@+id/driverIcon"
        android:layout_width="12dp"
        android:layout_height="12dp"
        android:layout_marginStart="4dp"
        android:layout_marginLeft="4dp"
        app:layout_constraintBottom_toBottomOf="@+id/driver"
        app:layout_constraintStart_toEndOf="@+id/number"
        app:layout_constraintTop_toTopOf="@+id/driver"
        app:srcCompat="@drawable/ic_person_white_24dp" />


    <TextView
        android:id="@+id/driver"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="2dp"
        android:layout_marginStart="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="2dp"
        android:layout_marginTop="16dp"
        android:drawablePadding="8dp"
        android:ellipsize="end"
        android:lines="1"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Body1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/driverIcon"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="Drivers name" />

    <ImageView
        android:id="@+id/coDriverIcon"
        android:layout_width="12dp"
        android:layout_height="12dp"
        android:layout_marginStart="4dp"
        android:layout_marginLeft="4dp"
        app:layout_constraintBottom_toBottomOf="@+id/codriver"
        app:layout_constraintStart_toEndOf="@+id/number"
        app:layout_constraintTop_toTopOf="@+id/codriver"
        app:srcCompat="@drawable/ic_person_white_24dp" />

    <TextView
        android:id="@+id/codriver"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="2dp"
        android:layout_marginStart="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="2dp"
        android:drawablePadding="8dp"
        android:ellipsize="end"
        android:lines="1"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Body1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/coDriverIcon"
        app:layout_constraintTop_toBottomOf="@+id/driver"
        tools:text="Co-Driver name" />

    <ImageView
        android:id="@+id/carIcon"
        android:layout_width="12dp"
        android:layout_height="12dp"
        android:layout_marginStart="4dp"
        android:layout_marginLeft="4dp"
        app:layout_constraintBottom_toBottomOf="@+id/car"
        app:layout_constraintStart_toEndOf="@+id/number"
        app:layout_constraintTop_toTopOf="@+id/car"
        app:srcCompat="@drawable/ic_car_white_24dp" />

    <TextView
        android:id="@+id/car"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="2dp"
        android:layout_marginStart="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="2dp"
        android:ellipsize="end"
        android:lines="1"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Body1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/carIcon"
        app:layout_constraintTop_toBottomOf="@+id/codriver"
        tools:text="Racing Car" />


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="gone">

        <ImageView
            android:id="@+id/image"
            android:layout_width="72dp"
            android:layout_height="72dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            app:srcCompat="@drawable/ic_account_circle_white_24dp" />

        <ImageView
            android:id="@+id/logout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:padding="12dp"
            android:tint="@android:color/white"
            app:srcCompat="@drawable/ic_log_out" />
    </RelativeLayout>

    <TextView
        android:id="@+id/switchText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="16dp"
        android:layout_marginRight="8dp"
        android:autoLink="web"
        android:gravity="center_vertical"
        android:maxLines="2"
        android:text="@string/track_me_on_racelivemaps_com"
        app:layout_constraintEnd_toStartOf="@+id/trackingOn"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/number" />


    <Switch
        android:layout_width="wrap_content"
        android:id="@+id/trackingOn"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:autoLink="web"
        android:gravity="center_vertical"

        android:maxLines="2"
        app:layout_constraintBottom_toBottomOf="@+id/switchText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@+id/switchText" />


    <TextView
        android:id="@+id/textView12"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:text="@string/active_stage"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Body2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switchText" />

    <Spinner
        android:id="@+id/activeStage"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView12" />

</androidx.constraintlayout.widget.ConstraintLayout>

The menu:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:title="@string/mode">
        <menu>
            <group android:checkableBehavior="single">

                <item
                    android:id="@+id/recce"
                    android:icon="@drawable/ic_write_black_24dp"
                    android:title="@string/reccemode" />
                <item
                    android:id="@+id/liaison"
                    android:icon="@drawable/ic_route_black_24dp"
                    android:title="@string/liaisonmode" />

                <item
                    android:id="@+id/racing"
                    android:icon="@drawable/ic_racing_flag_black_24dp"
                    android:title="@string/racemode" />

                <item
                    android:id="@+id/tsd"
                    android:icon="@drawable/ic_timer_black_24dp"
                    android:title="@string/tsd" />

                <item
                    android:id="@+id/tsd_advanced"
                    android:icon="@drawable/ic_tsd_advanced"
                    android:title="@string/tsd_advanced" />

                <item
                    android:id="@+id/custom_1"
                    android:icon="@drawable/ic_navigation_layout"
                    android:title="@string/custom_layout_1" />

                <item
                    android:id="@+id/custom_2"
                    android:icon="@drawable/ic_navigation_layout"
                    android:title="@string/custom_layout_2" />

                <item
                    android:id="@+id/custom_3"
                    android:icon="@drawable/ic_navigation_layout"
                    android:title="@string/custom_layout_3" />

            </group>
        </menu>
    </item>
    <group android:checkableBehavior="none">
        <item
            android:id="@+id/stages"
            android:icon="@drawable/ic_stage_black_24dp"
            android:title="@string/special_stages" />

        <item
            android:id="@+id/settings"
            android:icon="@drawable/ic_settings_black_24dp"
            android:title="@string/settings" />

        <item
            android:id="@+id/customize_ui"
            android:icon="@drawable/ic_layout_edit"
            android:title="@string/customize_ui" />

        <item
            android:id="@+id/weather"
            android:icon="@drawable/ic_weather"
            android:title="@string/weather" />

        <item
            android:id="@+id/login"
            android:icon="@drawable/ic_key_white_24dp"
            android:title="@string/log_in" />

        <item
            android:id="@+id/manual"
            android:icon="@drawable/ic_manual"
            android:title="@string/user_manual" />

        <item
            android:id="@+id/language"
            android:icon="@drawable/ic_translate"
            android:title="@string/language" />

        <item
            android:id="@+id/invite"
            android:icon="@drawable/ic_share_black_24dp"
            android:title="@string/invite" />

        <item
            android:id="@+id/feedback"
            android:icon="@drawable/ic_feedback_black_24dp"
            android:title="@string/feedback_report_bug" />

        <item
            android:id="@+id/tester"
            android:icon="@drawable/ic_tester"
            android:title="@string/become_a_tester" />

        <item
            android:id="@+id/policy"
            android:icon="@drawable/ic_policy"
            android:title="@string/privacy_policy" />

        <item
            android:id="@+id/logoff"
            android:icon="@drawable/ic_key_white_24dp"
            android:title="@string/log_off" />

        <item
            android:id="@+id/exit"
            android:icon="@drawable/ic_exit_to_app_black_24dp"
            android:title="@string/exit" />


    </group>


</menu>

And finally the crash logs.

android.view.InflateException: Binary XML file line #48: Binary XML file line #48: Error inflating class com.google.android.material.navigation.NavigationView at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3173) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3284) at android.app.ActivityThread.-wrap12(Unknown Source) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1894) at android.os.Handler.dispatchMessage(Handler.java:109) at android.os.Looper.loop(Looper.java:166) at android.app.ActivityThread.main(ActivityThread.java:7383) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)

Caused by android.view.InflateException: Binary XML file line #48: Binary XML file line #48: Error inflating class com.google.android.material.navigation.NavigationView

Caused by android.view.InflateException: Binary XML file line #48: Error inflating class com.google.android.material.navigation.NavigationView

Caused by java.lang.reflect.InvocationTargetException at java.lang.reflect.Constructor.newInstance0(Constructor.java) at java.lang.reflect.Constructor.newInstance(Constructor.java:334) at android.view.LayoutInflater.createView(LayoutInflater.java:658) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:801) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741) at android.view.LayoutInflater.rInflate(LayoutInflater.java:874) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:835) at android.view.LayoutInflater.inflate(LayoutInflater.java:515) at android.view.LayoutInflater.inflate(LayoutInflater.java:423) at android.view.LayoutInflater.inflate(LayoutInflater.java:374) at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469) at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) at ee.siimplangi.rallytripmeter.activities.MainActivity.onCreate(MainActivity.kt:186) at android.app.Activity.performCreate(Activity.java:7358) at android.app.Activity.performCreate(Activity.java:7349) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1219) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3126) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3284) at android.app.ActivityThread.-wrap12(Unknown Source) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1894) at android.os.Handler.dispatchMessage(Handler.java:109) at android.os.Looper.loop(Looper.java:166) at android.app.ActivityThread.main(ActivityThread.java:7383) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)

Caused by android.view.InflateException: Binary XML file line #29: Binary XML file line #29: Error inflating class ImageView

Caused by android.view.InflateException: Binary XML file line #29: Error inflating class ImageView

Caused by android.content.res.Resources$NotFoundException: Resource ID

0x7f0800a5

   at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:290)
   at android.content.res.Resources.getValue(Resources.java:1476)
   at androidx.appcompat.widget.AppCompatDrawableManager.createDrawableIfNeeded(AppCompatDrawableManager.java:235)
   at androidx.appcompat.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:200)
   at androidx.appcompat.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:191)
   at androidx.appcompat.content.res.AppCompatResources.getDrawable(AppCompatResources.java:102)
   at androidx.appcompat.widget.AppCompatImageHelper.loadFromAttributes(AppCompatImageHelper.java:59)
   at androidx.appcompat.widget.AppCompatImageView.(AppCompatImageView.java:78)
   at androidx.appcompat.widget.AppCompatImageView.(AppCompatImageView.java:68)
   at androidx.appcompat.app.AppCompatViewInflater.createImageView(AppCompatViewInflater.java:182)
   at androidx.appcompat.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
   at androidx.appcompat.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1266)
   at androidx.appcompat.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1316)
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:783)
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741)
   at android.view.LayoutInflater.rInflate(LayoutInflater.java:874)
   at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:835)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
   at com.google.android.material.internal.NavigationMenuPresenter.inflateHeaderView(NavigationMenuPresenter.java:207)
   at com.google.android.material.navigation.NavigationView.inflateHeaderView(NavigationView.java:281)
   at com.google.android.material.navigation.NavigationView.(NavigationView.java:193)
   at com.google.android.material.navigation.NavigationView.(NavigationView.java:104)
   at java.lang.reflect.Constructor.newInstance0(Constructor.java)
   at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
   at android.view.LayoutInflater.createView(LayoutInflater.java:658)
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:801)
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741)
   at android.view.LayoutInflater.rInflate(LayoutInflater.java:874)
   at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:835)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
   at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
   at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
   at ee.siimplangi.rallytripmeter.activities.MainActivity.onCreate(MainActivity.kt:186)
   at android.app.Activity.performCreate(Activity.java:7358)
   at android.app.Activity.performCreate(Activity.java:7349)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1219)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3126)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3284)
   at android.app.ActivityThread.-wrap12(Unknown Source)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1894)
   at android.os.Handler.dispatchMessage(Handler.java:109)
   at android.os.Looper.loop(Looper.java:166)
   at android.app.ActivityThread.main(ActivityThread.java:7383)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)



from Error inflating class NavigationView caused by ResourceNotFoundException

How do I authenticate a Vue.js progressive web app with the Microsoft Graph

I have a Vue.js app. This app is a progressive web app so it's intended to primarily run on the client-side. However, during the initial start-up, I need to authenticate the user in my Azure Active Directory, get data associated with their account, and store it for offline use.

I have a server-side API in place already for retrieving the data associated with a user account. I also know how to store it for offline use. However, my question is, how do I authenticate with the Microsoft Graph from my Vue.js app? Everything I see relies on using Node.js Middleware. But, unless I'm misunderstanding something, my progressive web app isn't a Node.js app, it's just straight up JavaScript, HTML, and CSS.

If the user closes the app, then revisits it in a couple of days, I believe I would need to use the refresh token to get a new access token. Still, once again, everything I see relies on Node.js middleware. I believe I need a solution that works purely in Vue.js / JavaScript. Am I mistaken?



from How do I authenticate a Vue.js progressive web app with the Microsoft Graph

Custom Expandable RecyclerView Crashing on notifyItemRangeRemoved and notifyItemRangeInserted

I have created expandable recylerview following is my adapter code

public class FoodMenuRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    List<Object> objects;
    FoodMenuParentListener foodMenuParentListener;
    boolean isAddAllowed;

    boolean isVegOnly;
    static final int TYPE_FOOD = 0;
    static final int TYPE_MENU_ITEM = 1;


    public FoodMenuRecyclerAdapter(List<Object> objects, FoodMenuParentListener foodMenuParentListener, boolean isVegOnly, boolean isAddAllowed) {
        this.foodMenuParentListener = foodMenuParentListener;
        this.isVegOnly = isVegOnly;
        this.isAddAllowed = isAddAllowed;
        this.objects = objects;
    }

    @Override
    public int getItemViewType(int position) {
        Object object = objects.get(position);
        if (object instanceof FoodMenuItem) {
            return TYPE_FOOD;
        } else if(this.objects.get(position) == null) {
            throw new IllegalStateException("Null object added");
        }else {
            return TYPE_MENU_ITEM;
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view;
        switch (getItemViewType(i)) {
            case TYPE_FOOD:
                view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_food_parent, viewGroup, false);
                return new MenuViewHolder(view);
            case TYPE_MENU_ITEM:
                view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_food_child, viewGroup, false);
                return new ChildMenuHolder(view);
            default:
                throw new IllegalArgumentException("Invalid viewType");

        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
        Object object = objects.get(i);
        Context context = viewHolder.itemView.getContext();
        Log.d("myAdapter","position"+ i + ":"+ ((getItemViewType(i) == TYPE_MENU_ITEM) ? "TYPE_MENU_ITEM" : "TYPE_FOOD"));
         if (getItemViewType(i) == TYPE_MENU_ITEM) {
            ChildMenuHolder childMenuHolder = (ChildMenuHolder) viewHolder;
            GmrApplication gmrApplication = (GmrApplication) context.getApplicationContext();
            Item item = (Item) object;
            childMenuHolder.tvPrice.setText(gmrApplication.getCurrencySymbolString() + item.getPrice());
            childMenuHolder.tvTitle.setText(item.getTitle());
            childMenuHolder.txtQty.setText(String.valueOf(item.getQuatity()));
            childMenuHolder.txtCartInc.setVisibility(item.isAddedToCart() ? View.VISIBLE : View.GONE);
            childMenuHolder.txtQty.setVisibility(item.isAddedToCart() ? View.VISIBLE : View.GONE);
            childMenuHolder.txtCartDec.setVisibility(item.isAddedToCart() ? View.VISIBLE : View.GONE);
            childMenuHolder.btnAdd.setVisibility(!item.isAddedToCart() ? View.VISIBLE : View.GONE);
            childMenuHolder.btnAdd.setBackgroundResource(isAddAllowed ? R.drawable.rounded_bottom_edge_shape_food : R.drawable.rounded_bottom_edge_shape_disable);
            childMenuHolder.btnAdd.setTextColor(isAddAllowed ? ContextCompat.getColor(context, R.color.button_green) : ContextCompat.getColor(context, R.color.gray_a1));
            childMenuHolder.ivType.setColorFilter(item.getType().equalsIgnoreCase(Item.FOOD_TYPE_VEG) ? ContextCompat.getColor(context, R.color.selected_green) : ContextCompat.getColor(context, R.color.app_red));
        } else {
            FoodMenuItem foodMenuItem = (FoodMenuItem) object;
            MenuViewHolder menuViewHolder = (MenuViewHolder) viewHolder;
            if (isVegOnly) {
                List<Item> items = new ArrayList<>();
                for (Item item : foodMenuItem.getItems()) {
                    if (item.getType().equalsIgnoreCase(Item.FOOD_TYPE_VEG)) {
                        items.add(item);
                    }
                }
                menuViewHolder.tvNumItems.setText("(" + items.size() + " items)");

            } else {
                menuViewHolder.tvNumItems.setText("(" + foodMenuItem.getItems().size() + " items)");

            }
            menuViewHolder.ivArrow.setImageResource(foodMenuItem.isExpanded() ? R.drawable.chev_up : R.drawable.chev_down);
            menuViewHolder.tvTitle.setText(foodMenuItem.getCategoryName());
        }


    }


    @Override
    public int getItemCount() {
        return objects.size();
    }

    public class MenuViewHolder extends RecyclerView.ViewHolder {
        TextView tvTitle;
        TextView tvNumItems;
        ImageView ivArrow;
        // RecyclerView rvMenu;
        View rlArrow;

        public MenuViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
            tvNumItems = (TextView) itemView.findViewById(R.id.tvNumItems);
            ivArrow = (ImageView) itemView.findViewById(R.id.ivArrow);
            // rvMenu.setNestedScrollingEnabled(false);
            rlArrow = itemView.findViewById(R.id.rlArrow);
            rlArrow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (foodMenuParentListener != null) {
                        Object object = objects.get(getAdapterPosition());
                        if (object instanceof FoodMenuItem) {
                            FoodMenuItem foodMenuItem = (FoodMenuItem) object;
                            foodMenuParentListener.OnExpandClick(foodMenuItem, getAdapterPosition());

                        }
                    }
                }
            });
            tvTitle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (foodMenuParentListener != null) {
                        Object object = objects.get(getAdapterPosition());
                        if (object instanceof FoodMenuItem) {
                            FoodMenuItem foodMenuItem = (FoodMenuItem) object;
                            foodMenuParentListener.OnExpandClick(foodMenuItem, getAdapterPosition());

                        }
                    }
                }
            });
        }
    }

    public boolean isVegOnly() {
        return isVegOnly;
    }

    public void setVegOnly(boolean vegOnly) {
        isVegOnly = vegOnly;
    }

    public interface FoodMenuParentListener extends AddItemListener {
        public void OnExpandClick(FoodMenuItem foodMenuItem, int position);

        public void OnVegOnlyClicked();
    }

    public class ChildMenuHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        ImageView ivType;
        TextView tvTitle;
        TextView tvPrice;
        TextView txtCartDec;
        TextView txtQty;
        TextView txtCartInc;

        Button btnAdd;

        public ChildMenuHolder(@NonNull View itemView) {
            super(itemView);
            ivType = (ImageView) itemView.findViewById(R.id.ivType);
            tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
            tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
            txtCartDec = (TextView) itemView.findViewById(R.id.txtCartDec);
            txtQty = (TextView) itemView.findViewById(R.id.txtQty);
            txtCartInc = (TextView) itemView.findViewById(R.id.txtCartInc);
            btnAdd = (Button) itemView.findViewById(R.id.btnAdd);
            btnAdd.setOnClickListener(this);
            txtCartInc.setOnClickListener(this);
            txtCartDec.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {

        }
    }

    public void setExpandIndex(int expandIndex) {
    }

    public boolean isItemExpanded(int position) {
        return true;
    }


    public class VegOnlyViewHolder extends RecyclerView.ViewHolder {
        Switch wtVeg;

        public VegOnlyViewHolder(@NonNull View itemView) {
            super(itemView);
            wtVeg = (Switch) itemView.findViewById(R.id.wtVeg);
            wtVeg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (foodMenuParentListener != null) {
                        foodMenuParentListener.OnVegOnlyClicked();
                    }
                }
            });
        }
    }


    public interface AddItemListener {
        public void onAddClicked(Item item, int parentIndex);

        public void increaseItemCount(Item item, int parentIndex);

        public void decreaseItemCount(Item item, int parentIndex);
    }

    public void addAll(int position, List<Item> objectsToAdd) {
        this.objects.addAll(position, objectsToAdd);
    }

    public void addItem(int position, Item object) {
        this.objects.add(position, object);
    }
    public void removeItem(Object object) {
        this.objects.remove(object);
    }


    public void removeAll(List<Item> objectsToRemove) {
        objects.removeAll(objectsToRemove);
        Log.d("myAdapter","item at first position after remove" + ":"+objects.get(0));
        Log.d("myAdapter","item at second position after remove" + ":"+objects.get(1));
    }

    public Object isItemInList(Item item) {
        for (Object object : objects) {
            if (object instanceof Item && ((Item) object).getId().equals(item.getId())) {
                return object;
            }
        }
        return null;
    }
    }

Following is code in my Fragment to expand collapse RecyclerView

 @Override
        public void OnExpandClick(FoodMenuItem foodMenuItem, int position) {
            if (recyclerViewMenu != null && recyclerViewMenu.getAdapter() != null) {
                recyclerViewMenu.getRecycledViewPool().clear();
                FoodMenuRecyclerAdapter foodMenuRecyclerAdapter = (FoodMenuRecyclerAdapter) recyclerViewMenu.getAdapter();
                foodMenuItem.setExpanded(!foodMenuItem.isExpanded());
                if (foodMenuItem.isExpanded()) {
                    foodMenuRecyclerAdapter.addAll(position + 1, foodMenuItem.getItems());
                    foodMenuRecyclerAdapter.notifyItemRangeInserted(position, foodMenuItem.getItems().size());

                } else {
                    foodMenuRecyclerAdapter.removeAll(foodMenuItem.getItems());
                    foodMenuRecyclerAdapter.notifyItemRangeRemoved(position + 1, foodMenuItem.getItems().size());

                }

            }

        }

Following is listener code inside fragment to expand and collapse

public void OnExpandClick(FoodMenuItem foodMenuItem, int position) {
            if (recyclerViewMenu != null && recyclerViewMenu.getAdapter() != null) {
                FoodMenuRecyclerAdapter foodMenuRecyclerAdapter = (FoodMenuRecyclerAdapter) recyclerViewMenu.getAdapter();
                foodMenuItem.setExpanded(!foodMenuItem.isExpanded());
                if (foodMenuItem.isExpanded()) {
                    foodMenuRecyclerAdapter.addAll(position + 1, foodMenuItem.getItems());
                    foodMenuRecyclerAdapter.notifyItemRangeInserted(position, foodMenuItem.getItems().size());

                } else {
                    foodMenuRecyclerAdapter.removeAll(foodMenuItem.getItems());
                    foodMenuRecyclerAdapter.notifyItemRangeRemoved(position +1 , foodMenuItem.getItems().size());

                }

            }

        }

Above code is throwing exception following is exception stack trace

 java.lang.ClassCastException: com.myapp.android.pojoentities.Item cannot be cast to com.myapp.android.pojoentities.FoodMenuItem
    at com.myapp.android.food.menu.FoodMenuRecyclerAdapter.onBindViewHolder(FoodMenuRecyclerAdapter.java:104)
    at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
    at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
    at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
    at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
    at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
    at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
    at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
    at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
    at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3875)
    at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3639)
    at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:4194)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.support.design.widget.CoordinatorLayout.layoutChild(CoordinatorLayout.java:1183)
    at android.support.design.widget.CoordinatorLayout.onLayoutChild(CoordinatorLayout.java:870)
    at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:889)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
    at com.myapp.android.custom.FitsSystemWindowsFrameLayout.onLayout(FitsSystemWindowsFrameLayout.java:247)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1231)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
    at android.view.View.layout(View.java:

Update:

After collapsing first item I have checked log for type of first two items in list found that first two items are of type ParentItem which is FoodMenuItem but when I checked log for getItemViewType for same positions it is returning wrong value somehow

Following are logs

05-28 00:13:47.643 32010-32010/com.myapp.android D/myAdapter: item at first position after remove:com.myapp.android.pojoentities.FoodMenuItem@7fdf002
05-28 00:13:47.643 32010-32010/com.myapp.android D/myAdapter: item at second position after remove:com.myapp.android.pojoentities.FoodMenuItem@9cbfd13
05-28 00:13:47.664 32010-32010/com.myapp.android D/myAdapter: position1:TYPE_FOOD
05-28 00:13:47.678 32010-32010/com.myapp.android D/myAdapter: position2:TYPE_MENU_ITEM



from Custom Expandable RecyclerView Crashing on notifyItemRangeRemoved and notifyItemRangeInserted

Selenium python Error: element could not be scrolled into view

I am working on automating the IdentiGO application for my company, and I'm getting the following error:

Internal Server Error: /identigo
Traceback (most recent call last):
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/jane/Code/maynard_env/maynard/employee/views.py", line 63, in post
    driver.main(employee)
  File "/Users/jane/Code/maynard_env/maynard/employee/driver.py", line 31, in main
    WebDriverWait(driver, 1000000).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[5]/div[3]/div/button/span'))).click()
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py", line 633, in _execute
    return self._parent.execute(command, params)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: Element <span class="ui-button-text"> could not be scrolled into view

Here is my code, with the scripts leading up to this page omitted since they aren't relevant to my problem.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


WebDriverWait(driver, 1000000).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[5]/div[3]/div/button/span'))).click()

On the page prior to this code, where the user selects an appointment date and time; I want the script to wait for the "Go" button to be pushed, then click on "Continue" in the following screenshot:

enter image description here

If you would like to see the exact page, go to this url, then you will have to make a series of POST requests using the following info:

  • click schedule a new appointment
  • other
  • vendors and contractors (children)
  • tnvc00047
  • 37204
  • make random appointment date

Any advice would really be appreciated!

Update

Here is a JS Fiddle with the html of the page:

https://jsfiddle.net/khf4tym3/

When I click "view page source", the popup html doesn't show in the source code, so I assume that it is generated with JS.

<div class="ui-dialog-buttonset">
    <button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
        <span class="ui-button-text">Continue</span>
    </button>
</div>

Update 2

If I change the line WebDriverWait(driver, 1000000) to WebDriverWait(driver, 30), I get the following error instead:

Internal Server Error: /identigo
Traceback (most recent call last):
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/jane/Code/maynard_env/maynard/employee/views.py", line 63, in post
    driver.main(employee)
  File "/Users/jane/Code/maynard_env/maynard/employee/driver.py", line 34, in main
    element=WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.XPATH,"//div[@class='ui-dialog-buttonset']/button[@class='ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only']/span[contains(.,'Continue')]")))
  File "/Users/jane/Code/maynard_env/env/lib/python3.7/site-packages/selenium/webdriver/support/wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 

pythonfiddle

code for the project so far, so you can skip the forum entry.

https://jsfiddle.net/93k5s2xg/1/



from Selenium python Error: element could not be scrolled into view

How to make firebase push notifications work

I have spent about 2 days going through firebases documentation, asking questions and looking at others and following youtube/medium tutorials and more. Here is a github project with my full app delegate, so that all my code is visible.

But I am yet to figure out how to be able to send a notification message from firebase cloud messaging. I have setup Apple push services have gotten and inputed auth key into firebase and written code in my app delegate seen here

Can someone let me know what I need to do to make it work? What have I missed?

Here is my didRegisterForRemoteNotificationsWithDeviceToken method:

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken
    let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
    let token = tokenParts.joined()
    print("Device Token: \(token)")

}

Update:

I have followed again this whole documentation by firebase and still sending notifications from fire cloud messaging does not work.

Clearly however the code is running given that 2 lines I have which save the token to firebase successfully save the token.



from How to make firebase push notifications work

Creating API versioning for my php application (Social App)

I'm currently working on a Social Application.

I would like to have a versioning system on my PHP backend, but I don't know where to start: I have looked up bunch of articles online, but I couldn't really understand what I've found.

Let's say my application is v1.0. Then I create a new version v2.0 and of course I update the PHP files too. After this, if someone hasn't updated their app from v1.0, I would like them to reach myapp.com/v1.0/, so that the app doesn't crash.

What would you recommend?

A typical PHP file of mine looks like this, for example:

<?php

// Include files

include_once ('../../config.php');

include_once (ROOT_DIR . '/config/includes.php');

$_USERDATA = Validator::validateUser($_POST["userId"], $_POST["session"]);

// Valid session

$qry = $db->prepare('SELECT n.id, n.type, n.time, n.isRead, n.postId, n.commentId, n.text, n.inReplyToCommentId, u.id as byUserId, 
    ( SELECT COUNT(nu.id)
    FROM notificationUsers AS nu
    WHERE nu.notificationId = n.id ) as detail1,
    ( SELECT nu2.userId
    FROM notificationUsers AS nu2
    WHERE nu2.notificationId = n.id ORDER BY nu2.id DESC LIMIT 1 ) as latestUserId FROM notifications AS n LEFT JOIN userData AS u ON n.byUserId = u.id
    WHERE n.userId = :userId ORDER BY n.time DESC');
$qry->bindParam(':userId', $_USERDATA["userId"], PDO::PARAM_INT);
$qry->execute();

$notificationsArray = $qry->fetchAll(PDO::FETCH_ASSOC);


$returnValue = array();
$returnValue["status"] = "1";
$returnValue["title"] = "Success";
$returnValue["message"] = "Downloaded notifications";
$returnValue["data_notifications"] = $notificationsArray;
exit(json_encode($returnValue));



?>

...

UPDATE 1

So I decided to do the following:

Placing every not shared file inside a folder like so:

/api/v1.0/file.php

But every resource for example (images) is outside the api

/resources/images/profilepictures/image.jpg


If I make a minor change, I just update the files within the api/v1.0/ folder.

Then, all the users that are using the Application v1.1, they are requesting myapp.com/api/v1.1/, but I redirect them to api/v1.0/ where I can present the users the right data (depending if the request was from v1.0 or v1.1)

If the versions add up and I release a bigger update, I'll create a new folder with the name v2.0, and so it goes...

Or what do you think. How should I do it?



from Creating API versioning for my php application (Social App)