Sunday 30 June 2019

How to use jQuery ContextMenu to have 2 different menus one above the other inside a table?

Using jQuery ContextMenu plugin is it possible to use a menu inside another?

In my snippet I would like to open the first menu only on right click (on the table row) and open the second menu only on left click of the button (inside my row).

I set trigger: 'left' only for the button however when I left click on it both menus are shown as you see here:

$(function() {
    $.contextMenu({
        selector: '.context-menu-one', 
        callback: function(key, options) {
            var m = "clicked: " + key;
            window.console && console.log(m) || alert(m); 
        },
        items: {
            "edit": {name: "Edit", icon: "edit"},
            "cut": {name: "Cut", icon: "cut"},
           copy: {name: "Copy", icon: "copy"},
            "paste": {name: "Paste", icon: "paste"},
            "delete": {name: "Delete", icon: "delete"},
            "sep1": "---------",
            "quit": {name: "Quit", icon: function(){
                return 'context-menu-icon context-menu-icon-quit';
            }}
        }
    });
    
    $.contextMenu({
        selector: '.context-menu-two', 
              trigger: 'left',
        items: {
            "new": {name: "New", icon: "new"},
            "open": {name: "Open", icon: "open"}
        }
    });  
});
table{width:300px;height:100px}
tr {background:#222;color:#fff}
<link href="https://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet"/>
<link href="https://www.jqueryscript.net/demo/Feature-rich-Custom-jQuery-Context-Menu-Plugin-contextMenu/dist/jquery.contextMenu.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.jqueryscript.net/demo/Feature-rich-Custom-jQuery-Context-Menu-Plugin-contextMenu/dist/jquery.ui.position.js"></script>
<script src="https://www.jqueryscript.net/demo/Feature-rich-Custom-jQuery-Context-Menu-Plugin-contextMenu/dist/jquery.contextMenu.js"></script>
<table>
    <tbody>
        <tr role="row" class="context-menu-one">
            <td>
                <button class="context-menu-two">Left click</button>
            </td>
        </tr>
    </tbody>
</table>

I want to show both menus however is there a method to prevent the first menu to be shown when I click on the button?



from How to use jQuery ContextMenu to have 2 different menus one above the other inside a table?

com.android.tools.r8.utils.AbortException: Error: program input - Unsupported source file type

After I upgraded my android project to androidX I get the following build error:

org.gradle.execution.MultipleBuildFailures: Build completed with 1 failures.
    at org.gradle.initialization.DefaultGradleLauncher$ExecuteTasks.run(DefaultGradleLauncher.java:358)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.initialization.DefaultGradleLauncher.runTasks(DefaultGradleLauncher.java:219)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
    at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:124)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:77)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:74)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:154)
    at org.gradle.internal.work.StopShieldingWorkerLeaseService.withLocks(StopShieldingWorkerLeaseService.java:38)
    at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:96)
    at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:74)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:55)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$3.run(RunAsBuildOperationBuildActionRunner.java:50)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:45)
    at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:47)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:44)
    at org.gradle.composite.internal.DefaultRootBuildState.run(DefaultRootBuildState.java:79)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:44)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:62)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:34)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:31)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:46)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:81)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app-android:transformClassesWithMultidexlistForDebug'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:77)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
    at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.run(EventFiringTaskExecuter.java:51)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
    at org.gradle.execution.taskgraph.LocalTaskInfoExecutor.execute(LocalTaskInfoExecutor.java:42)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:277)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:262)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:135)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:130)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.execute(DefaultTaskPlanExecutor.java:200)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.executeWithWork(DefaultTaskPlanExecutor.java:191)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.run(DefaultTaskPlanExecutor.java:130)
    ... 6 more
Caused by: java.lang.RuntimeException: com.android.build.api.transform.TransformException: Error while generating the main dex list:
Error while merging dex archives: 
    at com.android.builder.profile.Recorder$Block.handleException(Recorder.java:55)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:104)
    at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:230)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:50)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:131)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:120)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:99)
    ... 34 more
Caused by: com.android.build.api.transform.TransformException: Error while generating the main dex list:
Error while merging dex archives: 
    at com.android.build.gradle.internal.transforms.D8MainDexListTransform.transform(D8MainDexListTransform.kt:147)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:239)
    at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:235)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
    ... 51 more
Caused by: com.android.builder.multidex.D8MainDexList$MainDexListException: Error while merging dex archives: 
    at com.android.builder.multidex.D8MainDexList.getExceptionToRethrow(D8MainDexList.java:107)
    at com.android.builder.multidex.D8MainDexList.generate(D8MainDexList.java:95)
    at com.android.build.gradle.internal.transforms.D8MainDexListTransform.transform(D8MainDexListTransform.kt:131)
    ... 54 more
Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete
    at com.android.tools.r8.BaseCommand$Builder.build(BaseCommand.java:143)
    at com.android.builder.multidex.D8MainDexList.generate(D8MainDexList.java:93)
    ... 55 more
Caused by: com.android.tools.r8.utils.AbortException: Error: program input '/mnt/data/Entwicklung/SkipngoApp/app/app-android/build/intermediates/transforms/FirebasePerformancePlugin/debug/127/module-info.class', Unsupported source file type
    at com.android.tools.r8.utils.Reporter.failIfPendingErrors(Reporter.java:89)
    at com.android.tools.r8.shaking.ProguardConfigurationParser.parse(ProguardConfigurationParser.java:173)
    at com.android.tools.r8.GenerateMainDexListCommand$Builder.makeCommand(GenerateMainDexListCommand.java:113)
    at com.android.tools.r8.GenerateMainDexListCommand$Builder.makeCommand(GenerateMainDexListCommand.java:32)
    at com.android.tools.r8.BaseCommand$Builder.build(BaseCommand.java:139)
    ... 56 more

I have read, that this might be an issue that is fixed in Android-Studio 3.5 Beta as mentioned here But I have tried it with the newest beta version and I get the same error. Others said the same here. But I am not even sure if it is the same problem for me.

Anyone has an idea how to fix this?



from com.android.tools.r8.utils.AbortException: Error: program input - Unsupported source file type

SOAPUI and Node.JS/Request- AccessException

I am trying to build a shipment tracking tool using the Estes Shipment Tracking Web Services which use SOAP. I talked with their web support, and they are able to create a working request using SOAPUI that receives a valid response using my credentials. It would appear that my problem is the inability to replicate the request/response in SOAPUI with node.js. Why am I not able to replicate the SOAPUI request/response in node.js?

The following is the working raw request from SOAPUI that Estes web support used:

POST https://api.estes-express.com:443/ws/estesrtshipmenttracking.base.ws.provider.soapws:EstesShipmentTracking/estesrtshipmenttracking_base_ws_provider_soapws_EstesShipmentTracking_Port HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: text/xml;charset=UTF-8
SOAPAction: "estesrtshipmenttracking_base_ws_provider_soapws_EstesShipmentTracking_Binder_shipmentTracking"
Content-Length: 468
Host: api.estes-express.com:443
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
Authorization: Basic XXXXX

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="https://api.estes-express.com/ws/tools/shipment/tracking/v1.1/">
   <soapenv:Header/>
   <soapenv:Body>
      <v1:shipmentTracking>
         <search>
            <requestID>testroger</requestID>
            <!--Optional:-->
            <pro>XXXXXX</pro>
         </search>
         <debug>N</debug>
      </v1:shipmentTracking>
   </soapenv:Body>
</soapenv:Envelope>

I've omitted the base 64 encoded Basic Auth information above, but I assure you I am using the exact same value in my request.

My request is below, using node.js. I should note that I am providing proxy information in my request, but I have verified that it works in other request functions.

function estes(obj) {

    var auth = 'Basic XXXXXXX'

    var url = 'https://api.estes-express.com:443/ws/estesrtshipmenttracking.base.ws.provider.soapws:EstesShipmentTracking/estesrtshipmenttracking_base_ws_provider_soapws_EstesShipmentTracking_Port'

    const request = require('request')
    const fs = require('fs');
    const xml = fs.readFileSync('estessample.xml', 'utf-8');

    request.post({
        uri: url,
        headers: {
            'SOAPAction': 'estesrtshipmenttracking_base_ws_provider_soapws_EstesShipmentTracking_Binder_shipmentTracking',
            'Content-Type': 'text/xml;charset=UTF-8',
            'Content-Length': xml.length,
            'Host': 'api.estes-express.com:443',
            'Authorization': auth
        },
        proxy: 'XXXXXX',
        body: xml
    }, function (error, response, body) {
        console.log(body)

        fs.writeFile("response.txt", body, (err) => {
            if (err) console.log(err);
            console.log("Successfully Written to File.");
        });
    })
}

This is the XML that I am posting to their service (estessample.xml), which is the same as what the Estes web services team was using that worked above:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="https://api.estes-express.com/ws/tools/shipment/tracking/v1.1/">
   <soapenv:Header/>
   <soapenv:Body>
      <v1:shipmentTracking>
         <search>
            <requestID>testroger</requestID>
            <!--Optional:-->
            <pro>XXXXXXX</pro>
         </search>
         <debug>N</debug>
      </v1:shipmentTracking>
   </soapenv:Body>
</soapenv:Envelope>

And lastly, here is the error I am receiving in response.xml:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>soapenv:Client</faultcode>
         <faultstring>[ISS.0088.9164] Access to WSDescriptor estesrtshipmenttracking.base.ws.provider.soapws:EstesShipmentTracking denied.</faultstring>
         <faultactor>http://api.estes-express.com/tools</faultactor>
         <detail>
            <webM:exception xmlns:webM="http://www.webMethods.com/2001/10/soap/encoding">
               <webM:className>com.wm.app.b2b.server.AccessException</webM:className>
               <webM:message xml:lang="">[ISS.0088.9164] Access to WSDescriptor estesrtshipmenttracking.base.ws.provider.soapws:EstesShipmentTracking denied.</webM:message>
            </webM:exception>
         </detail>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>



from SOAPUI and Node.JS/Request- AccessException

Using angular inside Aspx page

Scenario: Use an angular app inside an aspx page.

Issue: Aspx page has some scripts placed in an asset folder in one place, and angular's code is placed inside "Areas/Navigation/www". When I build the code using ng build --prod --base-href Areas/Navigation/View/www/, it generates the single index file.

I used all the js file reference in my aspx page

<script language="javascript" type="text/javascript" src="Areas/Navigation/View/www/runtime.js"></script>
<script language="javascript" type="text/javascript" src="Areas/Navigation/View/www/es2015-polyfills.js" nomodule></script>
<script language="javascript" type="text/javascript" src="Areas/Navigation/View/www/polyfills.js"></script>
<script language="javascript" type="text/javascript" src="Areas/Navigation/View/www/styles.js"></script>
<script language="javascript" type="text/javascript" src="Areas/Navigation/View/www/vendor.js"></script>
<script language="javascript" type="text/javascript" src="Areas/Navigation/View/www/main.js"></script>
<base href="Areas/Navigation/View/www/" />
....
<app-navigation></app-navigation>

But when i run the application, It's expecting my aspx js/css files to be inside Areas/Navigation/View/www/. How can I solve his?

Update #1:

I tried using ng build, the angular app is rendered in the aspx project but the fonts and transalation file is not loaded.

enter image description here

Actually the en-US.json and the fonts resides in https://localhost:44301/Areas/Navigation/View/www

Update #2:

The fonts are actually from an node package. Its not my font but a third party node package which uses these fonts.



from Using angular inside Aspx page

Dynamic REST API call angular

I have been successful in accessing static API data on the page. I am now trying to access dynami API. I have read some documentation to access the dynamic API, but the documentation by API provider is different from online resources. I am not sure what changes I have to make in existing code to access dynamic API data. Here is the link from API provider - https://drive.google.com/file/d/0B2HH3TWuI4Fdc3RfNGVocy1pT0tuSXlLdHlPMUZSRG5GTWJV/view. I am also confused about the contracts and getter, setter mentioned in the documentation. How and where should I use them?

Here is my code for accessing Name, Line and MoneyLine data from static json API - https://sportsbook.draftkings.com/api/odds/v1/leagues/3/offers/gamelines.json

How can I make use of the documentation and access live API data?

api.component.ts code

import {Component} from '@angular/core';
import {HttpClient} from '@angular/common/http'
import {forkJoin} from 'rxjs';
import {map} from 'rxjs/operators';

@Component({
  selector: 'app-mlb-api',
  templateUrl: './mlb-api.component.html',
  styleUrls: ['./mlb-api.component.css']
})
export class MlbApiComponent  {
//allhomeTeamName;
//allawayTeamName;
allline;
allOdds;
allName;
all: Array<{line: string, name: string,oddsAmerican:string}> = [];
firstLinePerGame: Array<string>;
oddsAmericans: Array<string>;

  constructor(private http: HttpClient) {}

  ngOnInit() {

    const character = this.http.get('https://sportsbook.draftkings.com/api/odds/v1/leagues/3/offers/gamelines.json').pipe(map((re: any) => re.events));
    const characterHomeworld = this.http.get('https://www.fantasylabs.com/api/sportevents/3/2019_06_17');

    this.firstLinePerGame = new Array<string>();
    //this.oddsAmericans = new Array<string>();

    forkJoin([character, characterHomeworld]).subscribe(([draftkingsResp, fantasylabsResp]) => {      

      //this.allhomeTeamName = draftkingsResp.map(r => r.homeTeamName);
      //this.allawayTeamName = draftkingsResp.map(r => r.awayTeamName);
      this.allName = draftkingsResp.map(r => r.name);
      this.allline = draftkingsResp.map(r=>r.offers).flat().map(r => r.outcomes).flat().map(o => o.line);
      this.allline = this.allline.filter(l => !!l);
      this.allOdds = draftkingsResp.map(r => r.offers).flat().map(r=>r.outcomes[0]).flat().map(o=>o.oddsAmerican);
      this.createAllArray();      


    });
  }

  createAllArray(): void {
    for (let i = 0; i < this.allline.length; i++) {
      let item = {
        line: this.allline[i],
        //awayTeam: this.allawayTeamName[i],
        //homeTeam: this.allhomeTeamName[i],
        name:this.allName[i],
        oddsAmerican: this.allOdds[i]
      }
      this.all.push(item);
    }
  }
}

api.component.html code

<table class="table table-striped table-condensed table-hover">
  <thead>
      <tr>

        <!--   <th class="awayTeamName">awayTeamName&nbsp;<a ng-click="sort_by('awayTeamName')"><i class="icon-sort"></i></a></th>
          <th class="field3">homeTeam&nbsp;<a ng-click="sort_by('HomeTeam')"><i class="icon-sort"></i></a></th>
 -->           <th class="field3">Name&nbsp;<a ng-click="sort_by('Name')"><i class="icon-sort"></i></a></th>
            <th class="line">Line&nbsp;<a ng-click="sort_by('line')"><i class="icon-sort"></i></a></th>
             <th class="field3">Money Line&nbsp;<a ng-click="sort_by('oddsAmericans')"><i class="icon-sort"></i></a></th>
      </tr>
  </thead>

  <tbody>
    <ng-container *ngFor="let item of all| paginate: { itemsPerPage: 5, currentPage: p }; let i = index">
      <tr>
        <td></td>
<!--         <td></td>
        <td> </td> -->
                <td></td>

        <td></td>

      </tr>
    </ng-container>
  </tbody>
</table> 


<pagination-controls (pageChange)="p = $event"></pagination-controls>



from Dynamic REST API call angular

Unexpected results with CuDNNLSTM (instead of LSTM) layer

I have posted this question as an issue in Keras' Github but figured it might reach a broader audience here.


System information

  • Have I written custom code (as opposed to using example directory): Minimal change to official Keras tutorial
  • OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Ubuntu 18.04.2 LTS
  • TensorFlow backend (yes / no): yes
  • TensorFlow version: 1.13.1
  • Keras version: 2.2.4
  • Python version: 3.6.5
  • CUDA/cuDNN version: 10.1
  • GPU model and memory: Tesla K80 11G

Describe the current behavior
I am executing the code from the Seq2Seq tutorial. The one and only change I made was to swap the LSTM layers for CuDNNLSTM. What happens is that the model predicts a fixed output for any input I give it. When I run the original code, I get sensible results.

Describe the expected behavior
See preceding section.

Code to reproduce the issue
Taken from here. Simply replace LSTM with CuDNNLSTM.


Any insights are greatly appreciated.



from Unexpected results with CuDNNLSTM (instead of LSTM) layer

How to get Webpack to use already existing source maps when generating source maps?

I have JavaScript code and source maps generated from TypeScript code (using tsc).

I then have a second compilation step which bundles the code using webpack.

I have enabled source maps in webpack.config.js:

module.exports = {
  devtool: "source-map"
}

The generated source map isn't entirely right.

Webpack is not taking into account the existing source maps that have been generated from TypeScript code.

This results in a mapping to the JavaScript code instead of the TypeScript code.

How can I get the Webpack source map to include existing mapping?

EDIT:

After renaming my question, and searching for my renamed question on Google, I found an answer.

You can use a preloader with webpack called source-map-loader: https://webpack.js.org/loaders/source-map-loader/

However, after installing source-map-loader and updating webpack.config.js to the following, the existing source maps are still not used:

module.exports = {
  devtool: "source-map",
  module: {
    rules: [
      {
        test: /\.js$/,
        use: ["source-map-loader"],
        enforce: "pre"
      }
    ]
  }
}

My guess is that because the files my existing source map point to are located outside the entry directory in webpack.config.js, they are ignored...?



from How to get Webpack to use already existing source maps when generating source maps?

Create a custom button plugin in Summernote

I'm trying to create a custom button plugin in Summernote, but the ui.button creates of course, a button. Is there any way to make that a div for example?

context.memo('button', function() {
                return ui.buttonGroup([
                    ui.button({
                        className: 'someClass',
                        tooltip: 'tooltipInfo',
                        data: {
                            toggle: 'dropdown'
                        },
                        click: function() {}
                    }),

What I tried is to do:

var buttonGroup = ui.buttonGroup([ ... ]);
buttonGroup.changeTag('div');
return buttonGroup;

Then update manually the button and change its tag to div. It "works" but for instance, the click event in the buttonGroup that I set doesn't work in this case. Even tried attaching an on('click') event to buttonGroup variable, and still, the click isn't triggering.

Any ideas on how I can achieve this in another way?



from Create a custom button plugin in Summernote

IActiveScriptParse32::ParseScriptText Memory Leak

Has anybody ever faced a memory leak problem with IActiveScriptParse32::ParseScriptText when using it in C#? I need a ScriptEngine that is able to parse JavaScript-Code. (Everything works fine, except the used memory)

The problem is, that the longer my passed JavaScript-Code is, the more unmanaged memory is allocated by the function "ParseScriptText".

I have no idea how to free the allocated space. I actually already run Marshal.ReleaseComObject(parse32) after parsing my script but somehow the used memory does not go down anymore.



from IActiveScriptParse32::ParseScriptText Memory Leak

Device orientation using Quaternion

I've written a JS SDK that listens to mobile device rotation, providing 3 inputs:

α : An angle can range between 0 and 360 degrees
β : An Angle between -180 and 180 degrees
γ : An Angle between -90 to 90 degrees

Documentation for device rotation

I have tried using Euler Angles to determine the device orientation but encountered the gimbal lock effect, that made calculation explode when the device was pointing up. That lead me to use Quaternion, that does not suffer from the gimbal lock effect.

I've found this js library that converts α,β and γ to a Quaternion, so for the following values:

α : 81.7324
β : 74.8036
γ : -84.3221

I get this Quaternion for ZXY order:

w: 0.7120695154301472
x: 0.6893688637611577
y: -0.10864439143062626
z: 0.07696733776346154

Code:

var rad = Math.PI / 180;
window.addEventListener("deviceorientation", function(ev) {

  // Update the rotation object
  var q = Quaternion.fromEuler(ev.alpha * rad, ev.beta * rad, ev.gamma * rad, 'ZXY');

  // Set the CSS style to the element you want to rotate
  elm.style.transform = "matrix3d(" + q.conjugate().toMatrix4() + ")";

}, true);


Visualizing the device orientation using 4d CSS matrix derived from the Quaternion Reflected the right device orientation (DEMO, use mobile):
enter image description here


Wrong visualizing with Euler Angels and the developer tools (DEMO, use mobile):
enter image description here


I would like to write a method that gets α,β and γ and outputs if the device is in one of the following orientations:

  • portrait
  • portrait upside down
  • landscape left
  • landscape right
  • display up
  • display down

Defining each orientation as a range of +- 45° around the relevant axes.

What approach should I take?



from Device orientation using Quaternion

Device orientation using Quaternion

I've written a JS SDK that listens to mobile device rotation, providing 3 inputs:

α : An angle can range between 0 and 360 degrees
β : An Angle between -180 and 180 degrees
γ : An Angle between -90 to 90 degrees

Documentation for device rotation

I have tried using Euler Angles to determine the device orientation but encountered the gimbal lock effect, that made calculation explode when the device was pointing up. That lead me to use Quaternion, that does not suffer from the gimbal lock effect.

I've found this js library that converts α,β and γ to a Quaternion, so for the following values:

α : 81.7324
β : 74.8036
γ : -84.3221

I get this Quaternion for ZXY order:

w: 0.7120695154301472
x: 0.6893688637611577
y: -0.10864439143062626
z: 0.07696733776346154

Code:

var rad = Math.PI / 180;
window.addEventListener("deviceorientation", function(ev) {

  // Update the rotation object
  var q = Quaternion.fromEuler(ev.alpha * rad, ev.beta * rad, ev.gamma * rad, 'ZXY');

  // Set the CSS style to the element you want to rotate
  elm.style.transform = "matrix3d(" + q.conjugate().toMatrix4() + ")";

}, true);


Visualizing the device orientation using 4d CSS matrix derived from the Quaternion Reflected the right device orientation (DEMO, use mobile):
enter image description here


Wrong visualizing with Euler Angels and the developer tools (DEMO, use mobile):
enter image description here


I would like to write a method that gets α,β and γ and outputs if the device is in one of the following orientations:

  • portrait
  • portrait upside down
  • landscape left
  • landscape right
  • display up
  • display down

Defining each orientation as a range of +- 45° around the relevant axes.

What approach should I take?



from Device orientation using Quaternion

Equivalent to googlechrome://myurl.com for Safari

I am having some issues with my webapp where if the user clicks the link from Facebook app it will use it's own browser/webview, but it is required to use Safari or Chrome in order to run the page.

While researching (this issue), I found that you can use googlechrome://navigate?url=example.com from a Android device to open chrome, and googlechrome://myurl.com from a iOS to open Chrome aswell, but I need a way to open Safari if the user's device is iOS.

Is there a way to do so?

Ps.: The link the user clicks in Facebook goes to a landing page, and in this page there is a button to the webapp. When the user clicks this button I will open Chrome/Safari.

Thanks in advance!



from Equivalent to googlechrome://myurl.com for Safari

How do I keep standard 'select all' and 'copy' menu items in the WebView text selection menu?

I need to extend android WebView's text selection menu with my custom commands. So far I have managed to implement my custom webview text selection menu the following way:

public class CustomActionWebView extends WebView {

    static String TAG = "CustomActionWebView";

    ActionMode mActionMode;

    int mMenuID;
    Activity mParentAct;

    ActionSelectListener mActionSelectListener;
    ButtonClickListener mButtonClick;

    public CustomActionWebView(Context context) {
        super(context);
    }

    public CustomActionWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomActionWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setActionMenu(int mActionMenu, Activity ParentAct) {

        setWebViewClient(new CustomWebViewClient());
        this.mMenuID = mActionMenu;
        mParentAct = ParentAct;
    }

    private ActionMode resolveActionMode(ActionMode actionMode) {
        if (actionMode != null) {
            final Menu menu = actionMode.getMenu();
            mActionMode = actionMode;
            menu.clear();

            mParentAct.getMenuInflater().inflate(mMenuID, menu);

            for (int i = 0; i < menu.size(); i++) {
                MenuItem mi = menu.getItem(i);

                mi.setOnMenuItemClickListener(item -> {
                    int id=item.getItemId();
                    if(id == R.id.cab_select_all)
                    {
                        String js = "var el =document.getElementsByTagName(\"BODY\")[0]; el.setSelectionRange(0, el.value.length); alert(el.value);)";
                        evaluateJavascript("javascript:" + js, null);
                    }
                    else getSelectedData( item.getItemId());
                    releaseAction();
                    return true;
                });

            }

        }
        mActionMode = actionMode;
        return actionMode;
    }

    @Override
    public ActionMode startActionMode(ActionMode.Callback callback) {
        ActionMode actionMode = super.startActionMode(callback);
        return resolveActionMode(actionMode);
    }

    @Override
    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
        ActionMode actionMode = super.startActionMode(callback, type);
        return resolveActionMode(actionMode);
    }

    private void releaseAction() {
        if (mActionMode != null) {
            mActionMode.finish();
            mActionMode = null;
        }
    }

    private void getSelectedData(int menuID) {


        String js2 = "(function getSelectedText() {" +
                "var txt;" +
                "var parentID;" +
                "var test;" +
                "var menuID = " + menuID + ";" +
                "if (window.getSelection) {" +
                "txt = window.getSelection().toString();" +
                "parentID = window.getSelection().baseNode.parentNode.id;"+
                "test = '1st';"+
                "} else if (window.document.getSelection) {" +
                "txt = window.document.getSelection().toString();" +
                "parentID = window.document.getSelection().baseNode.parentNode.id;"+
                "test = '2nd';"+
                "} else if (window.document.selection) {" +
                "txt = window.document.selection.createRange().text;" +
                "parentID = window.document.selection.baseNode.parentNode.id;"+
                "test = '3rd';"+
                "}" +
                "JSInterface.callback(txt, menuID, parentID);" +
                "})()";


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            evaluateJavascript("javascript:" + js2, null);
        } else {
            loadUrl("javascript:" + js2);
        }
    }

    public void linkJSInterface() {
        addJavascriptInterface(new ActionSelectInterface(this), "JSInterface");
        addJavascriptInterface(new ButtonClickInterface(this), "ButtonClick");
    }

    public void setActionSelectListener(ActionSelectListener actionSelectListener) {
        this.mActionSelectListener = actionSelectListener;
    }

    public void setVerseToolbarClickListener(ButtonClickListener mButtonClick) {
        this.mButtonClick = mButtonClick;
    }

    public void dismissAction() {
        releaseAction();
    }


    private class ActionSelectInterface {

        CustomActionWebView mContext;

        ActionSelectInterface(CustomActionWebView c) {
            mContext = c;
        }

        @JavascriptInterface
        public void callback(final String value, final int menuID, final String parentDivID) {
            if (mActionSelectListener != null) {
                mActionSelectListener.onTextSelectionMenuClick(menuID, value, parentDivID);
            }
        }

        @JavascriptInterface
        public void hl_click(long row_id) {
            if (mActionSelectListener != null) {
                mActionSelectListener.onHighlightClick(row_id);
            }
        }
    }

    private class ButtonClickInterface {

        CustomActionWebView mContext;

        ButtonClickInterface(CustomActionWebView c) {
            mContext = c;
        }

        @JavascriptInterface
        public void call(final String id) {
            if (mButtonClick != null) {
                mButtonClick.onClick(id);
            }
        }
    }


    private class CustomWebViewClient extends WebViewClient {

        private boolean mLastLoadFailed = false;

        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);
            if (!mLastLoadFailed) {
                CustomActionWebView customActionWebView = (CustomActionWebView) webView;
                customActionWebView.linkJSInterface();

            }
        }

        @Override
        public void onPageStarted(WebView webView, String url, Bitmap favicon) {
            super.onPageStarted(webView, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            mLastLoadFailed = true;
        }
    }


}

However this implementation results in the absence of the standard webview "COPY" and "SELECT ALL" menu items. I could implement my own COPY menu item, however I don't know how to have equivalent of the standard "SELECT ALL" menu item or to implement my own custom webview menu in such a way so that it preserves the standard ones. Can anyone please suggest how can I have "SELECT ALL" menu item working?



from How do I keep standard 'select all' and 'copy' menu items in the WebView text selection menu?

How to get frame by frame from MP4?

Actually I am working with OpenGL and I would like to put all my textures in MP4 in order to compress them.

Then I need to get it from MP4 on my Android

I need somehow decode MP4 and get frame by frame by request.

I found this MediaCodec

https://developer.android.com/reference/android/media/MediaCodec

and this MediaMetadataRetriever

https://developer.android.com/reference/android/media/MediaMetadataRetriever

But I did not see approach how to request frame by frame...

If there is someone who worked with MP4, please give me a way where to go.

P.S. I am working with native way (JNI), so does not matter how to do it.. Java or native, but I need to understand the concept.

EDIT1

I make some kind of movie (just one 3d model), so I am changing my geometry as well as textures every 32 milliseconds. So, it is seems to me reasonable to use mp4 for tex because of each new frame (32 milliseconds) very similar to privious one...

Now I use 400 frames for one model. For geometry I use .mtr and for tex I use .pkm (because it optimized for android) , so I have around 350 .mtr files(because some files include subindex) and 400 .pkm files ...

This is the reason why I am going to use mp4 for tex. Because one mp4 much more smaller than 400 .pkm

EDIT2

Plase take a look at Edit1

Actually all that I need to know is there API of Android that could read MP4 by frames? Maybe some kind of getNextFrame() method?

Something like this

MP4Player player = new MP4Player(PATH_TO_MY_MP4_FILE);

void readMP4(){
   Bitmap b;

   while(player.hasNext()){
      b = player.getNextFrame();

      ///.... my code here ...///
   }
}



from How to get frame by frame from MP4?

Full screen toggle for jQuery video player does not assign class-name correctly

I am working on a JavaScript/jQuery video player. It has a bug whose cause I was unable to find.

The players has, among others, an enter/exit full-screen button (it can be seen at the bottom of the HTML snippet):

(function($) {

  /* Helper functions */
  /* 1) full screen */
  function toggleFullScreen(elem) {
    if ((document.fullScreenElement !== undefined && document.fullScreenElement === null) || (document.msFullscreenElement !== undefined && document.msFullscreenElement === null) || (document.mozFullScreen !== undefined && !document.mozFullScreen) || (document.webkitIsFullScreen !== undefined && !document.webkitIsFullScreen)) {
      if (elem.requestFullScreen) {
        elem.requestFullScreen();
      } else if (elem.mozRequestFullScreen) {
        elem.mozRequestFullScreen();
      } else if (elem.webkitRequestFullScreen) {
        elem.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
      } else if (elem.msRequestFullscreen) {
        elem.msRequestFullscreen();
      }
    } else {
      if (document.cancelFullScreen) {
        document.cancelFullScreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }
    }
  }

  $('video').each(function() {
    var video = $(this)[0],
      videoContainer = video.closest('div'),
      $playToggleBtn = $(videoContainer).find('input[name="play-pause"]'),
      $progressBar = $(videoContainer).find('.progress-bar'),
      $progress = $(videoContainer).find('.progress'),
      $current_time = $(videoContainer).find('.current-time'),
      $durationDisplay = $(videoContainer).find('.duration'),
      $volumeSlider = $(videoContainer).find('.volume-slider'),
      $mute_toggle = $(videoContainer).find('.mute-toggle'),
      $muteBtn = $mute_toggle.find('input[type="checkbox"]'),
      $rate_display = $(videoContainer).find('.rate_display'),
      $fullScreenToggler = $(videoContainer).find('input[name="screen-toggler"]'),
      $playSpeed = $(videoContainer).find('.playback-rate ul li');

    $(document).bind('webkitfullscreenchange mozfullscreenchange fullscreenchange', function(e) {
      var state = document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen;
      var event = state ? 'FullscreenOn' : 'FullscreenOff';

      if (event === 'FullscreenOff') {
        $(videoContainer).removeClass('fullscreen');
        $fullScreenToggler.removeClass('exit');
      } else {
        $(videoContainer).addClass('fullscreen');
        $fullScreenToggler.addClass('exit');
      }
    });

  });

})(jQuery);

<div class="video-container">
  <video poster="posters/poster.jpg">
            <source src="videos/mymovie.mp4" type="video/mp4" />
        </video>
  <div class="controls-wrapper">
    <div class="progress-bar">
      <div class="progress"></div>
    </div>
    <ul class="video-controls">
      <li><input type="button" name="play-pause" value="Play" class="play" /></li>
      <li><a href="#" class="previous">Previous</a></li>
      <li><a href="#" class="next">Next</a></li>
      <li class="mute-toggle unmuted"><input type="checkbox" name="mute" /></li>
      <li><input type="range" min="0" max="1" step="0.01" class="volume-slider" /></li>
      <li><span class="current-time"></span><span>/</span><span class="duration"></span></li>
      <li class="playback-rate">
        <span class="rate_display">Normal</span>
        <div class="piker">
          <ul class="dropdown-content" id="rate_selector">
            <li data-rate="0.5">0.5x</li>
            <li data-rate="0.75">0.75x</li>
            <li data-rate="1">Normal</li>
            <li data-rate="1.125">1.125x</li>
            <li data-rate="1.5">1.5x</li>
            <li data-rate="2">2x</li>
          </ul>
        </div>
      </li>
      <li class="fullscreen-container">
        <input type="button" name="screen-toggler" value="Fullscreen" class="toggle-fullscreen" />
      </li>
    </ul>
  </div>
</div>

The problem: If I have two videos (or more), even if I click the full-screen button of the first clip, the fullscreen class-name will be added to all the video-container elements on the page.

Why does that happen?



from Full screen toggle for jQuery video player does not assign class-name correctly

Browser not sending cookies cross-origin cross domain with CORS enabled

I have a .net core webapi project set up to accept cross origin requests like so

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseCors(opts => opts
        .WithOrigins("https://fiddle.jshell.net")
        .AllowCredentials()
        .AllowAnyMethod()
        .AllowAnyHeader());

    app.UseHttpsRedirection();
    app.UseMvc();
}

This has a values controller with a GET method like so

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return Ok("cookies: " + string.Join(", ", HttpContext.Request.Cookies.Select(x => x.Key)));
    }
}

Now I am trying to send a fetch request from the browser like so

fetch('https://api.domain.com/api/values', { 
    headers: 
  { 
    'Content-Type': 'application/json' 
    }, 
    credentials: 'include', 
    mode: 'cors'
})
.then(function(resp){ 
    resp.text().then(function(data) { 
        console.log(data); 
  }) 
})
.catch(function(err){ 
    console.log(err) 
});

But this doesn't send the cookies from the page to the api. What am I missing here? I have tried all the solutions I could find about this including turning off third party cookies

Update I should mention that cookies from the same domain are being sent but not from a sub-domain. For example if the backend url is api.domain.com and then UI is at ui.domain.com the any cookies that belong to domain.com are sent along but those belonging to ui.domain.com are not.



from Browser not sending cookies cross-origin cross domain with CORS enabled

Running Python Code in .NET Environment without Installing Python

Is it possible to productionize Python code in a .NET/C# environment without installing Python and without converting the Python code to C#, i.e. just deploy the code as is?

I know installing the Python language would be the reasonable thing to do but my hesitation is that I just don't want to introduce a new language to my production environment and deal with its testing and maintenance complications, since I don't have enough manpower who know Python to take care of these issues.

I know IronPython is built on CLR, but don't know how exactly it can be hosted and maintained inside .NET. Does it enable one to treat PYthon code as a "package" that can be imported into C# code, without actually installing Python as a standalone language? How can IronPython make my life easier in this situation? Can python.net give me more leverage?



from Running Python Code in .NET Environment without Installing Python

KeyError: 8144 iterate through full data set - works on small set

Thanks for stopping by. I was hoping to get some help with an error. Here is my code:

a = ldamallet[bow_corpus_new[:751950]]

here is the error: error

So if I check the length of the bow_corpus:

length of corpus

It is the right length. What is weird is that this code:

a = ldamallet[bow_corpus_new[:36000]]

runs just fine:

shape of bow_corpus

I just can't get it to iterate through the whole data set :( pls help

The data:

bow_corpus

bow corpus 8144



from KeyError: 8144 iterate through full data set - works on small set

TypeError: Cannot read property 'left' of undefined

function roadsAndLibraries(n, c_lib, c_road, cities) {
    console.log("roadsAndLibraries n--->", n);
    console.log("roadsAndLibraries c_lib--->", c_lib);
    console.log("roadsAndLibraries c_road--->", c_road);
    console.log("roadsAndLibraries cities--->", cities);
    var m = new Map();
    m.set('a', 2);
    m.set('b', 3);
    m.set('b', 3);
    m.set('b', 2);
    m.set('b', 1);

    console.log("map value--->", m);
        // Check that a root node exists.

    // if (rootNode === null) {
    //     return;
    // }

    // Check that a root node exists.
    if (n === null) {
        console.log("n root node--->", n);
        return;
    }

    // Create our queue and push our root node into it.
    // var queue = [];
    // queue.push(rootNode);

    // Create our queue and push our root node into it.
    var queue = [];
    queue.push(n);

    console.log(" queue.push--->", queue);


    while (queue.length > 0) {
        // Create a reference to currentNode, at the top of the queue.
        var currentNode = queue[0];

        // If currentNode has a left child node, add it to the queue.
        if (currentNode.left !== null) {
            queue.push(currentNode.left)
        }
        // If currentNode has a right child node, add it to the queue.
        if (currentNode.right !== null) {
            queue.push(currentNode.right)
        }
        // Remove the currentNode from the queue.
        queue.shift()
    }




}



from TypeError: Cannot read property 'left' of undefined

Unable to go from tf.keras model -> quantized frozen graph -> .tflite with TOCO

I am new to all of these tools. I'm trying to get started with using Tensorflow Lite to ultimately run my own deep learning models on the Coral Edge TPU.

I have built a toy XOR network with the Keras API, written out the tensorflow graph, and frozen it. Now I'm trying to use TOCO to convert the frozen model to tflite format. I'm getting the following error:

ValueError: Input 0 of node dense_1/weights_quant/AssignMinLast was passed float from dense_1/weights_quant/min:0 incompatible with expected float_ref.

I have seen others talking about similar errors on github but I have not been able to find a solution.

Full code below:

training_data = np.array([[0,0],[0,1],[1,0],[1,1]], "uint8")
target_data = np.array([[0],[1],[1],[0]], "uint8")

model = Sequential()
model.add(Dense(16, input_dim=2, use_bias=False, activation='relu'))
model.add(Dense(1, use_bias=False, activation='sigmoid'))

session = tf.keras.backend.get_session()
tf.contrib.quantize.create_training_graph(session.graph)
session.run(tf.global_variables_initializer())

model.compile(loss='mean_squared_error',
              optimizer='adam',
              metrics=['binary_accuracy'])

model.fit(training_data, target_data, nb_epoch=1000, verbose=2)
print model.predict(training_data).round()
model.summary()

saver = tf.train.Saver()
saver.save(keras.backend.get_session(), 'xor-keras.ckpt')

tf.io.write_graph(session.graph, '.', 'xor-keras.pb')

Then freeze the model:

python freeze_graph.py \
  --input_graph='xor-keras.pb' \
  --input_checkpoint='xor-keras.ckpt' \
  --output_graph='xor-keras-frozen.pb' \
  --output_node_name='dense_2/Sigmoid'

Then calling toco like this:

toco \
  --graph_def_file=xor-keras-frozen.pb \
  --output_file=xor-keras-frozen.tflite \
  --input_shapes=1,2 \
  --input_arrays='dense_1_input' \
  --output_arrays='dense_2/Sigmoid' \
  --inference_type=QUANTIZED_UINT8

Here is the full output from TOCO:

2019-06-26 15:31:17.374904: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 AVX512F FMA
2019-06-26 15:31:17.404237: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2600000000 Hz
2019-06-26 15:31:17.407613: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x55bbcf9a5ed0 executing computations on platform Host. Devices:
2019-06-26 15:31:17.407741: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): <undefined>, <undefined>
Traceback (most recent call last):
  File "/home/redacted/.local/bin/toco", line 11, in <module>
    sys.exit(main())
  File "/home/redacted/.local/lib/python2.7/site-packages/tensorflow/lite/python/tflite_convert.py", line 503, in main
    app.run(main=run_main, argv=sys.argv[:1])
  File "/home/redacted/.local/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 40, in run
    _run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef)
  File "/home/redacted/.local/lib/python2.7/site-packages/absl/app.py", line 300, in run
    _run_main(main, args)
  File "/home/redacted/.local/lib/python2.7/site-packages/absl/app.py", line 251, in _run_main
    sys.exit(main(argv))
  File "/home/redacted/.local/lib/python2.7/site-packages/tensorflow/lite/python/tflite_convert.py", line 499, in run_main
    _convert_tf1_model(tflite_flags)
  File "/home/redacted/.local/lib/python2.7/site-packages/tensorflow/lite/python/tflite_convert.py", line 124, in _convert_tf1_model
    converter = _get_toco_converter(flags)
  File "/home/redacted/.local/lib/python2.7/site-packages/tensorflow/lite/python/tflite_convert.py", line 111, in _get_toco_converter
    return converter_fn(**converter_kwargs)
  File "/home/redacted/.local/lib/python2.7/site-packages/tensorflow/lite/python/lite.py", line 628, in from_frozen_graph
    _import_graph_def(graph_def, name="")
  File "/home/redacted/.local/lib/python2.7/site-packages/tensorflow/python/util/deprecation.py", line 507, in new_func
    return func(*args, **kwargs)
  File "/home/redacted/.local/lib/python2.7/site-packages/tensorflow/python/framework/importer.py", line 431, in import_graph_def
    raise ValueError(str(e))
ValueError: Input 0 of node dense_1/weights_quant/AssignMinLast was passed float from dense_1/weights_quant/min:0 incompatible with expected float_ref.



from Unable to go from tf.keras model -> quantized frozen graph -> .tflite with TOCO

Unable to catch and input some dynamically generated number in an inputbox to populate some result

Hello I am trying to scrape information from a website https://www.nsekra.com/. We need to select Non-Individual from dropdown then enter the PAN as AAAHA0064Q, and the captcha number which generates a random number every time the website is visited or opened. After that we need to press Search button so that the required information can be fetched.

import requests
from bs4 import BeautifulSoup

resp = requests.get('https://www.nsekra.com/')
soup = BeautifulSoup(resp.text,'lxml')
dictinfo = {i['name']:i.get('value','') for i in soup.select('input[name]')}

# trying to enter PAN as 'AAAHA0064Q'
dictinfo['txtPan']='AAAHA0064Q'

# trying to get captcha number & passing to textbox
captcha_number = soup.select_one("#lblDynamicCode").text
print('Fetched Catpcha No. -> ',captcha_number);
dictinfo['txtImageBox'] = captcha_number

# passsing pan no. & captcha number to the request method  
resp2 = requests.post('https://www.nsekra.com/',data=dictinfo)
soup2 = BeautifulSoup(resp2.text,'lxml')
name = soup2.select_one('#lblKra_name').text
print('KRA Name : '+name)

OUTPUT

print('Fetched Catpcha No. -> ',s);

Fetched Catpcha No. -> 757205

print(soup2.prettify());

enter image description here

print('KRA Name : '+name)

KRA Name : &nbsp

Expected Output

KRA Name : CVL KRA

As you can see I able to get the captcha number, but when I'm trying to passed it to the website, it regenerating new number everytime when the website is visited. So basically, the above code does fetch the captcha number but while visting to the website, new number is generated & instead of new number, the old or previous number is passed, & not the current one at when the website is visited. How can I grab and make use of that dynamically generated number in order to fetch the results I'm interested in?I like to stick to the requests library to get it done.



from Unable to catch and input some dynamically generated number in an inputbox to populate some result

How to define class field in Python that is an instance of a class?

I want to get a specific class instance in the class's namespace. In C# this would look like this:

public struct Foo
{
    public readonly static Bar = new Foo();
}

The only idea I have is to assign an instance right after the class definition (monkeypatch):

class Foo:
    def __init__(self, spam):
        self.spam = spam
Foo.bar = Foo(42)

But I want to provide instance in class definition, like this:

class Foo:
    ...
    bar = Foo(42)

And interface like this:

from foo import Foo
bar = Foo.bar

The last line in definition gives a syntax error because Foo is not yet defined. Is there a way to overcome this constraint except monkeypatching class?



from How to define class field in Python that is an instance of a class?

Saturday 29 June 2019

pipenv: only works in a installed folder?

Pipenv seems to work only in the directory where the Pipfile lives. Maybe I'm trying to use it in a way it is not designed for.

For example, I installed a tool called "leo" (an editor) and no surprise that I will go to many folders and start pipenv run Leo and it will start to install another virtual environment. What's the workaround?



from pipenv: only works in a installed folder?

NuxtJS $axios Send Cookies With Request

I am using NuxtJS's $axios module and I am interacting with a backend API that set's an authentication cookie for further authenticated requests after logging in. I've looked into withCredentials: true, but it is still not cooperating properly.

Do I need to set a specific header value or is something wrong with my axios configuration?

I just want to keep and use this cookie received from logging in successfully and use it in the next requests to make authenticated requests.

// nuxt.config.js
axios : {
    ...
    credentials: true,
    withCredentials : true,
    requestInterceptor: (config, {store}) => {
        config.headers.common['Content-Type'] = 'application/json';
        config.headers.common['API-Key'] = 'my_api_key';
        return config
    },
    ...
},

and here is where I am making my axios request


async asyncData({ $axios}) {
    try {
        // this response sends back an authentication cookie
        const login_response = await $axios.$post("my_login_route",{
            password : this.password,
            username : this.email,
        });

        if(login_response.success){
            // how i send my cookie to this route to prove im authenticated?
            const authenticated = await $axios.$get("my_url");
            console.log(authenticated); // always false; doesn't send cookie recieved in login $post request
        }else{
            console.log("Invalid username or password");
        }
    } catch(error) {
        console.log(error);
    }
}

I've made a test page with making a simple request to check if the user is authenticated. Turns out, the axios settings in the nuxt.config.js are NOT being applied here.

I need the axios configuration to apply to not just the base URL, but to my API routes. Here is a test method that activates when I press a test button:

check_auth : async function(){
    try {
        const response = await this.$axios.$get("https://<my_url>/Utility/IsAuthenticated/");
        console.log("IS AUTH:");
        console.log(response.isAuthenticated);
    }catch(error){
        console.log("something went wrong.");
    }
},

HTTP REQUEST HEADERS FOR AXIOS REQUEST MADE RIGHT ABOVE As you can see, there are no cookies or API-Key headers that I specified in the axios config.

Host: <my_url>
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:67.0) Gecko/20100101 Firefox/67.0
Accept: application/json, text/plain
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: http://localhost:1337/send/account
Origin: http://localhost:1337
DNT: 1
Connection: keep-alive

What do I need to change in my axios nuxt.config.js section to allow the axios configuration to apply to my api route? Do i need to use the proxy:{} section?

Please help!!



from NuxtJS $axios Send Cookies With Request

Difference between keepAliveTimeout and timeout?

Reading Node's doc about server.keepAliveTimeout:

If the server receives new data before the keep-alive timeout has fired, it will reset the regular inactivity timeout, i.e., server.timeout.

How is that different from server.timeout?

It sounds like they are both about socket timeout which only start to tick on inactivity.



from Difference between keepAliveTimeout and timeout?

Even if client id is correct its giving invalid client_id message in authorize callback

Issue

I am using this library to do OAuth with Strava. It works fine till redirecting a user to the authentication page of Strava but the issue comes once the user approves the application. In error, it says that client_id is invalid but actually it isn't because 1) I double checked 2) If that's the case then it should give an error when opening authentication page but it didn't.

I don't know what is the best way to debug the error. I tried setting up debugger in Xcode but it didn't work as I was not getting a clear picture through debugging points.

I am pasting my code below:

App.js

import { authorize, refresh, revoke } from 'react-native-app-auth';

config = {
    issuer: 'https://www.strava.com/oauth/mobile/authorize',
    clientId: '***',
    clientSecret: '*********',
    redirectUrl: 'myapp://myapp.com/'
    serviceConfiguration: {
      authorizationEndpoint: 'https://www.strava.com/oauth/mobile/authorize',
      tokenEndpoint: 'https://www.strava.com/oauth/token',
      revocationEndpoint: 'https://www.strava.com/oauth/deauthorize'
    },
    additionalParameters: {
      response_type: 'code',
      approval_prompt: 'force',
      grant_type: 'authorization_code'
    },
    scopes: ['activity:read']
  };

try {
    const authState = await authorize(this.config);
} catch (error) {
    console.error(JSON.stringify(error));
}

Info.plist (iOS)

<dict>
    <key>CFBundleTypeRole</key>
    <string>Editor</string>
    <key>CFBundleURLName</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleURLSchemes</key>
    <array>
        <string>myapp://myapp.com</string>
    </array>
</dict>

AppDelegate.m

#import "AppDelegate.h"
#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"myapp"
                                            initialProperties:nil];

  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *, id> *)options {
 return [self.authorizationFlowManagerDelegate resumeExternalUserAgentFlowWithURL:url];
}

@end


I don't know what is the issue. Is it something related to code or Am I passing data wrong?



from Even if client id is correct its giving invalid client_id message in authorize callback

MediaMetadataRetriever.getFrameAtTime() returns only first frame

I have extracted frames from a video using MetadataRetriever, and have stored all images in an ArrayList<Bitmap>. I want to store all of them on an SD card (just for testing purposes).

But when I pull out a folder from the emulator and look at the saved images, all images were of the video's first frame only.

This is how I extract the frames from the video:

File videoFile=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/videos","sample_mpeg4.mp4");

Uri videoFileUri=Uri.parse(videoFile.toString());

MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(videoFile.getAbsolutePath());
ArrayList<Bitmap> rev=new ArrayList<Bitmap>();

//Create a new Media Player
MediaPlayer mp = MediaPlayer.create(getBaseContext(), videoFileUri);

int millis = mp.getDuration();
for(int i=0;i<millis;i+=100){
   Bitmap bitmap=retriever.getFrameAtTime(i,OPTION_CLOSEST_SYNC);
   rev.add(bitmap);
}

And this is how I'm saving them (I'm calling this method and passing the bitmap ArrayList):

public void saveFrames(ArrayList<Bitmap> saveBitmapList) throws IOException{
    Random r = new Random();
    int folder_id = r.nextInt(1000) + 1;

    String folder = Environment.getExternalStorageDirectory()+"/videos/frames/"+folder_id+"/";
    File saveFolder=new File(folder);
    if(!saveFolder.exists()){
       saveFolder.mkdirs();
    }

    int i=1;
    for (Bitmap b : saveBitmapList){
       ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

        File f = new File(saveFolder,("frame"+i+".jpg"));

        f.createNewFile();

        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());

           fo.flush();
           fo.close();

        i++;
    }
    Toast.makeText(getApplicationContext(),"Folder id : "+folder_id, Toast.LENGTH_LONG).show();

}

When I pull out a folder to see all frames, all of the images were of the first frame of video. Can someone please explain to me what is happening?

UPDATE:

I've tried with another video. I've found that I'm not getting blank images, but it's always returning the first frame only.

MediaMetadataRetriever.getFrameAtTime(long timeUS) is returning only the first frame, but I want to retrieve all frames. What changes should I make?

How do I tackle this?



from MediaMetadataRetriever.getFrameAtTime() returns only first frame

TD contenteditable and update value in database

I have a table which i make the td's contenteditable, for the user to easily input the data needed.

Every rows and td have value of null in database. It will have value when the user will input something and it will save/update when button save is click

my php for tbody :

 <?php
$emp_name = $_SESSION["emp_name"];
$month = $_SESSION["month"];
$REMARKS = $_SESSION[""];
$date_now = date('m');
$current_day = date('d');
$sample_var=  $_SESSION["username"] ;

        try {
            $pdo = new PDO('mysql:host=localhost:3306;dbname=******;', '****', '*****' );
            $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            $stmt = $pdo->prepare(
                " SELECT * from tbl_assessment WHERE employeeName = '{$_SESSION['emp_name']}' "
        );
        $flag = $stmt->execute();
        if ( !$flag ) {
            $info = $stmt->errorInfo();
            exit( $info[2] );
        }
        while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ) {

                @$tbody1 .='<tr>';
                    $tbody1 .=' <input type="hidden" id="id" value="'.$_SESSION['id'].'"/> ';
                    $tbody1 .=' <input type="hidden" id="emp_name" value="'.$_SESSION['emp_name'].'"/> ';
                    $tbody1 .=' <input type="hidden" id="teamCode" value="'.$_SESSION['teamCode'].'"/> ';
                    $tbody1 .=' <input type="hidden" id="sectionCode" value="'.$_SESSION['sectionCode'].'"/> ';


                    $tbody1 .='<td style="height:30px" contenteditable>'.$row["date"].'</td>';
                    $tbody1 .='<td style="height:30px" contenteditable>'.$row["staffName"].'</td>';
                    $tbody1 .='<td style="height:30px" contenteditable>'.$row["findings"].'</td>';
                    $tbody1 .='<td style="height:30px" contenteditable>'.$row["action"].'</td>';
                    $tbody1 .='<td style="height:30px" contenteditable>'.$row["date_accomplished"].'</td>';
                    $tbody1 .='<td><button class="btn btn-warning px-2" id="btnSaveFindings" style="color:black;font-weight:bold;" title="Save"><i class="fas fa-save" aria-hidden="true"></i></button><button class="btn btn-info px-2" id="btnEdit" style="color:black;font-weight:bold;" title="Edit"><i class="fas fa-edit" aria-hidden="true"></i></button></td>';


        @$tbody .='</tr>';
        }   
            }
        catch ( PDOException $e ) {
        echo $e->getMessage();
        $pdo = null;
        }   
?>

my html for table :

<div id="containerDiv" style="background-color:white;border-bottom:3px solid #ff6600;margin-left:50px;margin-right:50px;margin-bottom:140px;" class="animated fadeInUp">
    <div class=""  style="margin-left:15px;margin-right:15px;overflow-x:auto;" ><br>
        <button class="btn btn-default px-3" style="float:right;" id="btnAddRow" name="btnAddRow" title="Add New row"><i class="fas fa-plus" aria-hidden="true"></i></button>
        <table class="assessment" id="assessment" width="1526px" >
        <thead style="background:-moz-linear-gradient( white, gray);">
            <tr>    
                <th colspan="6" style="font-size:20px;">ASSESSMENT/FINDINGS:</th>
            </tr>
            <tr> <!---FIRST TABLE ROW--->
                <th>DATE</th>
                <th>NAME OF THE STAFF/S</th>
                <th>ASSESSMENT/FINDINGS</th>
                <th>ACTION TAKEN</th>
                <th>DATE ACCOMPLISHED</th>
                <th>ACTION</th>
            </tr>
            <tbody>
                <?php echo $tbody1; ?>
            </tbody>
        </thead>
    </table><br><br>
</div>

what would be the function of btnSaveFindings to update the value of td in database?



from TD contenteditable and update value in database

Javascript to load content in HTML sometimes unless element hovered inside inspect

I have made a widget. The content of this is loaded dynamically by JS. However, sometimes when a page loads the data doesnt show up on the widget unless it is clicked upon. Even going into inspect and hovering over any element loads the items. The two images below are before and after click

Update - Click doesn't necessarily loads the data but hovering inside inspect element does.

Update 2 - This seem to get fixed if I call the function tp putdata multiple times. Note- I have 15 sec timer to call the function, however if I reduce the interval of first 4 runs, it fixes. However, this seems like a workaround and not a solution.

Before click/hover After Click/Hover

Here is the function that is putting the data

function putData(dataSet) {
if(dataSet.length == 3) {
    document.getElementById('liveBlock').style.display = 'none';
    document.getElementById('upcomingCompletedBlock').style.display = 'block';
    for(var i=1; i<=3; i++) {
        title = dataSet[i-1].title;
        teams = title.split(' vs ');
        homeTeamName = teams[0];
        awayTeamName = teams[1];
        homeTeam = dataSet[i-1].homeTeamLogoUrl;
        awayTeam = dataSet[i-1].awayTeamLogoUrl;
        document.getElementById('botCupLogo'+i+'1').src=homeTeam;
        document.getElementById('botCupLogo'+i+'2').src=awayTeam;
        document.getElementById('botCupName'+i+'1').innerHTML=homeTeamName;
        document.getElementById('botCupName'+i+'2').innerHTML=awayTeamName;

        if(dataSet[i-1].matchStatus == 'UPCOMING') {
            var date = new Date(dataSet[i-1].startDateTime);
            document.getElementById('summaryText'+i).innerHTML = date;
        }
        else if(dataSet[i-1].matchStatus == 'COMPLETED') {
            document.getElementById('summaryText'+i).innerHTML = dataSet[i-1].summaryText;
        }
    }
}

It is called by a different function which fetches data from an API. The data is correctly fetched and passed into this function



from Javascript to load content in HTML sometimes unless element hovered inside inspect

Node.js - FCM send scheduled topic notification

I'm using an Angular app and a Node.js server to send topic notifications to Android devices using FCM. I am using bull to schedule the notifications.

There are two ways of sending a notification: send a notification now and send a notification at a specific date and time.

To send notifications I am using an Angular app and this method:

  sendTopicNotification(notification: Notification): Observable<any> {
    console.log("send topic");
    return this.http.post(endpoint + `notifications/send/topic/topic${notification.target}`, JSON.stringify(notification), httpOptions).pipe(
      map(result => { return true; })
    );
  }

This is my Node.js code:

const express = require('express');
const router = express.Router();
const fb = require('../firebase/fb');
const db = fb.firestore();
const fcm = fb.messaging();
const moment = require('moment');

var Queue = require('bull');
var notificationsQueue = new Queue('topic notifications', { redis: { port: 6379, host: '127.0.0.1' } }); // Specify Redis connection using object

const notificationsCollection = 'notifications';
const donationsCollection = 'donations';


router.post('/send/topic/:topic', (req, res) => {
    var topic = `/topics/${req.params.topic.toString()}`;

    var payload = {
        notification: {
            title: req.body.title,
            body: req.body.body
        }
    };

    var options = {
        priority: "high",
        timeToLive: 60 * 60 * 24
    };

    if (req.body.sendDate && req.body.sendHour) {
        var date = req.body.sendDate;
        var hour = req.body.sendHour;
        scheduleMessage(date, hour, topic, payload, options);
    } else {
        sendTopicNotification(topic, payload, options);
    }


    res.send(200);
});

//Schedule the job
async function scheduleMessage(date, hour, topic, payload, options, res) {
    var date = date.toString().split("/");
    var hour = hour.toString().split(":");
    console.log(date[2], date[1], date[0], hour[0], hour[1], 0);
    var jobDate = new Date(date[2], date[1] - 1, date[0], hour[0], hour[1]);

    console.log(jobDate);
    console.log(new Date());
    var jobDelay = ((jobDate.getTime() / 1000) - (Math.floor(new Date().getTime() / 1000)));

    console.log(jobDate.getTime() / 1000);
    console.log(Math.abs(jobDelay));
    console.log(Math.floor(new Date().getTime() / 1000));

    const job = await notificationsQueue.add({
        topic: topic,
        payload: payload,
        options: options
    }, { delay: Math.abs(jobDelay) });
    console.log(date + " " + hour);
}

//Process qued job
notificationsQueue.process(async (job, done) => {
    console.log(job.data);
    sendTopicNotification(job.data.topic, job.data.payload, job.data.options);
});

//Send notificaiton
function sendTopicNotification(topic, payload, options) {
    var currentTime = new Date().getTime();

    var target;
    switch (topic) {
        case "/topics/topicA":
            target = 'Donatorii cu grupa sanguină A'
            break;
        case "/topics/topicB":
            target = 'Donatorii cu grupa sanguină B'
            break;
        case "/topics/topicAB":
            target = 'Donatorii cu grupa sanguină AB'
            break;
        case "/topics/topic0":
            target = 'Donatorii cu grupa sanguină 0'
            break;
        case "/topics/topicAll":
            target = 'Toți donatorii'
            break;
        default:
            break;
    }
    fcm.sendToTopic(topic, payload, options)
        .then((response) => {
            db.collection(notificationsCollection).doc(currentTime.toString()).set({
                title: payload.notification.title,
                body: payload.notification.body,
                date: currentTime,
                target: target,
                status: "Notificarea a fost trimisă!"
            }).then((res) => {
                console.log('Create new notification ');
            });
            // Response is a message ID string.
            console.log('Successfully sent message:', response);
        })
        .catch((error) => {
            db.collection(notificationsCollection).doc(currentTime.toString()).set({
                title: payload.notification.title,
                body: payload.notification.body,
                date: currentTime,
                target: topic,
                status: "Notificarea nu a fost trimisă!"
            }).then(() => {
                console.log('Create new notification');
            });
            console.log('Error sending message:', error);
        });
}
module.exports = router;

1). "Now" notification

Notification body:

{
    body: "test",
    date: undefined,
    status: "Notificarea nu a fost trimisă!",
    target: "A",
    title: "test",
}

These are the result and the logs:

express deprecated res.send(status): Use res.sendStatus(status) instead routes/notifications.js:41:9
Successfully sent message: { messageId: 9203836031271870000 }
Create new notification

The notification reaches the Android app and everything works normal as expected.

2). "Scheduled notification"

Notification body:

{
    body: "test",
    date: undefined,
    sendDate: "29/06/2019",
    sendHour: "07:27",
    status: "Notificarea nu a fost programată!",
    target: "A",
    title: "test",
}

These are the result and the logs:

2019-06-29T04:27:00.000Z
2019-06-29T04:25:35.070Z
{ topic: '/topics/topicA',
  payload: { notification: { title: 'test', body: 'test' } },
  options: { priority: 'high', timeToLive: 86400 } }
Successfully sent message: { messageId: 5284791767401410000 }
Create new notification 

Now there is something wrong with the behaviour. The notification won't reach the Android app until I restart the server. As you can see it is programmed to be sent at 2019-06-29T04:27:00.000Z, but nothing was sent even after a longer period. When I restart the server the Android app will receive the last sent notification.

So my problems are in the second scenario:

  • notifications are not sent after the delay;
  • the notifications seem not to be stored in a queue so only the last one will be sent after I restart the server;
  • after I restart the server the previously scheduled notifications seem to be sent on and on. Eg: first notification is sent, restart, second is sent, restart, first is sent, etc.

What am I missing?



from Node.js - FCM send scheduled topic notification