Tuesday 30 April 2019

How to Avoid throwing 400 errors from ExpressJS

Background: I am getting 400 errors (and a blank 400 page response) from a malformed cookie on my site (coming from one of my affiliate pages). I have wrote a code to delete the cookie, but some of my customers still get an error because it's in their cache. Once they clear their cache the problem is fixed.

This issue is circumvented all together in my .NET code base by simply ignoring a 400 error, I would like to do the same in Express JS.

Ask: I would like to have express ignore all cookies on a 400 error (often caused by defective cookies) or to at least ignore the error all together. Is there any way to do this?

My ClearDefectiveCookies function for reference

const clearDefectiveCookies = (req, res, next) => {
  const cookies = req.cookies;
  const defectiveCookies = Object.keys(cookies).filter(key => typeof cookies[key] === 'string' && (cookies[key].charAt(0) === '='));

  if (defectiveCookies.length > 0) {
    defectiveCookies.forEach(defectiveCookie => {
      res.clearCookie(defectiveCookie);
    });
  }

  next();
};

Problematic Cookie for Reference

Name: xyz_123 and value: =NaN=xyz=123



from How to Avoid throwing 400 errors from ExpressJS

Alexa ask a question and get response from external API

I have set up a simple intent

{
    "interactionModel": {
        "languageModel": {
            "invocationName": "viva bank",
            "intents": [
                ...builtin intents...
                {
                     "name": "ask",
                     "slots": [
                        {
                            "name": "question",
                            "type": "AMAZON.SearchQuery"
                        }
                    ],
                    "samples": [
                        "when {question}",
                        "how to {question}",
                        "what {question}"
                    ]
                }
            ],
            "types": []
        }
    }
}

But when I ask a question it gives me a generic error response like this:

Me: alexa ask viva bank when is the late fee charged

Alexa: Sorry, I don't know that.

Here is my lambda code, but I don't think it is getting that far.

'use strict';

const Alexa = require('ask-sdk-core');
var https = require('https');
var querystring = require('querystring');


const APP_ID = 'amzn1.ask.skill.1234'; 

const AskIntentHandler = {
  canHandle(handlerInput) {
    return !!handlerInput.requestEnvelope.request.intent.slots['question'].value;
  },
  handle(handlerInput) {
    var question = handlerInput.requestEnvelope.request.intent.slots['question'].value;
    console.log('mydata:', question);
    var responseString = '';
    const subscription_key = 'XXXX';

    var data = {
        simplequery: question,
        channel: 'Alexa'
    };
    var get_options = {
        headers: {'Subscription-Key': subscription_key }
    };

    https.get('https://fakeapi.com/' + querystring.stringify(data), get_options, (res) => {
      console.log('statusCode:', res.statusCode);
      console.log('headers:', res.headers);

      res.on('data', (d) => {
        responseString += d;
      });

      res.on('end', function(res) {
        var json_hash = JSON.parse(responseString);
        // grab the first answer returned as text and have Alexa read it
        const speechOutput = json_hash['results'][0]['content']['text'];
        console.log('==> Answering: ', speechOutput);
        // speak the output
        return handlerInput.responseBuilder.speak(speechOutput).getResponse();
      });
    }).on('error', (e) => {
      console.error(e);
      return handlerInput.responseBuilder.speak("I'm sorry I ran into an error").getResponse();
    });
  }

};

exports.handler = (event, context) => {
  const alexa = Alexa.handler(event, context);
  alexa.APP_ID = APP_ID;
  alexa.registerHandlers(AskIntentHandler);
  alexa.execute();
};

I'm really just looking to create a very simple pass through, where a question is asked to Alexa, and then I pipe that to an external API and have Alexa read the response.



from Alexa ask a question and get response from external API

Change text size on the positveButtonText in the EditTextPreference dialog

I cannot figure out how to change the text size on the buttons in the EditTextPreference dialog popup box. I would like all my text throughout my app to be streamlined at 24 sp. This is happening everywhere except this dialog box from the PreferenceScreen. As you can see in the ListPreference I figured out how to hide the positiveButtonText and negativeButtonText.

I would like to do this in the xml, if possible. I also would like to avoid having to create a custom dialog layout. In the EditTextPreference tag I can edit the title and layout in the dialog, I just can't figure out how to "touch" the default buttons.

Here is my pref_connection.xml:

<PreferenceScreen 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:title="Connection">

    <ListPreference
        android:defaultValue="box1"
        android:entries="@array/pref_box_type_list_titles"
        android:entryValues="@array/pref_box_type_list_values"
        android:key="box_types_list"
        android:negativeButtonText="@null"
        android:positiveButtonText="@null"
        android:layout="@layout/preference_screen_layout"
        android:title="@string/pref_title_box_type"/>

    <EditTextPreference
        android:defaultValue="@string/pref_default_internet_addr"
        android:digits="0123456789."
        android:inputType="number|numberDecimal"
        android:key="internet_addr"
        android:selectAllOnFocus="true"                  
        android:singleLine="true"
        android:layout="@layout/preference_screen_layout"
        android:textSize="@dimen/text_size"
        android:title="@string/pref_title_internet_addr"/>
    <...>
</PreferenceScreen>

Here is the layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView android:id="@android:id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/large_margin"
        android:paddingBottom="@dimen/margin"
        android:textSize="@dimen/text_size"/>

    <TextView android:id="@android:id/summary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/large_margin"
        android:textSize="@dimen/text_size"/>

</LinearLayout>

Would like to do something simple like styles:

<style name="AlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:textSize">24sp</item>
</style>

or utilize dialogLayout inside the EditTextPreference:

android:dialogLayout="@layout/dialogLayout"

But can't seem to get any of those working.

Hopefully screenshots of my app will help with understanding what I'm trying to accomplish.

This shows my Preference screen on the left side. This shows my Preference screen on the left side.

This shows the dialog box that pops up after the EditTextPreference is clicked. The text size on the cancel and ok buttons are what I'm trying to change. See red arrows. The other text in this dialog are controlled by the attributes in the EditTextPreference. This shows the dialog box that pops up after the EditTextPreference is clicked. The text size on the cancel and ok buttons are what I'm trying to change. See red arrows.

Any help would be greatly appreciated.



from Change text size on the positveButtonText in the EditTextPreference dialog

How to use redux-promise-middleware with react-scripts v3

I recently updated my react-scripts to version 3.0.0 in my React application and all of my actions stopped working.

I am using redux-promise-middleware so I have always this pattern when fetching data:

export const FIRST_ACTION = 'FIRST_ACTION';
export const FIRST_ACTION_PENDING = 'FIRST_ACTION_PENDING';
export const FIRST_ACTION_REJECTED = 'FIRST_ACTION_REJECTED';
export const FIRST_ACTION_FULFILLED = 'FIRST_ACTION_FULFILLED';

store.js:

import promiseMiddleware from 'redux-promise-middleware';

export default function configureStore() {
    return createStore(
        rootReducer,
        applyMiddleware(thunk, promiseMiddleware(), logger)
    );
}

I am usually performing several requests in a chain in my actions like this:

import { 
    firstAction,
    secondAction
} from '../service';

const chainedAction = (...) => {
    return (dispatch) => {
        return dispatch({
            type: FIRST_ACTION,
            payload: firstAction(...)
        }).then(() => dispatch({
            type: SECOND_ACTION,
            payload: secondAction(...)
        }));
    };
};

After the update, I am getting the following errors:

React Hook "firstAction" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function  react-hooks/rules-of-hooks

Does anybody know how to migrate my actions so they will be compliant with the latest dependencies?

EDIT: I am importing this action in my react component and calling it from there:

import { 
    chainedAction
} from '../actions';
...
<Button onClick={(...) => chainedAction(...)}
...
const mapDispatchToProps = dispatch => (
    bindActionCreators({ 
        chainedAction
    }, dispatch)
);

export default connect(mapStateToProps, mapDispatchToProps)(MyPage);

firstAction (second action is similar):

export const firstAction = (...) => {
    return new Promise((resolve, reject) => {
        fetch(API_URL, {
            method: 'POST',
            body: ...
        }).then(response => {
            if (response.ok) {
                resolve(response.text());
            }

            reject('...');
        }).catch(error => {
            return reject(error.message);
        });
    });
};



from How to use redux-promise-middleware with react-scripts v3

Error Domain=CBATTErrorDomain Code=2 "Reading is not permitted." UserInfo={NSLocalizedDescription=Reading is not permitted.}

I am developing app which manage BLE device. I am trying to write data in didDiscoverCharacteristicsFor method like below.

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        if let characteristics = service.characteristics {
                    for characteristic in characteristics {
                        if characteristic.uuid == CBUUID(string: Common.PinUUID) {
            var varInt = 0
            let data = Data.init(bytes: &varInt, count: 1);
            peripheral.writeValue(data, for: characteristic, type: .withResponse)
                        }
        }
    }

When I try to write data on characteristic then I got error like below.

<CBCharacteristic: 0x283b213e0, UUID = 47E9EE30-47E9-11E4-8939-164230D1DF67, properties = 0x8, value = (null), notifying = NO> - Optional("Writing is not permitted.")

My characteristic is Write only type. I don't know why it shows error like this.

Also when I try to read data then I call like below.

  if characteristic.uuid == CBUUID(string: Common.TemperatureDataUUID) {
            print(characteristic)
            peripheral.readValue(for: characteristic)
   }

I got error like below,

<CBCharacteristic: 0x283e77300, UUID = 47E9EE2B-47E9-11E4-8939-164230D1DF67, properties = 0xA, value = (null), notifying = NO> - Optional("Reading is not permitted.")

How to solve it not finding any solution? Please help.



from Error Domain=CBATTErrorDomain Code=2 "Reading is not permitted." UserInfo={NSLocalizedDescription=Reading is not permitted.}

Add Xcode Developer Account from the Command Line

I am trying to use xcodebuild -allowProvisioningUpdates on a machine that I only have access via the command line (Azure Devops macOS Hosted Machine).

Unfortunately, according to man xcodebuild in order to use -allowProvisioningUpdates it seems that "Requires a developer account to have been added in Xcode's Accounts preference pane."

Giving this, is there a way do add the account via the command line?

Thank you, Cosmin



from Add Xcode Developer Account from the Command Line

Emacs and conda workaround

I'm using emacs and anaconda.

I have this in my init.el:

(setenv "WORKON_HOME" "/home/user/anaconda3/envs/")

And conda on my path:

# added by Anaconda3 installer
export PATH="/home/user/anaconda3/bin:$PATH"

but emacs can't find my conda environments, which I understand it is supposed to be able to do..

So, when I run C-c C-p to start a new session, and C-c C-c, it fails to import my packages which are installed in a conda environment, with ModuleNotFoundError.

Since I have added this to my path and it still doesn't work, I am trying to work around this, and still be able to run my conda applications from emacs.

I can open a shell in emacs with M-x shell, then source activate myenv, and run python.

I now want C-c C-c to copy into /this/ shell. How do I mark this shell buffer as a python process to send my file.py's text to on C-c C-c, rather than just a shell shell?

Update1

I've also looked at the following references:

But neither package works for me. I still get, when I try:

conda-env-list

*Conda envs*

Produces a blank buffer.

And this for pyvenv-workon:

pyvenv-workon
  Work on:  (empty)

These environments very much exist, and it makes it impossible to use emacs as a python IDE if I can't run my code.



from Emacs and conda workaround

Appended new row is not behaving like previous one (row)

I have a HTML table in side which i have several td as input field,my table is dynamic, when page loads i am appending the 1st row of my table and focus on first input field, in my case i.e Item Name

I have 3 input fields in my row which are Item Name,Unit Qty and Disc%

  • When user clicks inside ItemName input field i am searching for itemnames from a data which is objects inside a array to populate itemnames
  • After selecting Item NAme i am moving my focus to next input field which is Unit Qty then after that focus in to next input field which is Disc% in between this some calculation are happening to calculate Total Amount
  • Then after this when user is focus out from Disc% i am appending a new row, actually i have a function inside which i have code to append the row, so i am calling that function on focus out of Disc%
  • After focus out of Disc% i want my focus should go to the ItemName of new row and should behave like it was behaving (Like search from data) and so on

I have commented the lines in my code to better user understanding what is happening where

function rowappend() // this one is appending row
{
  var markup = '<tr><td><input type="text" class="form-control commantd"name="itemNametd" id="itemNametd">' +
    '</td><td id="itemCodetd" class="commantd"></td>' +
    '<td><input type="text" class="form-control commantd"name="unitQtytd" id="unitQtytd"></td>' +
    '<td id="purRatetd" class="commantd"></td>' +
    '<td><input type="text" class="form-control commantd"name="discPercentagetd" id="discPercentagetd"></td>' +
    '<td id="discAmttd" class="commantd"></td>' +
    '<td id="gstPercentagetd" class="commantd"></td>' +
    '<td id="gstAmttd" class="commantd"></td>' +
    '<td id="totalAmttd" class="commantd"></td></tr>'
  $("table tbody").append(markup);
  $("itemNametd").next().focus();
}
rowappend()


var data = [ //data to populate Item Name search input field
  {
    "ItemName": "Butter"
  },
  {
    "ItemName": "Rice"
  },
  {
    "ItemName": "Milk"
  },
  {
    "ItemName": "Ice Cream"
  },
  {
    "ItemName": "Curd"
  }
]
var data1 = [{ // this data will be dynamic but for now to test i am using this single data
  "ItemName": "Butter",
  "ItemCode": 400564,
  "PurRate": 8,
  "DiscAmt": 6,
  "gstPercentage": 35,
  "gstAmt": 5
}]
var totalAmount = "";
var unitQuantity = "";
$(function() {
  let itemName = data.map(value => { //using autocomplete to for searching input field

    return value.ItemName;
  });
  $("#itemNametd").autocomplete({
    source: itemName
  });
});
$("#itemNametd").focusout(function() { //when user focus out from Item Name doing this

  data1.map(value => {
    $("#itemCodetd").text(value.ItemCode);
    $("#purRatetd").text(value.PurRate);
    $("#discAmttd").text(value.DiscAmt);
    $("#gstPercentahgetd").text(value.gstPercentage);
    $("#gstAmttd").text(value.gstAmt);

  });

});
$("#unitQtytd").focusout(function() { //when user focus out Unit Qty doing some calculation
  unitQuantity = $("#unitQtytd").val();
  purchaseRate = $("#purRatetd").text();
  totalAmount = (parseInt(unitQuantity) * parseInt(purchaseRate));
  $("#totalAmttd").text(totalAmount);

});
$("#discPercentagetd").focusout(function() { //here when user is focus out i am calling the fuinction which is creating new row

  rowappend()



});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<div class="container commonDivInvoice">
  <div class="row tableInvoice" id="commonDvScroll">
    <table class="table table-bordered" id="tableInvoice">
      <thead>
        <tr>
          <th id="itemNameth" class="commanth">Item Name</th>
          <th id="itemCodeth" class="commanth">Item Code</th>
          <th id="unitQtyth" class="commanth">Unit Qty</th>
          <th id="purRateth" class="commanth">Pur.Rate</th>
          <th id="discPercentageth" class="commanth">Disc%</th>
          <th id="discAmtth" class="commanth">Disc Amt</th>
          <th id="gstPercentageth" class="commanth">Gst%</th>
          <th id="gstAmtth" class="commanth">Gst Amt</th>
          <th id="totalAmtth" class="commanth">Total Amount</th>


        </tr>
      </thead>
      <tbody>


      </tbody>

    </table>

  </div>
</div>

From my side i think i am using wrong approach to do this task

NOTE :- in future on each focus out i may be doing some calculations so please help me out in that way

I have provided all the information if it is not sufficient then you all can ask me in comments

EDIT

as per Wils's answer after focus out from Disc% new row is appending and focus is also shifting to new row's Item Name but issue is when new row is appending the autocomplete is not working in first row initially when page loads when i type m inside the input field of Item Name all the item name containing m are displayed as drop-down but for 2nd row its not showing up

function rowappend() // this one is appending row
{
  var markup = $('<tr><td><input type="text" class="form-control commantd"name="itemNametd" id="itemNametd">' +
    '</td><td id="itemCodetd" class="commantd"></td>' +
    '<td><input type="text" class="form-control commantd"name="unitQtytd" id="unitQtytd"></td>' +
    '<td id="purRatetd" class="commantd"></td>' +
    '<td><input type="text" class="form-control commantd"name="discPercentagetd" id="discPercentagetd"></td>' +
    '<td id="discAmttd" class="commantd"></td>' +
    '<td id="gstPercentagetd" class="commantd"></td>' +
    '<td id="gstAmttd" class="commantd"></td>' +
    '<td id="totalAmttd" class="commantd"></td></tr>');

  $("table tbody").append(markup);
  $("#itemNametd", markup).focus();
}
rowappend()


var data = [ //data to populate Item Name search input field
  {
    "ItemName": "Butter"
  },
  {
    "ItemName": "Rice"
  },
  {
    "ItemName": "Milk"
  },
  {
    "ItemName": "Ice Cream"
  },
  {
    "ItemName": "Curd"
  }
]
var data1 = [{ // this data will be dynamic but for now to test i am using this single data
  "ItemName": "Butter",
  "ItemCode": 400564,
  "PurRate": 8,
  "DiscAmt": 6,
  "gstPercentage": 35,
  "gstAmt": 5
}]
var totalAmount = "";
var unitQuantity = "";
$(function() {
  let itemName = data.map(value => { //using autocomplete to for searching input field

    return value.ItemName;
  });
  $("#itemNametd").autocomplete({
    source: itemName
  });
});
$("#itemNametd").focusout(function() { //when user focus out from Item Name doing this

  data1.map(value => {
    $("#itemCodetd").text(value.ItemCode);
    $("#purRatetd").text(value.PurRate);
    $("#discAmttd").text(value.DiscAmt);
    $("#gstPercentahgetd").text(value.gstPercentage);
    $("#gstAmttd").text(value.gstAmt);

  });

});
$("#unitQtytd").focusout(function() { //when user focus out Unit Qty doing some calculation
  unitQuantity = $("#unitQtytd").val();
  purchaseRate = $("#purRatetd").text();
  totalAmount = (parseInt(unitQuantity) * parseInt(purchaseRate));
  $("#totalAmttd").text(totalAmount);

});

$('body').on('focusout', '#discPercentagetd', function() {
  rowappend()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<div class="container commonDivInvoice">
  <div class="row tableInvoice" id="commonDvScroll">
    <table class="table table-bordered" id="tableInvoice">
      <thead>
        <tr>
          <th id="itemNameth" class="commanth">Item Name</th>
          <th id="itemCodeth" class="commanth">Item Code</th>
          <th id="unitQtyth" class="commanth">Unit Qty</th>
          <th id="purRateth" class="commanth">Pur.Rate</th>
          <th id="discPercentageth" class="commanth">Disc%</th>
          <th id="discAmtth" class="commanth">Disc Amt</th>
          <th id="gstPercentageth" class="commanth">Gst%</th>
          <th id="gstAmtth" class="commanth">Gst Amt</th>
          <th id="totalAmtth" class="commanth">Total Amount</th>


        </tr>
      </thead>
      <tbody>


      </tbody>

    </table>

  </div>
</div>

Anyone out here please help me out



from Appended new row is not behaving like previous one (row)

Python Design Pattern: using class attributes to store data vs. local function variables

Often I find myself running into the same question. A common pattern is that I create a class that performs some operations. Eg. Loads data, transforms/cleans data, saves data. The question then arises how to pass/save intermediate data. Look at the following 2 options:

import read_csv_as_string, store_data_to_database

class DataManipulator:
    ''' Intermediate data states are saved in self.results'''

    def __init__(self):
        self.results = None

    def load_data(self):
        '''do stuff to load data, set self.results'''
        self.results = read_csv_as_string('some_file.csv')

    def transform(self):
        ''' transforms data, eg get first 10 chars'''
        transformed = self.results[:10]
        self.results = transformed

    def save_data(self):
        ''' stores string to database'''
        store_data_to_database(self.results)

    def run(self):
        self.load_data()
        self.transform()
        self.save_data()

DataManipulator().run()

class DataManipulator2:
    ''' Intermediate data states are not saved but passed along'''


    def load_data(self):
        ''' do stuff to load data, return results'''
        return read_csv_as_string('some_file.csv')

    def transform(self, results):
        ''' transforms data, eg get first 10 chars'''
        return results[:10]

    def save_data(self, data):
        ''' stores string to database'''
        store_data_to_database(data)

    def run(self):
        results = self.load_data()
        trasformed_results = self.transform(results)
        self.save_data(trasformed_results)

DataManipulator2().run()

Now for writing tests, I find DataManipulator2 better since functions can be tested more easily in isolation. At the same time I also like the clean run function of DataManipulator. What is the most pythonic way?



from Python Design Pattern: using class attributes to store data vs. local function variables

FindBugs IDEA - ClassNotFoundException com.google.wireless.android.sdk.stats.IntellijIndexingStats

FindBugs IDEA v1.0.1 Android Studio 3.4

I get this error when running FindBugs. I don't use com.google.wireless.android.sdk anywhere in the app.

Error:Internal error: (java.lang.ClassNotFoundException) com.google.wireless.android.sdk.stats.IntellijIndexingStats$Index
java.lang.ClassNotFoundException: com.google.wireless.android.sdk.stats.IntellijIndexingStats$Index
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at com.intellij.util.indexing.counters.IndexCounters.<clinit>(IndexCounters.java:34)
    at com.intellij.util.indexing.impl.MapReduceIndex.<init>(MapReduceIndex.java:86)
    at org.jetbrains.jps.backwardRefs.index.CompilerReferenceIndex$CompilerMapReduceIndex.<init>(CompilerReferenceIndex.java:214)
    at org.jetbrains.jps.backwardRefs.index.CompilerReferenceIndex.<init>(CompilerReferenceIndex.java:73)
    at org.jetbrains.jps.backwardRefs.JavaCompilerBackwardReferenceIndex.<init>(JavaCompilerBackwardReferenceIndex.java:12)
    at org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter.initialize(JavaBackwardReferenceIndexWriter.java:74)
    at org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexBuilder.buildStarted(JavaBackwardReferenceIndexBuilder.java:40)
    at org.jetbrains.jps.incremental.IncProjectBuilder.runBuild(IncProjectBuilder.java:358)
    at org.jetbrains.jps.incremental.IncProjectBuilder.build(IncProjectBuilder.java:178)
    at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:138)
    at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:302)
    at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:135)
    at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler.lambda$channelRead0$0(BuildMain.java:229)
    at org.jetbrains.jps.service.impl.SharedThreadPoolImpl.lambda$executeOnPooledThread$0(SharedThreadPoolImpl.java:42)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)



from FindBugs IDEA - ClassNotFoundException com.google.wireless.android.sdk.stats.IntellijIndexingStats

TestFlight: Couldn't install on Apple Watch

I can install the watch app on my iPhone using Xcode fine. But, I get the following error when I (or my beta testers) try to install the watch app using TestFlight.

enter image description here

I found this message on the console. The provisioning profiles are handled by Xcode automatically. Previous build of this app had no problem with the Watch app installation via TestFlight, but now even previous builds in TestFlight refuse to install the watch app. enter image description here



from TestFlight: Couldn't install on Apple Watch

What are the keycodes `getwch` returns?

I'm using msvcrt.getwch to make an interactive prompt in Python targeting Windows.

The documentation says:

Read a keypress and return the resulting character as a byte string. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return '\000' or '\xe0'; the next call will return the keycode. The Control-C keypress cannot be read with this function.

I have found F10 to use the former - \x00D, and F11 to use the latter \xe0\x85.

However this doesn't say what the keycodes are. This is important as I don't have a \xe0 key (à), among other keys, and so can't test the output of entering this value.


Additional side context

For example, I've tried pasting this key into the prompt in two ways.

  • CTRL-v - Which enters the keycode \x16. Which is the synchronous idle key in ASCII. [1] (Which is the key combination I entered.)
  • Right clicking (Paste in PS) - Results in just \xe0 being entered.

    I'm unsure if Power Shell and Visual C++ are kindly letting me paste escape sequences, or this is the actual handling of that key.


Given that msvcrt seems to be a wrapper around Visual C++ , I also looked at that documentation too.

The _getch and _getwch functions read a single character from the console without echoing the character. None of these functions can be used to read CTRL+C. When reading a function key or an arrow key, each function must be called twice; the first call returns 0 or 0xE0, and the second call returns the actual key code.

This also doesn't say what the keycodes are.

I've looked online but I can only find information about virtual keycodes, however this says F10 is \x79, and F11 is \x7A. As this function isn't returning these values, I know it's not referring to these keycodes.



from What are the keycodes `getwch` returns?

Problems using PackageLoader to load the wrench class

I am trying to load the Wrench library using PackageLoader and I can't get it to work. My code is below.

include __DIR__.'/PackageLoader.php';
$loader = new PackageLoader\PackageLoader();
$loader->load(__DIR__."/vendor/wrench/wrench");

$app = new class implements \Wrench\Application\DataHandlerInterface
{
    public function onData(string $data, \Wrench\Connection $connection): void
    {
        $connection->send($data);
    }
};

I get this error

Fatal error: Interface 'Wrench\Application\DataHandlerInterface' not found in C:\Users\desbest\Documents\UniServerZ\www\sugarchat\includes\actions.php on line 13

It finds the composer.json file though when I load the library.

How do I fix this?



from Problems using PackageLoader to load the wrench class

drag and drop with interact.js

I am trying to build an interface that allows both resize/drag and rotate on some element and to acheive this I am using interact.js javascript library.

I have my interact functions working:

    interact('.resize-drag-ratio')
      .draggable({
        onmove: window.dragMoveListener
      })
      .resizable({
        preserveAspectRatio: true,
        edges: { left: true, right: true, bottom: true, top: true }
      })
      .on('resizemove', function (event) {
        var target = event.target,
            x = (parseFloat(target.getAttribute('data-x')) || 0),
            y = (parseFloat(target.getAttribute('data-y')) || 0);

        var min_size = 35;

        if(event.rect.width>min_size){
            // update the element's style
            target.style.width  = event.rect.width + 'px';
            target.style.height = event.rect.height + 'px';


            // translate when resizing from top or left edges
            x += event.deltaRect.left;
            y += event.deltaRect.top;

            target.style.webkitTransform = target.style.transform =
                'translate(' + x + 'px,' + y + 'px)';

            target.setAttribute('data-x', x);
            target.setAttribute('data-y', y);

            }
      });

and drag-rotate that allows for rotation

    interact('.drag-rotate')
      .draggable({
      onstart: function (event) {
        const element = event.target;
        const rect = element.getBoundingClientRect();
        // store the center as the element has css `transform-origin: center center`
        element.dataset.centerX = rect.left + rect.width / 2;
        element.dataset.centerY = rect.top + rect.height / 2;

        console.log("element.dataset.centerX: "+element.dataset.centerX);
        console.log("element.dataset.centerY: "+element.dataset.centerY);



        // get the angle of the element when the drag starts
        element.dataset.angle = getDragAngle(event);
      },
      onmove: function (event) {
        var element = event.target;
        var center = {
          x: 300,
          y: 300,
        };


        console.log("element.dataset.centerX: "+element.dataset.centerX);
        console.log("element.dataset.centerY: "+element.dataset.centerY);


        var angle = getDragAngle(event);

        // update transform style on dragmove
      element.style.transform = 'rotate(' + angle + 'rad' + ')';
      },
      onend: function (event) {
        const element = event.target;

        // save the angle on dragend
        element.dataset.angle = getDragAngle(event);
      },
    })

The two classes get switched using jquery thus turning drag into rotaion and vice versa . My problem is that object location and rotation angle do not stay as placed and I am not sure how to fix that.

After i drag an element to some position and press the rotate button, one i start rotating the element it moves to top:0px left:0px and does not stay at its dragged position.

you can see the full working code right here: https://codepen.io/yaary-vidanpeled/pen/ZZwGmE



from drag and drop with interact.js

EXEC_BAD_ACCESS w/ OpenCV `cv::aruco::detectMarkers()` on IOS

  • opencv: 4.1.0 (w/ 'contrib' extensions)
  • swift: 5
  • IOS: 12.2

I am trying to run opencv's method cv::aruco::detectMarkers on every frame from an iphone camera. This works but after a minute or so it crashes with the error: Thread 8: EXC_BAD_ACCESS (code=1, address=0x10dea0000)

I've included what I think are the two most relevant pieces of the app, the UIViewController and the Objective-C wrapper and I've marked the two lines in each where the exception is thrown with a comment.

This doesn't appear to me to be a concurrency issue since this should be running synchronously on the main thread.

Here is the result of thread backtrace

* thread #8, queue = 'com.apple.root.default-qos', stop reason = EXC_BAD_ACCESS (code=1, address=0x10dea0000)
  * frame #0: 0x000000010505c700 Camera`cv::pointSetBoundingRect(cv::Mat const&) + 432
    frame #1: 0x000000010505c8c0 Camera`cvBoundingRect + 236
    frame #2: 0x0000000104fdf168 Camera`cvFindNextContour + 4348
    frame #3: 0x0000000104fe00fc Camera`cvFindContours_Impl(void*, CvMemStorage*, CvSeq**, int, int, int, CvPoint, int) + 1008
    frame #4: 0x0000000104fe118c Camera`cv::findContours(cv::_InputArray const&, cv::_OutputArray const&, cv::_OutputArray const&, int, int, cv::Point_<int>) + 972
    frame #5: 0x0000000104fe1bb0 Camera`cv::findContours(cv::_InputArray const&, cv::_OutputArray const&, int, int, cv::Point_<int>) + 96
    frame #6: 0x000000010507df68 Camera`cv::aruco::DetectInitialCandidatesParallel::operator()(cv::Range const&) const + 2056
    frame #7: 0x0000000104f8e068 Camera`(anonymous namespace)::ParallelLoopBodyWrapper::operator()(cv::Range const&) const + 248
    frame #8: 0x0000000104f8df5c Camera`(anonymous namespace)::block_function(void*, unsigned long) + 32
    frame #9: 0x0000000105318824 libdispatch.dylib`_dispatch_client_callout2 + 20

This is how I setup the AVCaptureVideoDataOutputSampleBufferDelegate, which receives every frame as a CMSampleBuffer, converts it to a UIImage and sends that UIImage to opencv for Aruco marker detection.

extension ViewController : AVCaptureVideoDataOutputSampleBufferDelegate {
    func captureOutput(
        _ output: AVCaptureOutput,
        didOutput sampleBuffer: CMSampleBuffer,
        from connection: AVCaptureConnection) {

        let image : UIImage = self.sample_buffer_to_uiimage(sampleBuffer: sampleBuffer)

        // call out to opencv wrapper, which eventually blows up
        let annotated_image : UIImage = OpenCVWrapper.drawMarkers(image)

        self.imageView.image = annotated_image

    }
    func sample_buffer_to_uiimage(sampleBuffer:CMSampleBuffer) -> UIImage
    {
        let imageBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
        let cimage : CIImage  = CIImage(cvPixelBuffer: imageBuffer)
        let context:CIContext = CIContext.init(options: nil)
        let cgImage:CGImage   = context.createCGImage(cimage, from: cimage.extent)!
        let image:UIImage     = UIImage.init(cgImage: cgImage)
        return image
    }
}

This is how I setup the objective-c opencv wrapper method

+(UIImage *) drawMarkers:(UIImage *)image {

    cv::Mat colorImageRGBA;
    cv::Mat colorImage;
    cv::Mat grayImage;

    UIImageToMat(image, colorImageRGBA);

    cvtColor(colorImageRGBA, grayImage, cv::COLOR_BGR2GRAY);
    cvtColor(colorImageRGBA, colorImage, cv::COLOR_RGBA2RGB);

    cv::Ptr<cv::aruco::Dictionary> dictionary = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_6X6_250);

    std::vector<int> markerIds;
    std::vector<std::vector<cv::Point2f>> markerCorners;

    // this is the line that blows up
    cv::aruco::detectMarkers(grayImage, dictionary, markerCorners, markerIds);

    if (markerIds.size() > 0) {
        cv::aruco::drawDetectedMarkers(colorImage, markerCorners, markerIds);
    }

    return MatToUIImage(colorImage);
}



from EXEC_BAD_ACCESS w/ OpenCV `cv::aruco::detectMarkers()` on IOS

Nodejs OPENSSH - Error: read ECONNRESET at TCP.onStreamRead

In one node.js script, I am using openssh to execute dos command from one windows server to another remote windows server. The remote server has openssh server running and i have tested it in ssh shell,

ssh username@hostname

But this does not work when I try from node.js. Here is the code which i am using ,

var SSH = require('simple-ssh');
var command = 'dir /b' //or dir 
ssh = new SSH({
            host: 'XXX.XXX.XX.XXX',
            user: 'username',
            pass: 'password'
        });

ssh.exec(command, {
    out: function(stdout) {
        console.log(stdout);
    }
}).start(); 

ssh.on('error', function(err) {
            console.log('In Start, something went wrong.');
            console.log(err);           
            ssh.end();
        });

Above script throws error,

In Start, something went wrong.
{ Error: read ECONNRESET
    at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
  errno: 'ECONNRESET',
  code: 'ECONNRESET',
  syscall: 'read',
  level: 'client-socket' }

please note, this gives output when i put "ls" as command , along with same error message. Ultimately I want to execute one bat file with some input parameters on remote windows server. I am not getting idea of this error and how to handle this.

Thanks



from Nodejs OPENSSH - Error: read ECONNRESET at TCP.onStreamRead

history.replaceState not working for firefox v56+

In my application, To Hide some information in URL i am using below code.

history.replaceState ({}, "", "bar.html");

It is working in all the browsers except firefox latest version (v56+)

In Firefox, if i press F5 then it is going back to previous URL which i have already replaced with above code.

Any help will be highly appreciated.



from history.replaceState not working for firefox v56+

df.style.apply centers multiindex values in display

When I run

import pandas as pd
from IPython.display import display
df = pd.DataFrame('a',index=pd.MultiIndex.from_product([[0,1]]*3),columns=['A'])
display(df)
display(df.style.apply(lambda x: ['']*len(x),axis=1))

in Jupyter, I get the following displays (unfortunately I cannot upload screenshots)

0 0 0 a
    1 a
  1 0 a
    1 a
1 0 0 a
    1 a
  1 0 a
    1 a

-

    0 a
  0  
    1 a
0
    0 a
  1  
    1 a
    0 a
  0  
    1 a
1
    0 a
  1  
    1 a

1: How do I prevent that change?

2: Since I actually don't dislike the second format completely: How can I fix the backgrounds in the multiindex, so that the boundaries of the groups in each multiindex level become visually clear?

(PS: In my actual code, the lambda returns 'background: green' for some rows)



from df.style.apply centers multiindex values in display

Front Facing Camera does not Auto Focus or Manually Focus

Current Behaviour

I'm using react-native-camera with iPads/iPhones and I use the front-facing camera to scan barcodes (Code39, Code128, QR, etc..) However when using the front-facing camera, it does not focus on the barcode or anything I put mildly close to the camera. The rear camera works absolutely perfectly however the front camera does not.

I have not been able to test android as I'm not building for android purely just iOS. I can't seem to find any information on getting the front camera to focus.

If I was to stand in the background, hold up my Code39 close to the camera but leave a small gap at the bottom, it would not try focus on the card however stay focused on me in the background.

I've also raised an issue here on their GitHub page, but came here to see if anyone has ran in to this before, has a work around etc.

Expected Behaviour

I expect the camera to see the code is taking up a lot more of the screen than I am, focus on it, read the code and proceed to run the code onBarCodeRead

What have I tried to fix it?

  • Disable the autoFocus as this was a fix for Android, no luck here.
  • Manually set the focusDepth.
  • Manually set autoFocusPointOfInterest to center of screen.
  • Change the zoom to 0.2 and slowly increase to the point of where it starts to look silly.
  • Set onGoogleVisionBarcodesDetected to just console.log something as this was another fix for android.
  • Update react-native-camera@2.6.0
  • Update to master branch at react-native-camera@git+https://git@github.com/react-native-community/react-native-camera.git

How can I recreate it?

  • Create new react-native project
  • yarn add react-native-camera / npm install react-native-camera --save
  • set type={RNCamera.Constants.Type.front} to use the front camera.
  • set autoFocus={RNCamera.Constants.AutoFocus.on} (It's on by default anyway, this just ensures it.
  • set onBarCodeRead={() => alert('barcode found')}
  • Try to scan a Code39 / Code128 - (creatable here)
  • Try to scan it and you'll find the camera will not focus on it however stay focused on the background. This is also true if you cover the camera with your finger, when you pull your finger away you expect the camera to be out of focus to the background and try and re-focus. This is not the case, it will stay focused at a medium / long distance.

Software Used & Versions

  • iOS: 12.1.4
  • react-native-camera: ^2.1.1 / 2.6.0
  • react-native: 0.57.7
  • react: 16.6.1

Code

I render the camera in a react-native-modal and I've put my code below.

<RNCamera 
  style={styles.camera}
  type={RNCamera.Constants.Type.front}
  flashMode={RNCamera.Constants.FlashMode.off}
  autoFocus={RNCamera.Constants.AutoFocus.on}
  captureAudio={false}
  onBarCodeRead={(barcode) => {
    if (this.state.isModalVisible) {
      this.setState({
        isModalVisible : false
      }, () => this.captureQR(barcode.data));
    }
}}>

Relevant Package Code

I found some code that seems relevant:

/react-native-camera/blob/master/ios/RN/RNCamera.m - L275-L300

- (void)updateFocusDepth
{
    AVCaptureDevice *device = [self.videoCaptureDeviceInput device];
    NSError *error = nil;

    if (device == nil || self.autoFocus < 0 || device.focusMode != RNCameraAutoFocusOff || device.position == RNCameraTypeFront) {
        return;
    }

    if (![device respondsToSelector:@selector(isLockingFocusWithCustomLensPositionSupported)] || ![device isLockingFocusWithCustomLensPositionSupported]) {
        RCTLogWarn(@"%s: Setting focusDepth isn't supported for this camera device", __func__);
        return;
    }

    if (![device lockForConfiguration:&error]) {
        if (error) {
            RCTLogError(@"%s: %@", __func__, error);
        }
        return;
    }

    __weak __typeof__(device) weakDevice = device;
    [device setFocusModeLockedWithLensPosition:self.focusDepth completionHandler:^(CMTime syncTime) {
        [weakDevice unlockForConfiguration];
    }];
}

More specifically just this section here:

If device.position == RNCameraTypeFront it will just return providing it doesn't meet any of the other criteria.

    if (device == nil || self.autoFocus < 0 || device.focusMode != RNCameraAutoFocusOff || device.position == RNCameraTypeFront) {
        return;
    }



from Front Facing Camera does not Auto Focus or Manually Focus

Optimise function for many pseudodata realisations in TensorFlow 2

My end goal is to simulate likelihood ratio test statistics, however the core problem I am having is that I do not understand how to get TensorFlow 2 to perform many optimisations for different data inputs. Here is my attempt, hopefully it gives you the idea of what I am trying:

import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_probability import distributions as tfd
import numpy as np

# Bunch of independent Poisson distributions that we want to combine
poises0 = [tfp.distributions.Poisson(rate = 10) for i in range(5)]

# Construct joint distributions
joint0 = tfd.JointDistributionSequential(poises0)

# Generate samples
N = int(1e3)
samples0 = joint0.sample(N)

# Now we need the same distributions but with floating parameters,
# and need to define the function to be minimised
mus = [tf.Variable(np.random.randn(), name='mu{0}'.format(i)) for i in range(5)]

#@tf.function
def loss():
    poises_free = [tfp.distributions.Poisson(rate = mus[i]) for i in range(5)]
    joint_free = tfd.JointDistributionSequential(poises_free)
    # Construct (half of) test statistic
    return -2*(joint_free.log_prob(samples0))

# Minimise (for all samples? Apparently not?)
opt = tf.optimizers.SGD(0.1).minimize(loss,var_list=mus)

print(mus)
print(loss())
print(opt)
quit()

Output:

[<tf.Variable 'mu0:0' shape=() dtype=float32, numpy=53387.016>, <tf.Variable 'mu1:0' shape=() dtype=float32, numpy=2540.568>, <tf.Variable 'mu2:0' shape=() dtype=float32, numpy=-5136.6226>, <tf.Variable 'mu3:0' shape=() dtype=float32, numpy=-3714.5227>, <tf.Variable 'mu4:0' shape=() dtype=float32, numpy=1062.9396>]
tf.Tensor(
[nan nan nan nan ... nan nan nan], shape=(1000,), dtype=float32)
<tf.Variable 'UnreadVariable' shape=() dtype=int64, numpy=1>

In the end I want to compute the test statistic

q = -2*joint0.log_prob(samples0) - loss()

and show that it has a chi-squared distribution with 5 degrees of freedom.

I am new to TensorFlow so perhaps I am doing this entirely wrong, but I hope you get the idea of what I want.

Edit:

So I played around a bit more, and I suppose that TensorFlow simply doesn't perform optimisations over the input tensors in parallel like I assumed. Or perhaps it can, but I need to set things up differently, i.e. perhaps give it a tensor of input parameters and a gigantic joint loss function for all the minimisations at once?

I also tried doing things with a simple loop just to see what happens. As predicted it is pathetically slow, but I also don't even get the right answer:

poises0 = [tfp.distributions.Poisson(rate = 10) for i in range(5)]
joint0 = tfd.JointDistributionSequential(poises0)

N = int(5e2)
samples0 = joint0.sample(N)

mus = [tf.Variable(10., name='mu{0}'.format(i)) for i in range(5)]

#@tf.function
def loss(xi):
    def loss_inner():
        poises_free = [tfp.distributions.Poisson(rate = mus[i]) for i in range(5)]
        joint_free = tfd.JointDistributionSequential(poises_free)
        # Construct (half of) test statistic
        return -2*(joint_free.log_prob(xi))
    return loss_inner

# Minimise
# I think I have to loop over the samples... bit lame. Can perhaps parallelise though.
q = []
for i in range(N):
   xi = [x[i] for x in samples0]
   opt = tf.optimizers.SGD(0.1).minimize(loss=loss(xi),var_list=mus)
   q += [-2*joint0.log_prob(xi) - loss(xi)()]

fig = plt.figure()
ax = fig.add_subplot(111)
sns.distplot(q, kde=False, ax=ax, norm_hist=True)
qx = np.linspace(np.min(q),np.max(q),1000)
qy = np.exp(tfd.Chi2(df=5).log_prob(qx))
sns.lineplot(qx,qy)
plt.show()

The output is not a chi-squared distribution with DOF=5. Indeed the test statistic often has negative values, which means that the optimised result is often a worse fit than the null hypothesis, which should be impossible.

Not a chi-squared distribution with DOF=5

Edit 2:

Here is an attempt at the "monster" solution where I minimise a giant network of different input variables for each pseudodata realisation all at once. This feels more like something that TensorFlow might be good at doing, though I feel like I will run out of RAM once I go to large sets of pseudodata. Still, I can probably loop over batches of pseudodata.

poises0 = [tfp.distributions.Poisson(rate = 10) for i in range(5)]
joint0 = tfd.JointDistributionSequential(poises0)

N = int(5e3)
samples0 = joint0.sample(N)

mus = [tf.Variable(10*np.ones(N, dtype='float32'), name='mu{0}'.format(i)) for i in range(5)]

poises_free = [tfp.distributions.Poisson(rate = mus[i]) for i in range(5)]
joint_free = tfd.JointDistributionSequential(poises_free)
qM = -2*(joint_free.log_prob(samples0))

@tf.function
def loss():
    return tf.math.reduce_sum(qM,axis=0)

# Minimise
opt = tf.optimizers.SGD(0.1).minimize(loss,var_list=mus)
print("parameters:", mus)
print("loss:", loss())
q0 =-2*joint0.log_prob(samples0)
print("q0:", q0)
print("qM:", qM)
q = q0 - qM

fig = plt.figure()
ax = fig.add_subplot(111)
sns.distplot(q, kde=False, ax=ax, norm_hist=True)
qx = np.linspace(np.min(q),np.max(q),1000)
qy = np.exp(tfd.Chi2(df=5).log_prob(qx))
sns.lineplot(qx,qy)
plt.show()

Unfortunately I now get the error:

Traceback (most recent call last):
  File "testing3.py", line 35, in <module>
    opt = tf.optimizers.SGD(0.1).minimize(loss,var_list=mus)   
  File "/home/farmer/anaconda3/envs/general/lib/python3.6/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py", line 298, in minimize
    return self.apply_gradients(grads_and_vars, name=name)
  File "/home/farmer/anaconda3/envs/general/lib/python3.6/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py", line 396, in apply_gradients
    grads_and_vars = _filter_grads(grads_and_vars)
  File "/home/farmer/anaconda3/envs/general/lib/python3.6/site-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py", line 924, in _filter_grads
    ([v.name for _, v in grads_and_vars],))
ValueError: No gradients provided for any variable: ['mu0:0', 'mu1:0', 'mu2:0', 'mu3:0', 'mu4:0'].

which I suppose is a basic sort of error. I think I just don't understand how TensorFlow keeps track of the derivatives it needs to compute. It seems like things work if I define variables inside the loss function rather than outside, but I need them outside in order to access their values later. So I guess I don't understand something here.



from Optimise function for many pseudodata realisations in TensorFlow 2

Applying Bostock's wrap function on text

I have a use case where I would like to append a small/medium blurb of text to different parts of my visual. As is the default behavior, this looks very unsightly as svg text is just appended in one fell swoop. So after a bit of research I found that Mike Bostock has created a clever way to handle longer strings in svg text, which can be seen here. I have tried to adapt this function to my particular visual but it didn't quite pan out. Here is the snippet:

  

 var margins = {top:20, left:50, bottom:100, right:20};

var width = 1200;
var height = 500;

var totalWidth = width+margins.left+margins.right;
var totalHeight = height+margins.top+margins.bottom;

var svg = d3.select('body')
    .append('svg')
    .attr('width', totalWidth)
    .attr('height', totalHeight);

var graphGroup = svg.append('g')
    .attr('transform', "translate("+margins.left+","+margins.top+")");

var rawData = [
  {'date':'Dec-02-2018', 'regulator':'CBIRC', 'penalty':false, 'summary':'Finalized bank wealth management subsidiary rules allow equity investments'},
  {'date':'Nov-28-2018', 'regulator':'CSRC', 'penalty':false, 'summary':"Brokerage's retail-targeted, pooled asset management products required to follow mutual fund standards"},
  {'date':'Dec-14-2018', 'regulator':'CSRC', 'penalty':false, 'summary':'Regulators issue window guidance to stop FMCs from promoting short-term performance of pension funds'},
  {'date':'Dec-19-2018', 'regulator':'CSRC', 'penalty':false, 'summary':'CSRC issues information technology magement rules'},
  {'date':'Dec-25-2018', 'regulator':'AMAC', 'penalty':false, 'summary':'AMAC issues guidelines on bond-trading'},
  {'date':'Jan-11-2019', 'regulator':'SZSE', 'penalty':false, 'summary':'SZSE revises trading rules for certain ETFs'},
  {'date':'Jan-18-2019', 'regulator':'CSRC', 'penalty':false, 'summary':'CSRC issues guidelines on mutual fund investment info credit derivatives, while AMAC issues affiliated valuation guidelines'},
  {'date':'Jan-26-2019', 'regulator':'CSRC', 'penalty':false, 'summary':'Yi Huiman appointed as CSRC party secretary and chairman'},
  {'date':'Jan-28-2019', 'regulator':'CSRC', 'penalty':false, 'summary':'CSRC publishes draft rules for the new technology innovation board, which will be paired with a registration-based IPO system'},
  {'date':'Jan-22-2019', 'regulator':'CSRC', 'penalty':true, 'summary':'Several third-party fund distribution institutions punished by CSRC for incompliant distribution and reporting'},
  {'date':'Jan-31-2019', 'regulator':'PBoC', 'penalty':true, 'summary':'ICBC Credit Suisse punished by PBoC for mishandling customer information'}
];

var parseDate = d3.timeParse("%b-%d-%Y");

var formatTime = d3.timeFormat("%b %d, %Y");

var data = rawData.map(function(d) {
    return  {date:parseDate(d.date), regulator:d.regulator, penalty:d.penalty, summary:d.summary}
});

data.sort(function(x, y){
   return d3.ascending(x.date, y.date);
});

//var earliest = d3.min(data.map(d=>d.date));
//var latest = d3.max(data.map(d=>d.date));

var dateMin = d3.min(data, function(d){
    return d3.timeDay.offset(d.date, -10);
});

var dateMax = d3.max(data, function(d){
    return d3.timeDay.offset(d.date, +10);
});

var timeScale = d3.scaleTime()
    .domain([dateMin, dateMax])
    .range([0, width]);

var colorMap = {
  'CSRC':'#003366',
  'CBIRC':'#e4a733',
  'AMAC':'#95b3d7',
  'SZSE':'#b29866',
  'PBoC':'#366092'
};

var defs = svg.append('svg:defs');
var fillURL = "Fills/gray-1-crosshatch.svg";


defs.append("svg:pattern")
    .attr("id", "gray_hatch")
    .attr("width", 10)
    .attr("height", 10)
    .attr("patternUnits", "userSpaceOnUse")
    .append("svg:image")
    .attr("xlink:href", fillURL)
    .attr("width", 10)
    .attr("height", 10)
    .attr("x", 0)
    .attr("y", 0);

graphGroup.append('rect')
    .attr('width', width)
    .attr('height', 80)
    .attr('x', 0)
    .attr('y', height*.75)
    .style('fill', "url(#gray_hatch)");

graphGroup.append('rect')
    .attr('width', width)
    .attr('height', 20)
    .attr('x', 0)
    .attr('y', height*.75+30)
    .style('fill', "#a6a6a6");

graphGroup.append('rect')
    .attr('width',8)
    .attr('height',80)
    .attr('x',0)
    .attr('y',height*.75)
    .style('fill', "#a6a6a6");

graphGroup.append('rect')
    .attr('width',8)
    .attr('height',80)
    .attr('x',width)
    .attr('y',height*.75)
    .style('fill', "#a6a6a6");

graphGroup.selectAll('circle')
    .data(data)
    .enter()
    .append('circle')
    .attr('cx', function(d) {return timeScale(d.date)})
    .attr('cy', height*.75+40)
    .attr('r', 10)
    .style('fill', function(d) {return colorMap[d.regulator]});
    
graphGroup.selectAll('line')
    .data(data.filter(function(d) {return d.penalty==false}))
    .enter()
    .append('line')
    .attr('x1', function(d) {return timeScale(d.date)})
    .attr('x2', function(d) {return timeScale(d.date)})
    .attr('y1', function(d) {return height*.75+40})
    .attr('y2', function(d,i) {
      if (i%2) {
        return 50;
      } else {
        return height/2;
      }
      })
    .style('stroke', function(d) {return colorMap[d.regulator]})
    .style('stroke-width', '2px');

graphGroup.selectAll('.labelRects')
    .data(data.filter(function(d) {return d.penalty==false}))
    .attr('class', 'labelRects')
    .enter()
    .append('rect')
    .attr('width', 125)
    .attr('height', 10)
    .attr('x', function(d) {return timeScale(d.date)-125})
    .attr('y', function(d,i) {
      if (i%2) {
        return 50;
      } else {
        return height/2;
      }
      })
    .style('fill', function(d) { return colorMap[d.regulator]});

graphGroup.selectAll('text')
    .data(data.filter(function(d) {return d.penalty==false}))
    .enter()
    .append('text')
    .attr('x', function(d) {return timeScale(d.date)-125})
    .attr('y', function(d,i) {
      if (i%2) {
        return 50-5;
      } else {
        return height/2-5;
      }
      })
    .text(function(d) {return formatTime(d.date)})
    //.attr('text-anchor','middle')
    .attr('class', 'date');


    function wrap(text, width) {

      text.each(function() {
        var text = d3.select(this),
            words = text.text().split(/\s+/).reverse(),
            word,
            line = [],
            lineNumber = 0,
            lineHeight = 1.1, // ems
            y = text.attr("y"),
            dy = parseFloat(text.attr("dy")),
            tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
        while (word = words.pop()) {
          line.push(word);
          tspan.text(line.join(" "));
          if (tspan.node().getComputedTextLength() > width) {
            line.pop();
            tspan.text(line.join(" "));
            line = [word];
            tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
          }
        }
      });
    }

graphGroup.selectAll('.labelText')
    .data(data.filter(function(d) {return d.penalty==false}))
    .attr('class', 'labelText')
    .enter()
    .append('text')
    .attr('x', function(d) {return timeScale(d.date)-125})
    .attr('y', function(d,i) {
      if (i%2) {
        return 50+20;
      } else {
        return height/2+20;
      }
      })
    .text(function(d) {return d.summary})
    .style('font-size','12px');

d3.selectAll('.labelText')
  .call(wrap, 120);
text {
  font-family: Tw Cen MT;

}

.date {
    font-size: 18px;
    paint-order: stroke;
    stroke: #fff;
    stroke-width: 3px;
    stroke-linecap: butt;
    stroke-linejoin: miter;
    font-weight: 800;
}
<script src="https://d3js.org/d3.v5.min.js"></script>

It makes conceptual sense to me, I did everything that Bostock did in the example (I think), however the text doesn't appear to be going through the function correctly and no wrapping takes place -- no errors either.

Question

Is it possible to adapt Bostock's tspan wrap function for the general case? If so, how do we do it if it's not selecting the text and calling the function and setting the desired width?

Further Clarifications:

  • My font size: 12px
  • My desired width: 120

Bonus Points:

  • Desired text align: right (Bostock's is centered text, it seems)


from Applying Bostock's wrap function on text

How to play audio in WKWebView?

I'm making an iOS app to wrap my javascript game and audio plays fine on mobile safari, but not when in my native app's webView. I want to play audio with javascript audio.play()

In the javascript on audio.play() I get NotSupportedError: The operation is not supported. myAudio.readyState is 0. canplaythrough never happens.

<html>
    <body>
        <div id=debug style='font-size:20px' onclick="playSound(myAudio)">
            Debug<br />
            Tap here to play the sound2.<br />
        </div>
        <script>
            var url = "http://curtastic.com/gold.wav"
            //var url = "upgrade.wav" // I have also tried local audio files within the project. Same error.
            var myAudio
            var context = new webkitAudioContext()
            var playSound = function(sound)
            {
                log("playSound() readyState="+sound.readyState)
                sound.play()
                //Someone said to try it this way. Same error.
                context.resume().then(() => {
                                      log("Context resumed")
                                      sound.play()
                                      })
            }

            var myAudio = new Audio(url)
            myAudio.addEventListener('canplaythrough', function(){log('canplaythrough')}, false)

            function log(m)
            {
                console.log(m)
                debug.innerHTML += m+"<br />"
            }
        </script>
    </body>
</html>

And ViewController.swift

import UIKit
import WebKit

class ViewController: UIViewController {
    private var myWebView3 : WKWebView!
    override func viewDidLoad() {
        super.viewDidLoad()

        self.myWebView3 = WKWebView(frame: .zero)

        self.myWebView3.configuration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
        self.myWebView3.configuration.mediaTypesRequiringUserActionForPlayback = []
        self.myWebView3.configuration.allowsInlineMediaPlayback = true

        let url = Bundle.main.url(forResource: "index6", withExtension: "html", subdirectory: "/")!
        self.myWebView3.loadFileURL(url, allowingReadAccessTo: url)
        let request = URLRequest(url: url)
        self.myWebView3.load(request)

        self.view.addSubview(self.myWebView3)
    }

    override func viewDidLayoutSubviews() {
        self.myWebView3.frame = self.view.bounds
    }

}

I'm using Xcode 10.1 iPhone SE 12.1.1 I have also tried on an iPad with iOS 10 and get the same error. I have also tried playing the sound inside ontouchstart and get the same error. I have also tried context.decodeAudioData() / context.createBufferSource() and get the same error.



from How to play audio in WKWebView?

Export 2 webpack config const

I'm trying to build a webpack file, the problem came when I needed to add the 'node' target because it was causing problems with an 'fs' function reading some files. Then I divided my config into web and node. But I'm not complitely sure if I'm doing it right.

I'm currently trying to separate those webpack config.

My webpack.config.js:

const VueLoaderPlugin = require('vue-loader/lib/plugin')

var path = require('path');

const webConfig = {
    entry: './src/main.js',
    mode: 'development',
    output: {
        path: path.resolve(__dirname, './dist/'),
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['.css','.jpg','.png'],
        alias: {
          'vue$': 'vue/dist/vue.esm.js',
          '@': path.resolve(__dirname, './src/'),
        }
    },
    module: {
        rules: [
            { test: /\.less$/, loader: "style-loader!css-loader!less-loader" },
            { test: /\.png/,   loader: "url-loader?limit=100000&mimetype=image/png" },
            { test: /\.gif/,   loader: "url-loader?limit=100000&mimetype=image/gif" },
            { test: /\.jpg/,   loader: "file-loader" },
            { test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' },
            { test: /\.css$/, use: ['vue-style-loader','css-loader']} 
        ]
  }
}
const nodeConfig = {
  entry: './src/main.js',
  mode: 'development',
  output: {
      path: path.resolve(__dirname, './dist/'),
      filename: 'bundle.node.js'
  },
  resolve: {
      extensions: ['.js', '.vue','.json'],
      alias: {
        'vue$': 'vue/dist/vue.esm.js',
        '@': path.resolve(__dirname, './src/'),
      }
  },
  target: 'node',
  node: { fs: 'empty' },
  module: {
      rules: [
          { test: /\.vue$/,  loader: 'vue-loader' },
          { test: /\.js$/,   loader: 'babel-loader' },
          { test: /\.css$/, use: ['vue-style-loader','css-loader']} 
          // this will apply to both plain `.css` files
          // AND `<style>` blocks in `.vue` files
      ]
},
plugins: [
  new VueLoaderPlugin()
]
}

But I have these errors. The first one is having problems with js files even if I'm not event taking them. What am I doing wrong here?

ERROR in ./node_modules/axios/index.js
    Module not found: Error: Can't resolve './lib/axios' in 'C:\Users\sdr\Documents\deficarte\node_modules\axios'
     @ ./node_modules/axios/index.js 1:17-39
     @ ./src/main.js

ERROR in ./node_modules/vue-style-loader/lib/addStylesClient.js
    Module not found: Error: Can't resolve './listToStyles' in 'C:\Users\sdr\Documents\deficarte\node_modules\vue-style-loader\lib'
     @ ./node_modules/vue-style-loader/lib/addStylesClient.js 7:0-41 57:15-27 69:15-27
     @ ./node_modules/bootstrap/dist/css/bootstrap.min.css




from Export 2 webpack config const

Multiple choice question skewing the total points tally

I've created a step by step test (fiddle example below) that doesn't quite tally up the total correctly. It works fine if all questions have one answer but when there's multiple answers for a single question it gives a strange tally.

(All answers to the questions are the first checkbox except for "Question 2", the multiple choice question, which is the first 2 checkboxes)

For the multiple choice question - the progress squares at the bottom change green when only one of the two answers is correct (when you click next), it should only be green when both are checked correctly, if not correct then it should be red.

The second issue is that if you answer all questions correctly then the final score is 7... when it should be 5 (multiple choice questions should add 1 point per answer). (If you inspect the fiddle, you can see the total being updated when the next button is clicked in the hidden field at the bottom)

Where am I going wrong?

http://jsfiddle.net/rob_teamworks/vebcsjw0/

jQuery(function($) {
$(document).ready(function() {

  // hide all form-rows, but not the first one
  $('.form-row').not(':first').hide();

  // hide on last step
  $('button.next').last().hide();

var score = 0;
  $('button.next, input.check').click(function(e) {
    // prevent the next buttons from submitting the form
    e.preventDefault();

                var item = $(this).parents('div.form-row').find('.correct:first').data('progress');
    if ($(this).parents('div.form-row').find('.correct:first').is(":checked") && $(this).parents('div.form-row').find('.correct:first').hasClass('correct-answer')) {
                        $('.quiz-progress-circle[data-progress="' + item + '"]').removeClass("progress-incorrect");
                        $('.quiz-progress-circle[data-progress="' + item + '"]').addClass("progress-correct");
                        score += Number(score+1);
                } else {
                        $('.quiz-progress-circle[data-progress="' + item + '"]').removeClass("progress-correct");
      $('.quiz-progress-circle[data-progress="' + item + '"]').addClass("progress-incorrect");
    }

    // hide this form-row, and show the next one
    $(this).parents('div.form-row').hide().next('div.form-row').show();
                $('.finalscore').val(score);
        });

        // add the submit button to the last form-row
  $('<input>').addClass('check').prop('type', 'submit').appendTo($('.form-row:last'));

});
});


jQuery(function($) {
$(document).ready(function () {
    $("input[type=checkbox].correct").click(function (e) {
        if ($(e.currentTarget).closest("div.question").length > 0) {
            toggleInputs($(e.currentTarget).closest("div.question")[0]);
        }
    });
});

function toggleInputs(questionElement) {
    if ($(questionElement).data('max-answers') == undefined) {
        return true;
    } else {
        maxAnswers = parseInt($(questionElement).data('max-answers'), 10);
        if ($(questionElement).find(".correct:checked").length >= maxAnswers) {
            $(questionElement).find(".correct:not(:checked)").attr("disabled", true);
        } else {
            $(questionElement).find("input[type=checkbox].correct").attr("disabled", false);
        }
    }
}
});
.quiz-progress-circle {
        height:5px;
        width:5px;
        background-color:grey;
        display:inline-block;
        margin-right:10px;
}

.progress-correct {
        background-color:green!important;
}

.progress-incorrect {
        background-color:red!important;
}

.progress-current {
        background-color:blue!important;        
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<section class="row test">
                                <div class="columns">
                                        <div class="entry">

                                                <form class="form" method="POST" action="http://example.com/test-insert.php">
                                                        
                                                        <input type="hidden" value="teamworks" name="test-user">
                                                        <input type="hidden" value="Introduction" name="test-name">

                                                                                                                <div class="form-row">
                                                                <h1>Quiz | Introduction</h1>

                                                                <div class="clear"></div>
                                                                <div id="module-area">
                                                                        <div id="modules-top"></div>
                                                                        <div id="modules-repeat">
                                                                                        <h2 class="training">1. Question 1</h2>

                                                                                        <div class="question" data-max-answers="1">
                                                                                                                                                                                                                                                                                                <div style="display:table-row;">
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <input class="correct correct-answer" data-progress="1" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 1">
                                                                                                                </div>
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <p>
                                                                                                                                Answer 1                                                                                                                        </p>
                                                                                                                </div>
                                                                                                        </div>
                                                                                                                                                                                                                                                                                                        <div style="display:table-row;">
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <input class="correct " data-progress="1" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 2">
                                                                                                                </div>
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <p>
                                                                                                                                Answer 2                                                                                                                        </p>
                                                                                                                </div>
                                                                                                        </div>
                                                                                                                                                                                                                                                                                                        <div style="display:table-row;">
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <input class="correct " data-progress="1" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 3">
                                                                                                                </div>
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <p>
                                                                                                                                Answer 3                                                                                                                        </p>
                                                                                                                </div>
                                                                                                        </div>
                                                                                                                                                                                        </div>
                                                                                        <div class="inner"></div>
                                                                                        <button class="next">Next &gt;&gt;</button>
                                                                                <div class="clear"></div>
                                                                        </div>
                                                                        <div id="modules-bottom"></div>
                                                                </div>
                                                        </div>
                                                                                                                <div class="form-row" style="display: none;">
                                                                <h1>Quiz | Introduction</h1>

                                                                <div class="clear"></div>
                                                                <div id="module-area">
                                                                        <div id="modules-top"></div>
                                                                        <div id="modules-repeat">
                                                                                        <h2 class="training">2. Question 2</h2>

                                                                                        <div class="question" data-max-answers="2">
                                                                                                                                                                                                                                                                                                <div style="display:table-row;">
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <input class="correct correct-answer" data-progress="2" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 1">
                                                                                                                </div>
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <p>
                                                                                                                                Answer 1                                                                                                                        </p>
                                                                                                                </div>
                                                                                                        </div>
                                                                                                                                                                                                                                                                                                        <div style="display:table-row;">
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <input class="correct correct-answer" data-progress="2" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 2">
                                                                                                                </div>
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <p>
                                                                                                                                Answer 2                                                                                                                        </p>
                                                                                                                </div>
                                                                                                        </div>
                                                                                                                                                                                                                                                                                                        <div style="display:table-row;">
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <input class="correct " data-progress="2" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 3">
                                                                                                                </div>
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <p>
                                                                                                                                Answer 3                                                                                                                        </p>
                                                                                                                </div>
                                                                                                        </div>
                                                                                                                                                                                        </div>
                                                                                        <div class="inner"></div>
                                                                                        <button class="next">Next &gt;&gt;</button>
                                                                                <div class="clear"></div>
                                                                        </div>
                                                                        <div id="modules-bottom"></div>
                                                                </div>
                                                        </div>
                                                                                                                <div class="form-row" style="display: none;">
                                                                <h1>Quiz | Introduction</h1>

                                                                <div class="clear"></div>
                                                                <div id="module-area">
                                                                        <div id="modules-top"></div>
                                                                        <div id="modules-repeat">
                                                                                        <h2 class="training">3. Question 4</h2>

                                                                                        <div class="question" data-max-answers="1">
                                                                                                                                                                                                                                                                                                <div style="display:table-row;">
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <input class="correct correct-answer" data-progress="3" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 1">
                                                                                                                </div>
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <p>
                                                                                                                                Answer 1                                                                                                                        </p>
                                                                                                                </div>
                                                                                                        </div>
                                                                                                                                                                                                                                                                                                        <div style="display:table-row;">
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <input class="correct " data-progress="3" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 2">
                                                                                                                </div>
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <p>
                                                                                                                                Answer 2                                                                                                                        </p>
                                                                                                                </div>
                                                                                                        </div>
                                                                                                                                                                                                                                                                                                        <div style="display:table-row;">
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <input class="correct " data-progress="3" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 3">
                                                                                                                </div>
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <p>
                                                                                                                                Answer 3                                                                                                                        </p>
                                                                                                                </div>
                                                                                                        </div>
                                                                                                                                                                                        </div>
                                                                                        <div class="inner"></div>
                                                                                        <button class="next">Next &gt;&gt;</button>
                                                                                <div class="clear"></div>
                                                                        </div>
                                                                        <div id="modules-bottom"></div>
                                                                </div>
                                                        </div>
                                                                                                                <div class="form-row" style="display: none;">
                                                                <h1>Quiz | Introduction</h1>

                                                                <div class="clear"></div>
                                                                <div id="module-area">
                                                                        <div id="modules-top"></div>
                                                                        <div id="modules-repeat">
                                                                                        <h2 class="training">4. Question 5</h2>

                                                                                        <div class="question" data-max-answers="1">
                                                                                                                                                                                                                                                                                                <div style="display:table-row;">
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <input class="correct correct-answer" data-progress="4" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 1">
                                                                                                                </div>
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <p>
                                                                                                                                Answer 1                                                                                                                        </p>
                                                                                                                </div>
                                                                                                        </div>
                                                                                                                                                                                                                                                                                                        <div style="display:table-row;">
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <input class="correct " data-progress="4" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 2">
                                                                                                                </div>
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <p>
                                                                                                                                Answer 2                                                                                                                        </p>
                                                                                                                </div>
                                                                                                        </div>
                                                                                                                                                                                                                                                                                                        <div style="display:table-row;">
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <input class="correct " data-progress="4" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 3">
                                                                                                                </div>
                                                                                                                <div style="display:table-cell;">
                                                                                                                        <p>
                                                                                                                                Answer 3                                                                                                                        </p>
                                                                                                                </div>
                                                                                                        </div>
                                                                                                                                                                                        </div>
                                                                                        <div class="inner"></div>
                                                                                        <button class="next" style="display: none;">Next &gt;&gt;</button>
                                                                                <div class="clear"></div>
                                                                        </div>
                                                                        <div id="modules-bottom"></div>
                                                                </div>
                                                        <input class="check" type="submit"></div>
                                                        


                                                        <div class="quiz-progress">
                                                                                                                                        <div class="quiz-progress-circle" data-progress="1"></div>
                                                                                                                                        <div class="quiz-progress-circle" data-progress="2"></div>
                                                                                                                                        <div class="quiz-progress-circle" data-progress="3"></div>
                                                                                                                                        <div class="quiz-progress-circle" data-progress="4"></div>
                                                                                                                        </div>


                                                        <input type="hidden" value="236" name="test-id">
                                                        <input class="finalscore" type="hidden" value="" name="test-score">
                                                        <input type="hidden" value="2" name="test-pass">

                                                </form>



                                                <div class="clear"></div>
                                </div>


                            </div>
                    </section>

This is the php file it calls on submit. The variable $score comes from the hidden field with the name test-score that is tallied up by the jquery variable score.

<?php
$score = $_POST["test-score"];


$pass_msg = $_POST["test-pass"];
if ($score >= $pass_msg) {
    $pass_txt = "Pass";
} else {
    $pass_txt = "Fail";
}

// Opens a connection to a MySQL server
$username="root";
$password="root";
$database="local";
$host="localhost";

$con = mysqli_connect($host, $username, $password);
if (!$con)
{
    die('Could not connect: ' . mysqli_error());
}
mysqli_select_db($con, "local");
$user = $_POST["test-user"];
$testid = $_POST["test-id"];
$sql = mysqli_query($con, "INSERT INTO test (`name`, `testname`, `score`, `pass-fail`) VALUES ('".$user."', '".$testid."', '".$score."', '".$pass_txt."')");
if (!$sql)
  {
  die('Error: ' . mysqli_error());
  }
mysqli_close($con);
header('Location: http://example.com/training/introduction/');
?>



from Multiple choice question skewing the total points tally