Q: PHP contact form issue (Method Not Allowed) PHP CODE
$name_error = $email_error =  "";
$name = $email = $message = $success = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $name_error = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $name_error = "Only letters and white space allowed";
    }
  }

  if (empty($_POST["email"])) {
    $email_error = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $email_error = "Invalid email format";
    }
  }

    if (empty($_POST["subject"])) {
    $subject_error = "Subject is required";
  } else {
    $subject = test_input($_POST["subject"]);
  }

  if (empty($_POST["message"])) {
    $message = "";
  } else {
    $message = test_input($_POST["message"]);
  }

  $to = "ayoub.kermout@gmail.com"
  $about = "GA:TC CONTACT RECIVED!!"
  $body = "Name: $name\nEmail: $email\nSubject: $subject\nMessage: $message"

  mail($to, $about, body, "From: $name <$email>")
  $success = "Message sent, thank you for contacting us!";
  $name = $email = $message = '';

}
}
?>

JAVASCRIPT CODE
(function($) {
  "use strict"; // Start of use strict

  // Smooth scrolling using jQuery easing
  $('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: (target.offset().top - 48)
        }, 1000, "easeInOutExpo");
        return false;
      }
    }
  });

  // Closes responsive menu when a scroll trigger link is clicked
  $('.js-scroll-trigger').click(function() {
    $('.navbar-collapse').collapse('hide');
  });

  // Activate scrollspy to add active class to navbar items on scroll
  $('body').scrollspy({
    target: '#mainNav',
    offset: 48
  });

  // Collapse the navbar when page is scrolled
  $(window).scroll(function() {
    if ($("#mainNav").offset().top > 100) {
      $("#mainNav").addClass("navbar-shrink");
    } else {
      $("#mainNav").removeClass("navbar-shrink");
    }
  });

  // Scroll reveal calls
  window.sr = ScrollReveal();
  sr.reveal('.sr-icons', {
    duration: 600,
    scale: 0.3,
    distance: '0px'
  }, 200);
  sr.reveal('.sr-button', {
    duration: 1000,
    delay: 200
  });
  sr.reveal('.sr-contact', {
    duration: 600,
    scale: 0.3,
    distance: '0px'
  }, 300);

  // Magnific popup calls
  $('.popup-gallery').magnificPopup({
    delegate: 'a',
    type: 'image',
    tLoading: 'Loading image #%curr%...',
    mainClass: 'mfp-img-mobile',
    gallery: {
      enabled: true,
      navigateByImgClick: true,
      preload: [0, 1]
    },
    image: {
      tError: 'The image #%curr% could not be loaded.'
    }
  });

})(jQuery);

HTML CODE

CONTACT FORM

Fill the form table down below to contact us.

Contact

          <form id="contact-form" class="form" action="mail/contact.php" method="post" role="form">

                  Your Name
                  <input type="text" class="form-control" id="name" name="name" placeholder="Your name" tabindex="1" required>

                  Your Email
                  <input type="email" class="form-control" id="email" name="email" placeholder="Your Email" tabindex="2" required>

                  Subject
                  <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" tabindex="3">

                  Message
                  <textarea rows="5" cols="50" name="message" class="form-control" id="message" placeholder="Message..." tabindex="4" required></textarea>

                  <button type="submit" class="btn btn-start-order">Send Message</button>

          </form>

PROBLEM:
As you can see that my PHP, JS, HTML code for the contact form, But for some reason it doesn't work!!??
Every time I try to use it I keep getting (method not allowed)!!!??
I most tried everything (new PHP code different html code)
and note (I'm using it on a site hosted on glitch) it doesn't officially support PHP but it does.

A: I tried you code. It should work except it should be $body instead of body in mail($to, $about, body, "From: $name <$email>");.
So the problem should be from the host provider.
BTW: Gmail seems having more strict security policy. I failed on Gmail and tried another mail service and succeed to receive the email.


Q: Unhandled Promise rejection: Cannot call method 'push' of null I have an issue I just cannot seem to understand. If anyone could offer some advise I would appreciate it.
I am using Ionic2 with Meteor/Mongo to build a Chat App.
I have the following code:
  private findChats(): Promise<Mongo.Collection<Chat>> {
    let promise: Promise<Mongo.Collection<Chat>> = new Promise<Mongo.Collection<Chat>>(resolve => {
      let registeredIds: String[] = [this.senderId];
      for (let i = 0; i < this.jobModelsForSender.length; i++) {
        console.log('findChats:  registeredIds.push this.jobModelsForSender[i].id: ' + registeredIds + '  -  ' + this.jobModelsForSender[i].id);
        registeredIds.push('J' + this.jobModelsForSender[i].id);
        console.log('findChats:  pushed: ' + registeredIds);
      }
      this.subscribe('chats', this.senderId, registeredIds, () => {
        console.log('findChats:  in subscribe: ' + this.senderId+'  '+registeredIds);

        let chats: Mongo.Cursor<Chat> = Chats.find(
          { memberIds: { $in: registeredIds } },
          {
            sort: { lastMessageCreatedAt: -1 },
            transform: this.transformChat.bind(this),
            fields: { memberIds: 1, lastMessageCreatedAt: 1 }
          }
        );
        console.log('findChats:  chats: ' + chats);
        this.chats = chats;
        let localChatCollection: Mongo.Collection<Chat> = new Mongo.Collection<Chat>(null);
        chats.forEach((chat: Chat) => {
          localChatCollection.insert(chat);
        });
        console.log('findChats:  resolve(localChatCollection): ' + localChatCollection);
        resolve(localChatCollection);
      });
    });
    return promise;
  }

But I get the following output:
findChats:  registeredIds.push this.jobModelsForSender[i].id: P8  -  72 app.bundle.js:118232
findChats:  pushed: P8,J72 app.bundle.js:118234
findChats:  registeredIds.push this.jobModelsForSender[i].id: P8  -  72 app.bundle.js:118232
findChats:  pushed: P8,J72 app.bundle.js:118234
findChats:  registeredIds.push this.jobModelsForSender[i].id: P8  -  72 app.bundle.js:118232
findChats:  pushed: P8,J72 app.bundle.js:118234
Unhandled Promise rejection: Cannot call method 'push' of null ; Zone: <root> ; Task: Promise.then ; Value: TypeError {stack: (...), message: "Cannot call method 'push' of null"} zone.js:461
Error {rejection: TypeError, promise: ZoneAwarePromise, zone: Zone, task: ZoneTask, stack: (...)…}
 zone.js:463
Unhandled Promise rejection: Cannot call method 'push' of null ; Zone: <root> ; Task: Promise.then ; Value: TypeError {stack: (...), message: "Cannot call method 'push' of null"} zone.js:461
Error {rejection: TypeError, promise: ZoneAwarePromise, zone: Zone, task: ZoneTask, stack: (...)…}
 zone.js:463
Unhandled Promise rejection: Cannot call method 'push' of null ; Zone: <root> ; Task: Promise.then ; Value: TypeError {stack: (...), message: "Cannot call method 'push' of null"} zone.js:461
Error {rejection: TypeError, promise: ZoneAwarePromise, zone: Zone, task: ZoneTask, stack: (...)…}
 zone.js:463
findChats:  in subscribe: P8  P8,J72 app.bundle.js:118243
findChats:  chats: [object Object] app.bundle.js:118249
findChats:  resolve(localChatCollection): [object Object]

As you can see, I am getting an error in zone.js. As far as I can see, when I debug this, and as the logs show, it does the push successfully to registeredIds. It then exits the function, returning the promise. After that it goes into zone.js where the error is logged.

A: The answer will probably not be relevant to many people, but as Anton pointed out, that it is an issue to do with the promise loading asynchronously.
I had an event that was calling the same promise at the same time. As soon as I remove the trigger to that event, I don't get any errors.


Q: Why is my posted data null in the Controller target of this AJAX call? I have modeled (no pun intended) my AJAX call on the answer here from logan filley, which seems sensible and likely to work. This is the jquery I have in the View:
$("#btnSaveConfig").click(function () {

    var saveConfigModel = {
        unit: $('#unitsselect').val(),
        scheduleProduceUsage: $('#ckbx_produceusage').checked,
        scheduleDeliveryPerformance: $('#ckbx_deliveryperformance').checked,
        scheduleFillRate: $('#ckbx_fillratebycustomer_location').checked,
        schedulePriceCompliance: $('#ckbx_pricecompliance').checked,
        // TODO: Finish this by storing add'l emails in an array along with the three on the page;
        recipients: $('#email1').val(),
        generationDayOfMonth: $('#dayofmonthselect').val(),
        generationOrdinal: $('#ordinalselect').val(),
        generationDayOfWeek: $('#dayofweekselect').val(),
        generationWeekOrMonth: $('#weekormonthselect').val(),
        daterangeFromProduceUsage: $('#produsagefrom').val(),
        daterangeToProduceUsage: $('#produsageto').val(),
        daterangeFromDeliveryPerformance: $('#delperffrom').val(),
        daterangeToDeliveryPerformance: $('#delperfto').val(),
        daterangeFromFillRate: $('#fillratefrom').val(),
        daterangeToFillRate: $('#fillrateto').val(),
        daterangeFromPriceCompliance: $('#pricecompliancefrom').val(),
        daterangeToPriceCompliance: $('#pricecomplianceto').val()
    }

    $.ajax({
        type:"POST",
        url:'@Url.Action("PostUnitConfig", "SaveConfig")',
        async:true,
        contentType: 'application/json',
        dataType:"json",
        data: JSON.stringify(saveConfigModel)
    });
}); // $("#btnSaveConfig").click()

...and this is my Model:
public class SaveConfigModel
{
    public UnitConfigVals unitConfigVals { get; set; }

    public class UnitConfigVals
    {
        public string unit { get; set; }
        public bool scheduleProduceUsage { get; set; }
        public bool scheduleDeliveryPerformance { get; set; }
        public bool scheduleFillRate { get; set; }
        public bool schedulePriceCompliance { get; set; }
        public List<string> recipients { get; set; }
        public int generationDayOfMonth { get; set; }
        public string generationOrdinal { get; set; }
        public string generationDayOfWeek { get; set; }
        public string generationWeekOrMonth { get; set; }
        public int daterangeFromProduceUsage { get; set; }
        public int daterangeToProduceUsage { get; set; }
        public int daterangeFromDeliveryPerformance { get; set; }
        public int daterangeToDeliveryPerformance { get; set; }
        public int daterangeFromFillRate { get; set; }
        public int daterangeToFillRate { get; set; }
        public int daterangeFromPriceCompliance { get; set; }
        public int daterangeToPriceCompliance { get; set; }
    }
}

...and Controller (obviously ultra-spartan at the moment):
public class SaveConfigController : Controller
{
    public ActionResult PostUnitConfig(SaveConfigModel model)
    {
        try
        {
            string s = model.unitConfigVals.unit;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return Json(new { success = true });
    }
}

I am reaching the breakpoint in my Controller (on the "string s = model.unitConfigVals.unit;" line), but it throws an exception because the value of "model" is null. Why? Have I got something in my AJAX call wrong, or...?!?
UPDATE
I changed my jquery to this (changed boolean assignments and appended a semicolon):
   $("#btnSaveConfig").click(function() {

      var saveConfigModel = {
        unit: $('#unitsselect').val(),
        scheduleProduceUsage: $('#ckbx_produceusage').attr('checked'),
        scheduleDeliveryPerformance:
        . . .
    };

    $.ajax({
        type: "POST",
        url: '@Url.Action("PostUnitConfig", "SaveConfig")',
        async: true,
        //contentType: 'application/json',
        dataType: "json",
        data: JSON.stringify({ data: saveConfigModel })
    });
});

...but the Controller is still passed a null model.
UPDATE 2
Now I changed "attr('checked')" to "is('checked')" but no difference...
UPDATE 3
"model" is null here in the Controller:
public class SaveConfigController : Controller
{
    public ActionResult PostUnitConfig(SaveConfigModel model)

...when the AJAX call is like this:
$.ajax({
    type: "POST",
    url: '@Url.Action("PostUnitConfig", "SaveConfig")',
    async: true,
    dataType: "json",
    data: saveConfigModel
});

...and also when the AJAX call is like this:
$.ajax({
    type: "POST",
    url: '@Url.Action("PostUnitConfig", "SaveConfig")',
    async: true,
    data: saveConfigModel
});

...and this:
$.ajax({
    type: "POST",
    url: '@Url.Action("PostUnitConfig", "SaveConfig")',
    async: true,
    contentType: 'application/json',
    dataType: "json",
    data: JSON.stringify({ model: saveConfigModel })
});

Do I need the "async: true"? I don't use that in my (working) GET AJAX calls. Similarly, do I need "cache: false"? I do use that in those working GET AJAX calls...
UPDATE 4
Even when I provide just some bogus vals:
var saveConfigModel = {
    unit: 'Buford', //$('#unitsselect').val(),
    scheduleProduceUsage: true, //$('#ckbx_produceusage').is(':checked'),
    scheduleDeliveryPerformance: false, // $('#ckbx_deliveryperformance').is(':checked'),
    scheduleFillRate: false, //$('#ckbx_fillratebycustomer_location').is('checked'),
    schedulePriceCompliance: false, //$('#ckbx_pricecompliance').is('checked'),
    // TODO: Finish this by storing add'l emails in an array along with the three on the page; might be as easy as declaring an array like this one, and adding to it as necessary
    recipients: 'platypus@whatever.com', // $('#email1').val(),
    generationDayOfMonth: '2nd', //$('#dayofmonthselect').val(),
    generationOrdinal: 'First', //$('#ordinalselect').val(),
    generationDayOfWeek: 'Thursday', // $('#dayofweekselect').val(),
    generationWeekOrMonth: 'month', // $('#weekormonthselect').val(),
    daterangeFromProduceUsage: $('#produsagefrom').val(),
    daterangeToProduceUsage: $('#produsageto').val(),
    daterangeFromDeliveryPerformance: '1', // $('#delperffrom').val(),
    daterangeToDeliveryPerformance: '1', //$('#delperfto').val(),
    daterangeFromFillRate: '1', //$('#fillratefrom').val(),
    daterangeToFillRate: '1', //$('#fillrateto').val(),
    daterangeFromPriceCompliance: '1', //$('#pricecompliancefrom').val(),
    daterangeToPriceCompliance: '1' //$('#pricecomplianceto').val()
};

...it still winds up at the Controller null like forevermore before.
And then, grasping at straws, I even encased the boolean values in single quotes ('true' and 'false'), but that also (probably predictably) made no difference either.
UPDATE 5
For future generations, this is the AJAX that works:
$.ajax({
    type: "POST",
    url: '@Url.Action("PostUnitConfig", "SaveConfig")',
    async: true,
    contentType: 'application/json',
    dataType: "json",
    data: JSON.stringify({ model: saveConfigModel })
});

A: Since the values you posting back are for your nested UnitConfigVals class (not SaveConfigModel, then you controller method should be
public ActionResult PostUnitConfig(SaveConfigModel.UnitConfigVals model)

and the ajax data option needs to be
data: JSON.stringify({ model: saveConfigModel })

Alternatively you could keep the current controller method and use
data: JSON.stringify({ model: { unitConfigVals: saveConfigModel }})

although it seems a little odd that you using a nested class here.
A few other issues with your initial code

*

*$('#ckbx_produceusage').checked will return undefined, and it
needs to be $('#ckbx_produceusage').is(':checked') which will
return true or false

*Since recipients is List<string>, it will need to be
recipients: [ 'someValue', 'anotherValue', etc ]
However all this code to build you json data not really necessary, and if your view is generated correctly using the strongly typed HtmlHelper methods, then your ajax call can be as simple as
$.ajax({
    type:"POST",
    url:'@Url.Action("PostUnitConfig", "SaveConfig")',
    dataType: "json",
    data: $('form').serialize(),
    success: function(data) {
        // do something
    }
});


Q: qDebug output in qtCreator while running unit tests with catch2 I have a project with unittests which are implemented with catch2 and using the catch2-integration in qtcreator. The unittests contain qDebug()<<"message" calls. The project uses CMAKE as build system. Everything compiles and I can both run the tests as standalone application and with the interface (i.e. "run selected tests") in qtcreator. Currently it is compiled in debug-mode.
However, when running in a terminal, I get all qDebug messages.
If I'm running the main application (not the unit tests), I can observe qDebug messages in the "Application output" tab.
However, if I'm running the unit tests, no matter if I use qtCreator interface or start debugging or run the compiled tests, the "Application output" stays empty.
As stated above, I'm able to see them in a terminal, but then I only can run the full test suite, while I would hope to be able only to run selected tests and get their output.
What needs to be in place that the qDebug messages which originate from catch2 unittests in qtcreator are displayed in the "Application Output" tab during test execution?
QtCreator 7.0.0, Windows, MSVC2019, 64Bit.
Amongst others I already tried (without luck): QtCreator: qDebug Messages Not Shown


Q: c/c++ clang linking error on Mac OSX - webkitgtk I am trying to use GTK3 and WebKitGTK. I am successful at running the following code :
#include <gtk/gtk.h>
#include <webkit2/webkit2.h>
#include <JavaScriptCore/JavaScript.h>

using namespace std;

static void destroyWindowCb(GtkWidget* widget, GtkWidget* window);
static gboolean closeWebViewCb(WebKitWebView* webView, GtkWidget* window);

int main(int argc, char* argv[])
{
// Initialize GTK+
gtk_init(&argc, &argv);

// Create an 800x600 window that will contain the browser instance
GtkWidget *main_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_default_size(GTK_WINDOW(main_window), 800, 600);

// Create a browser instance
WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new());

// Put the browser area into the main window
gtk_container_add(GTK_CONTAINER(main_window), GTK_WIDGET(webView));

// Set up callbacks so that if either the main window or the browser instance is
// closed, the program will exit
g_signal_connect(main_window, "destroy", G_CALLBACK(destroyWindowCb), NULL);
g_signal_connect(webView, "close", G_CALLBACK(closeWebViewCb), main_window);

// Load a web page into the browser instance
webkit_web_view_load_uri(webView, "http://www.webkitgtk.org/");

// Make sure that when the browser area becomes visible, it will get mouse
// and keyboard events
gtk_widget_grab_focus(GTK_WIDGET(webView));

// Make sure the main window and all its contents are visible
gtk_widget_show_all(main_window);

// Run the main GTK+ event loop
gtk_main();

return 0;
}

static void
destroyWindowCb(GtkWidget* widget, GtkWidget* window)
{
    gtk_main_quit();
}

static gboolean
closeWebViewCb(WebKitWebView* webView, GtkWidget* window)
{
    gtk_widget_destroy(window);
    return TRUE;
}

And the following cmake list :
cmake_minimum_required(VERSION 3.3)
project(HttpsMock)

# Use the package PkgConfig to detect GTK+ headers/library files
find_package(PkgConfig REQUIRED)

pkg_check_modules(GTK3 REQUIRED gtk+-3.0)
pkg_check_modules(WEBKIT REQUIRED webkitgtk-3.0)

# Setup CMake to use GTK+, tell the compiler where to look for headers
include_directories(${GTK3_INCLUDE_DIRS})
include_directories(${WEBKIT_INCLUDE_DIRS})

# and to the linker where to look for libraries
link_directories(${GTK3_LIBRARY_DIRS})
link_directories(${WEBKIT_LIBRARY_DIRS})

# Add other flags to the compiler
add_definitions(${GTK3_CFLAGS_OTHER})
add_definitions(${WEBKIT_CFLAGS_OTHER})

# Flags and source
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -v")

set(SOURCE_FILES main.cpp)

add_executable(HttpsMock ${SOURCE_FILES})
# Linking
target_link_libraries(HttpsMock ${GTK3_LIBRARIES})
target_link_libraries(HttpsMock ${WEBKIT_LIBRARIES})

But as soon as I try to use another method like :
WebKitURIRequest *request = webkit_uri_request_new("http://www.webkitgtk.org/");

The program doesn't want to link anymore. It's really weird. Here's a sample of the error :
[100%] Linking CXX executable HttpsMock
Apple LLVM version 7.0.0 (clang-700.0.72)
Target: x86_64-apple-darwin14.5.0
Thread model: posix
 "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" -demangle -dynamic -arch x86_64 -macosx_version_min 10.10.0 -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk -o HttpsMock -L/opt/local/lib -search_paths_first -headerpad_max_install_names CMakeFiles/HttpsMock.dir/main.cpp.o -lwebkitgtk-3.0 -lgtk-3 -lgdk-3 -lpangocairo-1.0 -lpangoft2-1.0 -lpango-1.0 -lm -lfontconfig -lfreetype -latk-1.0 -lcairo-gobject -lcairo -lgdk_pixbuf-2.0 -lsoup-2.4 -lgio-2.0 -lgobject-2.0 -ljavascriptcoregtk-3.0 -lglib-2.0 -lintl -rpath /opt/local/lib -lc++ -lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/7.0.0/lib/darwin/libclang_rt.osx.a
Undefined symbols for architecture x86_64:
  "_webkit_uri_request_new", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture x86_64

I really have no clue of what is going on. Could someone please enlighten me?
Thanks

A: The problem is that I was using
pkg_check_modules(WEBKIT REQUIRED webkitgtk-3.0)
instead of
pkg_check_modules(WEBKIT REQUIRED webkit2gtk-3.0)


Q: Spring Batch CompositeItemWriter How to properly set writer delegates Hi I am trying to add two writers to a spring batch compositeitemwriter. I am getting an error saying:
The method setDelegates(List<ItemWriter<? super MyObject>>) in the type CompositeItemWriter<MyObject> is not applicable for the arguments (List<ItemWriter<MyObject>>)

My code below
public ItemWriter<MyObject> myWriter(){
    ItemWriter<MyObject> myWriter = new myWriter();
    return myWriter;
}

public ItemWriter<MyObject> myOtherWriter(){
    ItemWriter<MyObject> myOtherWriter = new MyOtherWriter();
    return myOtherWriter;
}

public CompositeItemWriter<MyObject> compositeItemWriter(){
    CompositeItemWriter<MyObject> writer = new CompositeItemWriter<MyObject>();
    List<ItemWriter<MyObject>> writerList = new ArrayList<ItemWriter<MyObject>>();
    writerList.add(myWriter());
    writerList.add(myOtherWriter());
    writer.setDelegates(writerList); //<-- ERROR HERE
    return writer;
}

I could not find any strong code examples of compositeitemwriters that did not use xml. I know my error has something to do with generic type parameters, which I have little knowledge of. Could anyone explain why the above code would not work and possibly how to remedy it? Multiple itemwriters in Spring batch This is the closest I could find, but it uses generic types which also give me an error.
Thank you for any help! I am new to spring batch.

A: Try modifying...
List<ItemWriter<MyObject>> writerList = new ArrayList<ItemWriter<MyObject>>();

...with :
List<ItemWriter<? super MyObject>> writerList = new ArrayList<ItemWriter<? super MyObject>>();

CompositeItemWriter#setDelegates takes a list in the form List<ItemWriter<? super T>>.
See spring documentation.

A: Just in case you did not find a proper solution.
I would do it like this:
public ItemWriter<MyObject> myWriter() {
    ItemWriter<MyObject> myWriter = new JdbcBatchItemWriter<MyObject>(); //  <-- Example item writer 1
    return myWriter;
}

public ItemWriter<MyObject> myOtherWriter() {
    ItemWriter<MyObject> myOtherWriter = new JdbcBatchItemWriter<MyObject>(); //  <-- Example item writer 2
    return myOtherWriter;
}

public CompositeItemWriter<MyObject> compositeItemWriter() {
    CompositeItemWriter<MyObject> writer = new CompositeItemWriter<MyObject>();
    writer.setDelegates(Arrays.asList(myWriter(),myOtherWriter())); //<-- NO ERROR HERE :)
    return writer;
}

I hope that helps.


Q: How can I implement a decay for a matrix transformation with react-native-gesture-handler and reanimated? I'm trying to learn react-native-gesture-handler and react-native-reanimate. I like the idéa of using matrices for transformation, but I have a hard time understanding where to fit in physics functions, such as withDecay.
I want to use the new Gestures API (https://docs.swmansion.com/react-native-gesture-handler/docs/api/gestures/gesture) instead of the old gestureHandler API (https://docs.swmansion.com/react-native-gesture-handler/docs/gesture-handlers/api/common-gh)
Here is a nice example of using matrices for transformation and simply multiplying the change-matrice with the current matrice.
https://github.com/wcandillon/can-it-be-done-in-react-native/blob/master/bonuses/sticker-app/src/GestureHandler.tsx
This concept works great, but I also want to have a decay effect after ending a pan, i.e. the translation should continue to glide a bit.
Here is my first attempt. It does not work, and might be a bit naive. But I think that the code shows what I want to do. I just don't know how to do it correctly. My attempt was to add the .onEnd event, compared to Williams Candillon's original code.
  const pan = Gesture.Pan()
    .onChange(e => {
      matrix.value = multiply4(
        Matrix4.translate(e.changeX, e.changeY, 0),
        matrix.value,
      );
    })
    .onEnd(({velocityX, velocityY}) => {
      matrix.value = multiply4(
        Matrix4.translate(
          withDecay({velocity: velocityX}),
          withDecay({velocity: velocityY}),
          0,
        ),
        matrix.value,
      );
    });

A: the problem here is the withDecay returns an animation value (it auto update). So the idea would be to do trX.value = withDecay(), same of y and then use useDerivedValue to get the total Matrix4. I hope this helps.


Q: Cannot Remove Underline From Vue router-link I think I tried almost everything trying to remove underline from router-link.
This is my code:
<router-link :to="{name: 'Plan'}">

Plan Your Trip

      <router-link :to="{name: 'Plan'}">COVID-19</router-link>
      <router-link :to="{name: 'Plan'}">Visa</router-link>
      <router-link :to="{name: 'Plan'}">Essentials</router-link>

</router-link>

I'm trying to remove underline from sub-links only.
Things I've tried:
In-line style
<router-link style="text-decoration: none !important;" :to="{name: 'Plan'}">COVID-19</router-link>

Assign class
<router-link class="sub-link" :to="{name: 'Plan'}">COVID-19</router-link>

Declare tag
<router-link tag="div" :to="{name: 'Plan'}">COVID-19</router-link>

Assign seperate tag + Declare class for that tag
<router-link :to="{name: 'Plan'}">

COVID-19

</router-link>

These are just few lists, I literally tried every possible methods I can think of... Am I missing something about customizing Vue router-link?

A: Uses display: inline-block;text-decoration:none;, the trick is display: inline-block;.
Css spec states

For block containers that establish an inline formatting context, the
decorations are propagated to an anonymous inline element that wraps
all the in-flow inline-level children of the block container. For all
other elements it is propagated to any in-flow children. Note that
text decorations are not propagated to floating and absolutely
positioned descendants, nor to the contents of atomic inline-level
descendants such as inline blocks and inline tables.

Example: The link COVID-19 in your codes will remove the underline.
<router-link :to="{name: 'Plan'}">

Plan Your Trip

      <router-link :to="{name: 'Plan'}" style="display: inline-block;text-decoration:none;">COVID-19</router-link>
      <router-link :to="{name: 'Plan'}">Visa</router-link>
      <router-link :to="{name: 'Plan'}">Essentials</router-link>

</router-link>

Below is one demo:

let Layout = {
  template: `

Layout Page

  <router-link to="/contact">

Links

    <router-link to="/contact/add" style="display: inline-block;text-decoration:none;">Add1</router-link>
    <router-link to="/addcontact">Add2</router-link>

  </router-link>
  <router-view></router-view>

`
};
let Home = {
  template: '
this is the home page. Go to <router-link to="/contact">contact</router-link>
'
};

let ContactList = {
  // add <router-view> in order to load children route of path='/contact'
  template: '
this is contact list, click <router-link to="/contact/add">Add Contact In sub Router-View</router-link> here to add contact
<router-view></router-view>
 Or Click <router-link to="/addcontact">Add Contact In Current Router-View</router-link>
'
};

let ContactAdd = {
  template: '
Contact Add
'
}

let router = new VueRouter({
  routes: [{
    path: '/',
    redirect: 'home',
    component: Layout,
    children: [{
        path: 'home',
        component: Home
      },
      {
        path: 'contact',
        component: ContactList,
        children: [{
          path: 'add',
          component: ContactAdd
        }]
      },
      {
        path: 'addcontact', // or move ContactAdd as direct child route of path=`/`
        component: ContactAdd,
      }
    ]
  }]
});

new Vue({
  el: '#app',
  components: {
    'App': {
      template: '
<router-view></router-view>
'
    },
  },
  router
});

  <app></app>

A: When you inspect the DOM for a router-link, you see that it's an a tag. Bear in mind, that even when the initial underline is removed, there is an underline that happens when you hover over the router link text.
Using this snippet

<router-link :to="{name: 'Plan'}">

Plan Your Trip

      <router-link :to="{name: 'Plan'}">COVID-19</router-link>
      <router-link :to="{name: 'Plan'}">Visa</router-link>
      <router-link :to="{name: 'Plan'}">Essentials</router-link>

</router-link>

.expander a {
  text-decoration: none;
}

.expander a:hover {
  text-decoration: none;
}

A: The outer router-link is applying text-decoration: underline to its inner-text and the inner router-links are also applying text-decoration: underline to their inner-text.
You essentially have double underlines applied to your inner router-links at the moment.
You need to remove it from both. If you need another element to have text-decoration: underline then set it for that element separately.


Q: jQuery ui Slider for Background and Font Colors I have a problem regarding my new site design prospect, and it involves using some jQuery and jQueryUI (mainly SliderUi) and some css manipulation.
Everytime I slide the #slider, the width of .left will then update depend on (ui.value from 1-100 + '%'), from here slide + background transition is happening already,
My question is is there any possible way to manipulate the color of texts depending on slider's treshold or value? if yes, can you suggest how can I come up into something like this?
Snippet below.
Thanks in advance!

$(document).ready(function() {
  $( "#slider" ).slider({
    max: 101,
    min:1,
    value: 51,
    slide: function(event,ui) {
      var percentage = (ui.value)-1;
      $('.left').css("width",percentage +'%');
    }
  });
});
#slider {z-index: 5;background: #666; }
.left, .right {positioackgrn:absolute; top: 0; left: 0; height: 100vh;}
.left {background: #000; width: 50%; z-index: 1;}
.right {background: #fff;  z-index: -1; width: 100%;}
.main-content {z-index: 3; position: absolute; top: 0; left: 0; width: 100%;}
h3 {color: blue; text-align: center; margin-top: 30px;}
<link href="https://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

A part of my font must change color depending on slider-ui threshold

A: Update!
http://jsfiddle.net/lsubirana/7od3sfrr/1/
HTML:

My font color must change depending on slider-ui threshold

My font color must change depending on slider-ui threshold

CSS:
.left, .right {position:absolute; top: 0; left: 0; height: 100vh;overflow:hidden;}
.left h3 {color: white; text-align: center; margin-top: 30px;width:100vw;}
.right h3 {color: black; text-align: center; margin-top: 30px;width:100vw;}

Original Answer:
One method to obtain what you are looking for is to pass the slider percentage to a function that can return you an rgb color value. The following page shows how to create rainbows in javascript and I believe can be applied in this case:
http://krazydad.com/tutorials/makecolors.php
$(document).ready(function() {
  $( "#slider" ).slider({
    max: 101,
    min:1,
    value: 51,
    slide: function(event,ui) {
      var percentage = (ui.value)-1;
      $('.left').css("width",percentage +'%');
      $('h3').css('color', rgb(percentage));
    }
  });
});

function rgb(p){
    var frequency = .08;
       r = Math.sin(frequency*p + 0) * 127 + 128;
       g = Math.sin(frequency*p + 2) * 127 + 128;
       b = Math.sin(frequency*p + 4) * 127 + 128;
     return  'rgb(' + Math.round(r) + ',' + Math.round(g) + ',' + Math.round(b) + ')';
}

http://jsfiddle.net/lsubirana/376ow969/


Q: Extract fields from Json using Kusto in Application Insights I have the following json contained in a particular field in the traces.customDimensions:

When I parse this Json to extract a particular value I always get an empty column, for example:
traces | order by timestamp desc
| project CurrentContext = parse_json(customDimensions.CurrentPluginContext)
| extend Source = CurrentContext.source
| project Source

The query returns the following:

I've also tried:
traces | order by timestamp desc
| project timestamp, CurrentContext = customDimensions.CurrentPluginContext, CurrentParentContext = customDimensions.CurrentParentluginContext,
Source = parse_json(tostring(customDimensions.CurrentPluginContext)).source,
DepthCurrentContext = parse_json(tostring(customDimensions.CurrentPluginContext)).depth,
DepthCurrentParentContext = parse_json(tostring(customDimensions.CurrentParentluginContext)).depth
| mv-expand CurrentContext
| extend Source = CurrentContext.source

But here I get also an empty "Source" column. And the Columns "DepthCurrentContext" and "DepthCurrentParentContext" do not even appear.

The Json is valid.
Do I miss something here?
Any help is very appreciated!
UPDATE 27.02.2023
When I do the following:
let json = '{"source": "GetUserData","correlationId": "00000000-0000-0000-0000-000000000000","depth": "1","initiatingUserId": "00000000-0000-0000-0000-000000000000","isInTransaction": "False","isolationMode": "2","message": "Update","mode": "Asynchronus","operationId": "00000000-0000-0000-0000-000000000000","orgId": "00000000-0000-0000-0000-000000000000","orgName": "unqXXXXXXXXXXXXXXXXXXXX","requestId": "00000000-0000-0000-0000-000000000000","userId": "00000000-0000-0000-0000-000000000000","entityId": "00000000-0000-0000-0000-000000000000","entityName": "systemuser","type": "Plugin","stage": "Post-operation"}';

traces
| extend properties = parse_json(json)
| project Source = properties.source, CorrelationID = properties.correlationId

I get the properties out of the Json. The Json is the exact same as the ohne from the log.
Any idea?

A: as mentioned in the documentation: you will need to use tostring on the internal property bag.
i.e. parse_json(tostring(parse_json(customDimensions).CurrentPluginContext))

A: traces | order by timestamp desc
| project CurrentContext = parse_json(customDimensions.CurrentPluginContext)
| extend Source = parse_json(tostring(CurrentContext)).source
| project Source


Q: getting sql error unknown column in where clause when trying to filter data In the SQL query where city clause when I put string 'delhi' I get results but when I put a variable like below I get error unknown column delhi in where clause. how to solve the issue?
router.get('/filter/:city', (req, res) => {
  const location = req.params.city;
  const singleQuoteLocation = location.replace(/"/g, "'");
  connection.query(
    `select * from weather_data where city=${singleQuoteLocation}`,
    (err, results, field) => {
      if (err) {
        console.log(err);
      } else {
        res.status(200).send(results);
        console.log(results);
      }
    }
  );
});

A: You should be using a prepared statement with a ? placeholder for the city value.  Then, bind a JS variable to the ?.
router.get('/filter/:city', (req, res) => {
  const location = req.params.city;
  connection.query(
    "SELECT * FROM weather_data WHERE city = ?", [location],
    (err, results, field) => {
      if (err) {
        console.log(err);
      }
      else {
        res.status(200).send(results);
        console.log(results);
      }
    }
  );
});

Note that when using a prepared statement there is no need to massage the location variable by doing things like wrapping in single quotes.  Instead, let your MySQL driver worry about how to handle this, via the prepared statement.

A: `select * from weather_data where city = \'${singleQuoteLocation}\' `


Q: How to stretch table within a cell (nested table) in html? Nested table does not 100% height of parent td
I have used height="100%" but did not help
HTML:

Text

Text

Text

Text

Text

Text

Text

Actual result: https://jsfiddle.net/fela93/8ysfawve/17/


Q: What is the most efficient way to find rows of a CSV not containing duplicate entries across the fields of that row (excluding blank entires)? I'm looking to find all of the rows of a CSV file that contain the duplicate data in two or more of the fields of that row (i.e. find all of the rows without unique data in each field.)
For example, I have the following CSV file:
John,Smith,Smith,21
Mary,Jones,Smith,32
John,42,42,42
Henry,Brown,Jones,31
Mary,,,21

I would want the following rows to be printed:
John,Smith,Smith,21
John,42,42,42

These rows are printed because a the data in one field of these rows occurs in another field. Note that "Mary,,,21" was not printed even though it has duplicate empty fields.
I could write a Python script and keep a count of the times each entry occurs in each row, but it seems like there must be a better way to do this.

A: Using perl:
perl -F, -lane 'my %s; print if grep { $s{$_}++ } @F'

Uses:

*

*-F, to set field separator to ,

*-l to automatically handle linefeeds

*-a to autosplit

*-n to wrap it in a while ( <> ) { loop.

*-e to specify code to exec.

Incoming data is autosplit on , into @F and we use a %s hash to spot if there's a dupe.
If — based on your comment — you need to skip empty fields (which this would count as dupes):
perl -F, -lane 'my %s; print if grep { /./ ? $s{$_}++ : () } @F'

This includes a ternary operator to test if a field is empty.
Testing with Windows (which isn't quite the same, because of quotes):
C:\Users\me>perl -F, -lane "my %s; print qq{line matches:$_} if grep { /./ ? $s{$_}++ : () } @F"
line matches:John,Smith,Smith,21
line matches:John,42,42,42

If written longhand, it looks more like this:
#!/usr/bin/env perl
use strict;
use warnings;

while ( my $line = <DATA> ) {
   my %seen;
   chomp($line);
   my @fields = split /,/, $line;
   if ( grep { /./ and $seen{$_}++ } @fields ) {
       print $line,"\n";
   }
}

__DATA__
John,Smith,Smith,21
Mary,Jones,Smith,32
John,42,42,42
Henry,Brown,Jones,31
Mary,,,21

You could use the Text::CSV module to parse it, but I would suggest not doing so, unless you're specifically dealing with quoting/embedded linefeeds etc.
E.g.:
#!/usr/bin/env perl
use strict;
use warnings;

use Data::Dumper;
use Text::CSV;

my $csv = Text::CSV -> new ( {sep_char => ',', eol => "\n", binary => 1} );

while ( my $row = $csv -> getline ( \*DATA ) ) {
   my %seen;
   if ( grep { /./ and $seen{$_}++ } @$row ) {
       print join ",", @$row, "\n";
   }
}

__DATA__
John,Smith,Smith,21
Mary,Jones,Smith,32
John,42,42,42
Henry,Brown,Jones,31
Mary,,,21

A: Using awk you can do:
awk -F, '{delete a; for (i=1;i<=NF;i++) if ($i!="") if ($i in a) {print; next} else a[$i]}' file

John,Smith,Smith,21
John,42,42,42

A: $ awk -F, '{delete seen; for (i=1;i<=NF;i++) if ( ($i!="") && seen[$i]++ ) { print; next } }' file
John,Smith,Smith,21
John,42,42,42

A: If you'd like a Perl solution that you can integrate into a larger script (and doesn't quite so closely resemble line noise), and that correctly handles CSV data where a field contains a comma, I'd use the Text::CSV module:
#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV;

my $file = shift or die "Usage: $0 <file>\n";

open my $fh, '<', $file or die "Cannot open $file: $!\n";

my $csv = Text::CSV->new();

while (my $row = $csv->getline($fh)) {
   my %h;
   $h{$_}++ for @{$row};
   for my $dup_field (grep { $h{$_} > 1 } keys %h)  {
      if (length $dup_field) {
          print $csv->string();
          next;
      }
   }
}

A: If you like perl and regex, then this looks good :
perl -ne 'print if /(?:^|,)([^,]+),(?:.*,)?\1(?:,|$)/'
If you need explanations :
([^,]+) matches a "word" (in that context, I use "word" to mean "the data of a row"), and \1 will see if it is repeated. (?:.*,)? allows other words to be between the repetitions of your data. And finally (?:^|,) and (?:,|$) ensure that the 2 repeated words are the same, and no one is a substring of the other.


Q: how to implement level order print for MaxHeap I'm currently making a MaxHeap program and I need to print my heap in level order. How can this be done? Do I create a method to print the heap in level order inside of my heap class or would I do it in my main class? I know for like my binary search tree project i used iterative methods and called them from my main class but I'm not sure if I can do that here. Below is my implementation of the MaxHeap class from my textbook:
public final class MaxHeap<T extends Comparable<? super T>> implements MaxHeapInterface<T>
{
private T[] heap;
private int lastIndex;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 25;
private static final int MAX_CAPACITY = 10000;

int swaps=0;

public MaxHeap() {
this(DEFAULT_CAPACITY);
}

public MaxHeap(int initialCapacity) {
if (initialCapacity < DEFAULT_CAPACITY)
    initialCapacity = DEFAULT_CAPACITY;
else
    checkCapacity(initialCapacity);

@SuppressWarnings("unchecked")
T[] tempHeap = (T[]) new Comparable[initialCapacity + 1];
heap = tempHeap;
lastIndex = 0;
initialized = true;
}

public T getMax() {
checkInitialization();
T root = null;
if (!isEmpty())
    root = heap[1];
return root;
}


Q: How to Unescape a JavaScript string in Ruby What is the simplest way to unescape the following string in Ruby.
Sample Input
str = "\\u003Cul id=\\\"list_example\\\"\\u003E\\n\\t\\u003Cli class=\\\"item_example\\\"\\u003EHello\\u003C/li\\u003E\\n\\u003C/ul\\u003E\\n\\n"
puts str # => \u003Cul id=\"list_example\"\u003E\n\t\u003Cli class=\"item_example\"\u003EHello\u003C/li\u003E\n\u003C/ul\u003E\n\n
str.encoding # => #<Encoding:UTF-8>

Desired Output
puts str #=>

Hello

A: The simplest approach is just to read the string as a JSON string.
unescaped_str = JSON.load("\"#{str}\"")

A: That string is escaped twice. There are a few ways to unescape it. The easiest is eval, though it is not safe if you don't trust the input. However if you're sure this is a string encoded by ruby:
print eval(str)

Safer:
print YAML.load(%Q(---\n"#{str}"\n))

If it was a string escaped by javascript:
print JSON.load(%Q("#{str}"))

See also Best way to escape and unescape strings in Ruby?


Q: 'future_to_publish' hook not working in wordpress I'm trying to save data to a file when a scheduled post is published. I tried to do this using the hooks 'future_to_publish', 'publish_future_post', 'transition_post_status' - none of them worked for me. I experimented with changing the priority of the hooks - didn't work either.
This is my code:
<?php
function savePostData( $ID ) {
$wpRootPath     = get_home_path();
$postsDataPath  =  $wpRootPath . 'test.txt';
$handle = fopen( $postsDataPath, "w" );
fwrite( $handle, $ID );
fclose( $handle );
}
add_action( 'future_to_publish', 'savePostData', 10, 1 );
?>

When attaching the same function to the following hooks everything works:
add_action( 'publish_post', 'savePostData', 10, 1 );
add_action( 'pending_to_publish', 'savePostData', 10, 1 );
add_action( 'draft_to_publish', 'savePostData' );

I read there is some problem with the is_admin() function interfering with the wordpress cron job, but, still, I cannot get this to work.

A: It turned out when a post is published with cron, 'publish_post' hook is also executed and I didn't need to use it together with the 'future_to_publish' hook.
The problem with both hooks, however, was that for some reason get_home_path(); does not work in the same way as when the post is published immediately from admin panel, so using the exact path to my file solved the problem.


Q: Downloading a Nested DT table in Shiny I've got a nested DT table in my Shiny app. The child table is a list that gets passed and rendered into the table. When I go to add a download button via DT's built in method, the output contains the parent table data and then a list of [Object][Object].. instead of the actual child data.
Do I have to write my own downloadable button method instead of using DT's method or is there a original DT method that helps with this? Haven't found a solution yet.
Data
Parent
structure(list(Market = c("ABILENE, TX", "AKRON, OH"), `SQAD CPP ($)` = c(10,
49), `SQAD CPM ($)` = c(22, 30), `Override CPP ($)` = c(0, 0),
    `Override CPM ($)` = c(0, 0)), .Names = c("Market", "SQAD CPP ($)",
"SQAD CPM ($)", "Override CPP ($)", "Override CPM ($)"), row.names = c(NA,
-2L), class = "data.frame")

Child
structure(list(Market = c("ABILENE, TX", "ABILENE, TX", "ABILENE, TX",
"ABILENE, TX", "ABILENE, TX", "ABILENE, TX", "ABILENE, TX", "ABILENE, TX",
"ABILENE, TX", "AKRON, OH", "AKRON, OH", "AKRON, OH", "AKRON, OH",
"AKRON, OH", "AKRON, OH", "AKRON, OH", "AKRON, OH", "AKRON, OH"
), Daypart = c(" Podcast", " Streaming/Digital Audio", "Afternoon Drive",
"Daytime", "Evening", "Mon-Fri Average", "Mon-Sun Average", "Morning Drive",
"Weekend", " Podcast", " Streaming/Digital Audio", "Afternoon Drive",
"Daytime", "Evening", "Mon-Fri Average", "Mon-Sun Average", "Morning Drive",
"Weekend"), `Mix (%)` = c(10L, 10L, 10L, 10L, 10L, 10L, 5L, 15L,
10L, 10L, 10L, 10L, 10L, 10L, 10L, 5L, 15L, 10L), `Spot:60 (%)` = c(4,
4, 4, 4, 4, 4, 2, 6, 4, 4, 4, 4, 4, 4, 4, 2, 6, 4), `Spot:30 (%)` = c(6,
6, 6, 6, 6, 6, 3, 9, 6, 6, 6, 6, 6, 6, 6, 3, 9, 6), `SQAD CPP ($)` = c(10,
6, 27, 31, 44, 32, 31, 26, 26, 34, 21, 170, 156, 112, 151, 136,
177, 95), `SQAD CPM ($)` = c(21, 13, 57.6, 64.8, 93.6, 68.4,
64.8, 54, 54, 21, 13, 104.5, 96.1, 69, 93, 83.6, 108.7, 58.5),
    `Override CPP ($)` = c(10, 6, 27, 31, 44, 32, 31, 26, 26,
    34, 21, 170, 156, 112, 151, 136, 177, 95), `Override CPM ($)` = c(21,
    13, 57.63, 64.83, 93.64, 68.43, 64.83, 54.03, 54.03, 21,
    13, 104.49, 96.13, 68.96, 92.99, 83.59, 108.67, 58.51), population = c(47200L,
    47200L, 47200L, 47200L, 47200L, 47200L, 47200L, 47200L, 47200L,
    162700L, 162700L, 162700L, 162700L, 162700L, 162700L, 162700L,
    162700L, 162700L), slider_60s = c(0.4, 0.4, 0.4, 0.4, 0.4,
    0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4,
    0.4), slider_30s = c(0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6,
    0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6)), .Names = c("Market",
"Daypart", "Mix (%)", "Spot:60 (%)", "Spot:30 (%)", "SQAD CPP ($)",
"SQAD CPM ($)", "Override CPP ($)", "Override CPM ($)", "population",
"slider_60s", "slider_30s"), class = "data.frame", row.names = c(NA,
-18L))

Code
# Bind the market level and mix breakout data together for the final table
market_mix_table <- reactive({
  # Take a dependency on input$goButton
  input$goButton

  isolate({
    markets <- market_costings_gross_net()
    mix_breakout <- mix_breakout_digital_elements()
    # Make the dataframe
    # This must be met length(children) == nrow(dat)
    Dat <- NestedData(
      dat = markets,
      children = split(mix_breakout, mix_breakout$Market)
    )
    return(Dat)
  })
})

# Render the table
output$daypartTable <- DT::renderDataTable({
  Server = FALSE
  # Whether to show row names (set TRUE or FALSE)
  rowNames <- FALSE
  colIdx <- as.integer(rowNames)
  # The data
  Dat <- market_mix_table()
  parentRows <- which(Dat[,1] != "")
  callback_js = JS(
    "var ok = true;",
    "function onUpdate(updatedCell, updatedRow, oldValue) {",
    "  var column = updatedCell.index().column;",
    "  if(column === 8){",
    "    ok = false;",
    "  }else if(column === 7){",
    "    ok = true;",
    "  }",
    "}",
    sprintf("var parentRows = [%s];", toString(parentRows-1)),
    sprintf("var j0 = %d;", colIdx),
    "var nrows = table.rows().count();",
    "for(var i=0; i < nrows; ++i){",
    "  if(parentRows.indexOf(i) > -1){",
    "    table.cell(i,j0).nodes().to$().css({cursor: 'pointer'});",
    "  }else{",
    "    table.cell(i,j0).nodes().to$().removeClass('details-control');",
    "  }",
    "}",
    "",
    "// make the table header of the nested table",
    "var format = function(d, childId){",
    "  if(d != null){",
    "    var html = ",
    "      '

';",
    "    for(var key in d[d.length-1][0]){",
    "      html += '' + key + '	';",
    "    }",
    "    html += '

'",
    "    for(var key in d[d.length-1][0]){",
    "      html += '	';",
    "    }",
    "    return html + '

';",
    "  } else {",
    "    return '';",
    "  }",
    "};",
    "",
    "// row callback to style the rows of the child tables",
    "var rowCallback = function(row, dat, displayNum, index){",
    "  if($(row).hasClass('odd')){",
    "    $(row).css('background-color', 'white');",
    "    $(row).hover(function(){",
    "      $(this).css('background-color', 'lightgreen');",
    "    }, function() {",
    "      $(this).css('background-color', 'white');",
    "    });",
    "  } else {",
    "    $(row).css('background-color', 'white');",
    "    $(row).hover(function(){",
    "      $(this).css('background-color', 'lightblue');",
    "    }, function() {",
    "      $(this).css('background-color', 'white');",
    "    });",
    "  }",
    "};",
    "",
    "// header callback to style the header of the child tables",
    "var headerCallback = function(thead, data, start, end, display){",
    "  $('th', thead).css({",
    "    'color': 'black',",
    "    'background-color': 'white'",
    "  });",
    "};",
    "",
    "// make the datatable",
    "var format_datatable = function(d, childId, rowIdx){",
    "  // footer callback to display the totals",
    "  // and update the parent row",
    "  var footerCallback = function(tfoot, data, start, end, display){",
    "    $('th', tfoot).css('background-color', '#F5F2F2');",
    "    var api = this.api();",
    "// update the Override CPM when the Override CPP is changed",
    "    var col_override_cpp = api.column(7).data();",
    "    var col_population = api.column(9).data();",
    "    if(ok){",
    "      for(var i = 0; i < col_override_cpp.length; i++){",
    "        api.cell(i,8).data(((parseInt(col_override_cpp[i])*100)/(parseInt(col_population[i])/1000)).toFixed(0));",
    "      }",
    "    }",
    "// update the Override CPP when the Override CPM is changed",
    "    var col_override_cpm = api.column(8).data();",
    "    for(var i = 0; i < col_override_cpm.length; i++){",
    "      api.cell(i,7).data(((parseInt(col_override_cpm[i])*parseInt(col_population[i])/1000)/(100)).toFixed(0));",
    "    }",
    "// Update the spot mixes",
    "    var col_mix_percentage = api.column(2).data();",
    "    var col_mix60_mix30 = api.column(10).data();",
    "    var col_mix30_mix15 = api.column(11).data();",
    "    for(var i = 0; i < col_mix_percentage.length; i++){",
    "      api.cell(i,3).data((parseFloat(col_mix_percentage[i])*parseFloat(col_mix60_mix30[i])).toFixed(1));",
    "      api.cell(i,4).data((parseFloat(col_mix_percentage[i])*parseFloat(col_mix30_mix15[i])).toFixed(1));",
    "    }",
    "// Make the footer sums",
    "    api.columns().eq(0).each(function(index){",
    "      if(index == 0) return $(api.column(index).footer()).html('Mix Total');",
    "      var coldata = api.column(index).data();",
    "      var total = coldata",
    "          .reduce(function(a, b){return parseInt(a) + parseInt(b)}, 0);",
    "      if(index == 3 || index == 4 ||index == 5 || index == 6 || index==7 || index==8) {",
    "        $(api.column(index).footer()).html('');",
    "      } else {",
    "        $(api.column(index).footer()).html(total);",
    "      }",
    "      if(total == 100) {",
    "        $(api.column(index).footer()).css({'color': 'green'});",
    "      } else {",
    "        $(api.column(index).footer()).css({'color': 'red'});",
    "      }",
    "    })",
    "  // update the parent row",
    "    var col_share = api.column(2).data();",
    "    var col_CPP = api.column(5).data();",
    "    var col_CPM = api.column(6).data();",
    "    var col_Historical_CPP = api.column(7).data();",
    "    var col_Historical_CPM = api.column(8).data();",
    "    var CPP = 0, CPM = 0, Historical_CPP = 0, Historical_CPM = 0;",
    "    for(var i = 0; i < col_share.length; i++){",
    "      CPP += (parseInt(col_share[i])*parseInt(col_CPP[i]).toFixed(0));",
    "      CPM += (parseInt(col_share[i])*parseInt(col_CPM[i]).toFixed(0));",
    "      Historical_CPP += (parseInt(col_share[i])*parseInt(col_Historical_CPP[i]).toFixed(0));",
    "      Historical_CPM += (parseInt(col_share[i])*parseInt(col_Historical_CPM[i]).toFixed(0));",
    "    }",
    "    table.cell(rowIdx, j0+2).data((CPP/100).toFixed(2));",
    "    table.cell(rowIdx, j0+3).data((CPM/100).toFixed(2));",
    "    table.cell(rowIdx, j0+4).data((Historical_CPP/100).toFixed(2));",
    "    table.cell(rowIdx, j0+5).data((Historical_CPM/100).toFixed(2));",
    "  }",
    "  var dataset = [];",
    "  var n = d.length - 1;",
    "  for(var i = 0; i < d[n].length; i++){",
    "    var datarow = $.map(d[n][i], function (value, index) {",
    "      return [value];",
    "    });",
    "    dataset.push(datarow);",
    "  }",
    "  var id = 'table#' + childId;",
    "  if (Object.keys(d[n][0]).indexOf('_details') === -1) {",
    "    var subtable = $(id).DataTable({",
    "                 'data': dataset,",
    "                 'autoWidth': true,",
    "                 'deferRender': true,",
    "                 'info': false,",
    "                 'lengthChange': false,",
    "                 'ordering': d[n].length > 1,",
    "                 'order': [],",
    "                 'paging': true,",
    "                 'scrollX': false,",
    "                 'scrollY': false,",
    "                 'searching': false,",
    "                 'sortClasses': false,",
    "                 'pageLength': 50,",
    "                 'rowCallback': rowCallback,",
    "                 'headerCallback': headerCallback,",
    "                 'footerCallback': footerCallback,",
    "                 'columnDefs': [",
    "                  {targets: [0, 9, 10, 11], visible: false},",
    "                  {targets: '_all', className: 'dt-center'}",
    "                 ]",
    "               });",
    "  } else {",
    "    var subtable = $(id).DataTable({",
    "            'data': dataset,",
    "            'autoWidth': true,",
    "            'deferRender': true,",
    "            'info': false,",
    "            'lengthChange': false,",
    "            'ordering': d[n].length > 1,",
    "            'order': [],",
    "            'paging': true,",
    "            'scrollX': false,",
    "            'scrollY': false,",
    "            'searching': false,",
    "            'sortClasses': false,",
    "            'pageLength': 50,",
    "            'rowCallback': rowCallback,",
    "            'headerCallback': headerCallback,",
    "            'footerCallback': footerCallback,",
    "            'columnDefs': [",
    "              {targets: [0, 9, 10, 11], visible: false},",
    "              {targets: -1, visible: false},",
    "              {targets: 0, orderable: false, className: 'details-control'},",
    "              {targets: '_all', className: 'dt-center'}",
    "             ]",
    "          }).column(0).nodes().to$().css({cursor: 'pointer'});",
    "  }",
    "  subtable.MakeCellsEditable({",
    "    onUpdate: onUpdate,",
    "    inputCss: 'my-input-class',",
    "    columns: [2, 7, 8],",
    "    confirmationButton: {",
    "      confirmCss: 'my-confirm-class',",
    "      cancelCss: 'my-cancel-class'",
    "    }",
    "  });",
    "};",
    "",
    "// display the child table on click",
    "var children = [];", # array to store the id's of the already created child tables
    "table.on('click', 'td.details-control', function(){",
    "  var tbl = $(this).closest('table'),",
    "      tblId = tbl.attr('id'),",
    "      td = $(this),",
    "      row = $(tbl).DataTable().row(td.closest('tr')),",
    "      rowIdx = row.index();",
    "  if(row.child.isShown()){",
    "    row.child.hide();",
    "    td.html('');",
    "  } else {",
    "    var childId = tblId + '-child-' + rowIdx;",
    "    if(children.indexOf(childId) === -1){", # this child table has not been created yet
    "      children.push(childId);",
    "      row.child(format(row.data(), childId)).show();",
    "    td.html('');",
    "      format_datatable(row.data(), childId, rowIdx);",
    "    }else{",
    "      row.child(true);",
    "    td.html('');",
    "    }",
    "  }",
    "});"
  )
  # Table
  table <- DT::datatable(
    Dat,
    callback = callback_js,
    rownames = rowNames,
    escape = -colIdx-1,
    style = "bootstrap4",
    extensions = 'Buttons',
      options = list(
        dom = "Blfrtip",
        buttons = list("copy",
                       list(
                          extend = "collection",
                          buttons = "csv",
                          text = "Download"
                          )
                      ),
        lengthMenu = list(c(-1, 10, 20),
                          c("All", 10, 20)),
        columnDefs = list(
          list(width = '30px', targets = 0),
          list(width = '545px', targets = 1),
          list(visible = FALSE, targets = ncol(Dat)-1+colIdx),
          list(orderable = FALSE, className = 'details-control', targets = colIdx),
          list(className = "dt-center", targets = "_all")
      )
    )
  )
  # Call the html tools deps (js & css files in this directory)
  cell_edit_dep <- htmltools::htmlDependency(
    "CellEdit", "1.0.19",
    src = 'www/',
    script = "dataTables.cellEdit.js",
    stylesheet = "dataTables.cellEdit.css"
  )
  table$dependencies <- c(table$dependencies, list(cell_edit_dep))

  table %>% formatStyle(
    c('Market', 'SQAD CPP ($)', 'SQAD CPM ($)', 'Override CPP ($)', 'Override CPM ($)'),
    target = 'row',
    backgroundColor = "#F5F2F2"
  )
})

A: Try this:
js <- c(
  "function(xlsx) {",
  "  var table = $('#daypartTable').find('table').DataTable();",
  "  // Letters for Excel columns.",
  "  var LETTERS = [",
  "    'A','B','C','D','E','F','G','H','I','J','K','L','M',",
  "    'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'",
  "  ];",
  "  // Get sheet.",
  "  var sheet = xlsx.xl.worksheets['sheet1.xml'];",
  "  // Get a clone of the sheet data.        ",
  "  var sheetData = $('sheetData', sheet).clone();",
  "  // Clear the current sheet data for appending rows.",
  "  $('sheetData', sheet).empty();",
  "  // Row count in Excel sheet.",
  "  var rowCount = 1;",
  "  // Iterate each row in the sheet data.",
  "  $(sheetData).children().each(function (index) {",
  "    // Used for DT row() API to get child data.",
  "    var rowIndex = index - 2;", #
  "    // Don't process row if its the header row.",
  sprintf("    if (index > 1 && index < %d) {", nrow(Dat)+2), #
  "      // Get row",
  "      var row = $(this.outerHTML);",
  "      // Set the Excel row attr to the current Excel row count.",
  "      row.attr('r', rowCount);",
  "      // Iterate each cell in the row to change the row number.",
  "      row.children().each(function (index) {",
  "        var cell = $(this);",
  "        // Set each cell's row value.",
  "        var rc = cell.attr('r');",
  "        rc = rc.replace(/\\d+$/, \"\") + rowCount;",
  "        cell.attr('r', rc);",
  "      });",
  "      // Get the row HTML and append to sheetData.",
  "      row = row[0].outerHTML;",
  "      $('sheetData', sheet).append(row);",
  "      rowCount++;",
  "      // Get the child data - could be any data attached to the row.",
  sprintf("      var childData = table.row(':eq(' + rowIndex + ')').data()[%d];", ncol(Dat)-1), #
  "      if (childData.length > 0) {",
  "        var colNames = Object.keys(childData[0]);",
  "        // Prepare Excel formatted row",
  "        headerRow = '<row r=\"' + rowCount +",
  "          '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
  "          '\"><is><t></t></is></c>';",
  "        for(var i = 0; i < colNames.length; i++){",
  "          headerRow = headerRow +",
  "            '<c t=\"inlineStr\" r=\"' + LETTERS[i+1] + rowCount +",
  "            '\" s=\"7\"><is><t>' + colNames[i] +",
  "            '</t></is></c>';",
  "        }",
  "        headerRow = headerRow + '</row>';",
  "        // Append header row to sheetData.",
  "        $('sheetData', sheet).append(headerRow);",
  "        rowCount++; // Inc excelt row counter.",
  "      }",
  "      // The child data is an array of rows",
  "      for (c = 0; c < childData.length; c++) {",
  "        // Get row data.",
  "        child = childData[c];",
  "        // Prepare Excel formatted row",
  "        var colNames = Object.keys(child);",
  "        childRow = '<row r=\"' + rowCount +",
  "          '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
  "          '\"><is><t></t></is></c>';",
  "        for(var i = 0; i < colNames.length; i++){",
  "          childRow = childRow +",
  "            '<c t=\"inlineStr\" r=\"' + LETTERS[i+1] + rowCount +",
  "            '\" s=\"5\"><is><t>' + child[colNames[i]] +",
  "            '</t></is></c>';",
  "        }",
  "        childRow = childRow + '</row>';",
  "        // Append row to sheetData.",
  "        $('sheetData', sheet).append(childRow);",
  "        rowCount++; // Inc excel row counter.",
  "      }",
  "      // Just append the header row and increment the excel row counter.",
  "    } else {",
  "      $('sheetData', sheet).append(this.outerHTML);",
  "      rowCount++;",
  "    }",
  "  });",
  "}"
)

datatable(
  Dat, callback = callback, rownames = rowNames, escape = -colIdx-1,
  extensions = "Buttons",
  options = list(
    dom = "Bfrtip",
    columnDefs = list(
      list(visible = FALSE, targets = ncol(Dat)-1+colIdx),
      list(orderable = FALSE, className = 'details-control', targets = colIdx),
      list(className = "dt-center", targets = "_all")
    ),
    buttons = list(
      list(
        extend = "excel",
        exportOptions = list(
          orthogonal = "export",
          columns = 0:(ncol(Dat)-2)
        ),
        orientation = "landscape",
        customize = JS(js)
      )
    )
  )
)

Here is an example of the generated Excel file:

EDIT
Better:
excelTitle <- NULL # set to NULL if you don't want a title
js <- c(
  "function(xlsx) {",
  "  var table = $('#daypartTable').find('table').DataTable();",
  "  // Number of columns.",
  "  var ncols = table.columns().count();",
  "  // Is there a title?",
  sprintf("  var title = %s;", ifelse(is.null(excelTitle), "false", "true")),
  "  // Integer to Excel column: 0 -> A, 1 -> B, ..., 25 -> Z, 26 -> AA, ...",
  "  var XLcolumn = function(j){", # https://codegolf.stackexchange.com/a/163919
  "    return j < 0 ? '' : XLcolumn(j/26-1) + String.fromCharCode(j % 26 + 65);",
  "  };",
  "  // Get sheet.",
  "  var sheet = xlsx.xl.worksheets['sheet1.xml'];",
  "  // Get a clone of the sheet data.        ",
  "  var sheetData = $('sheetData', sheet).clone();",
  "  // Clear the current sheet data for appending rows.",
  "  $('sheetData', sheet).empty();",
  "  // Row count in Excel sheet.",
  "  var rowCount = 1;",
  "  // Iterate each row in the sheet data.",
  "  $(sheetData).children().each(function (index) {",
  "    // Used for DT row() API to get child data.",
  "    var rowIndex = title ? index - 2 : index - 1;",
  "    // Don't process row if it's the title row or the header row.",
  "    var i0 = title ? 1 : 0;",
  "    if (index > i0) {",
  "      // Get row",
  "      var row = $(this.outerHTML);",
  "      // Set the Excel row attr to the current Excel row count.",
  "      row.attr('r', rowCount);",
  "      // Iterate each cell in the row to change the row number.",
  "      row.children().each(function (index) {",
  "        var cell = $(this);",
  "        // Set each cell's row value.",
  "        var rc = cell.attr('r');",
  "        rc = rc.replace(/\\d+$/, \"\") + rowCount;",
  "        cell.attr('r', rc);",
  "      });",
  "      // Get the row HTML and append to sheetData.",
  "      row = row[0].outerHTML;",
  "      $('sheetData', sheet).append(row);",
  "      rowCount++;",
  "      // Get the child data - could be any data attached to the row.",
  "      var childData = table.row(':eq(' + rowIndex + ')').data()[ncols-1];",
  "      if (childData.length > 0) {",
  "        var colNames = Object.keys(childData[0]);",
  "        // Prepare Excel formatted row",
  "        var headerRow = '<row r=\"' + rowCount +",
  "          '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
  "          '\"><is><t></t></is></c>';",
  "        for(let i = 0; i < colNames.length; i++){",
  "          headerRow = headerRow +",
  "            '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +",
  "            '\" s=\"7\"><is><t>' + colNames[i] +",
  "            '</t></is></c>';",
  "        }",
  "        headerRow = headerRow + '</row>';",
  "        // Append header row to sheetData.",
  "        $('sheetData', sheet).append(headerRow);",
  "        rowCount++; // Inc excel row counter.",
  "      }",
  "      // The child data is an array of rows",
  "      for(let c = 0; c < childData.length; c++){",
  "        // Get row data.",
  "        var child = childData[c];",
  "        // Prepare Excel formatted row",
  "        var childRow = '<row r=\"' + rowCount +",
  "          '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
  "          '\"><is><t></t></is></c>';",
  "        var i = 0;",
  "        for(let colname in child){",
  "          childRow = childRow +",
  "            '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +",
  "            '\" s=\"5\"><is><t>' + child[colname] +",
  "            '</t></is></c>';",
  "          i++;",
  "        }",
  "        childRow = childRow + '</row>';",
  "        // Append row to sheetData.",
  "        $('sheetData', sheet).append(childRow);",
  "        rowCount++; // Inc excel row counter.",
  "      }",
  "      // Just append the header row and increment the excel row counter.",
  "    } else {",
  "      $('sheetData', sheet).append(this.outerHTML);",
  "      rowCount++;",
  "    }",
  "  });",
  "}"
)

datatable(
  Dat, callback = callback, rownames = rowNames, escape = -colIdx-1,
  extensions = "Buttons",
  options = list(
    dom = "Bfrtip",
    columnDefs = list(
      list(visible = FALSE, targets = ncol(Dat)-1+colIdx),
      list(orderable = FALSE, className = 'details-control', targets = colIdx),
      list(className = "dt-center", targets = "_all")
    ),
    buttons = list(
      list(
        extend = "excel",
        exportOptions = list(
          orthogonal = "export",
          columns = 0:(ncol(Dat)-2)
        ),
        title = excelTitle,
        orientation = "landscape",
        customize = JS(js)
      )
    )
  )
)

EDIT 2
In callback_js, replace
"  var dataset = [];",
"  var n = d.length - 1;",
"  for(var i = 0; i < d[n].length; i++){",
"    var datarow = $.map(d[n][i], function (value, index) {",
"      return [value];",
"    });",
"    dataset.push(datarow);",
"  }",
"  var id = 'table#' + childId;",
"  if (Object.keys(d[n][0]).indexOf('_details') === -1) {",
"    var subtable = $(id).DataTable({",
"                 'data': dataset,",
"                 'autoWidth': true,",
"                 'deferRender': true,",
"                 'info': false,",
"                 'lengthChange': false,",
"                 'ordering': d[n].length > 1,",
"                 'order': [],",
"                 'paging': true,",
"                 'scrollX': false,",
"                 'scrollY': false,",
"                 'searching': false,",
"                 'sortClasses': false,",
"                 'pageLength': 50,",
"                 'rowCallback': rowCallback,",
"                 'headerCallback': headerCallback,",
"                 'footerCallback': footerCallback,",
"                 'columnDefs': [",
"                  {targets: [0, 9, 10, 11], visible: false},",
"                  {targets: '_all', className: 'dt-center'}",
"                 ]",
"               });",
"  } else {",
"    var subtable = $(id).DataTable({",
"            'data': dataset,",
"            'autoWidth': true,",
"            'deferRender': true,",
"            'info': false,",
"            'lengthChange': false,",
"            'ordering': d[n].length > 1,",
"            'order': [],",
"            'paging': true,",
"            'scrollX': false,",
"            'scrollY': false,",
"            'searching': false,",
"            'sortClasses': false,",
"            'pageLength': 50,",
"            'rowCallback': rowCallback,",
"            'headerCallback': headerCallback,",
"            'footerCallback': footerCallback,",
"            'columnDefs': [",
"              {targets: [0, 9, 10, 11], visible: false},",
"              {targets: -1, visible: false},",
"              {targets: 0, orderable: false, className: 'details-control'},",
"              {targets: '_all', className: 'dt-center'}",
"             ]",
"          }).column(0).nodes().to$().css({cursor: 'pointer'});",
"  }",

with
"  var n = d.length - 1;",
"  var id = 'table#' + childId;",
"  var columns = Object.keys(d[n][0]).map(function(x){",
"    return {data: x, title: x};",
"  });",
"  if (Object.keys(d[n][0]).indexOf('_details') === -1) {",
"    var subtable = $(id).DataTable({",
"                 'data': d[n],",
"                 'columns': columns,",
"                 'autoWidth': true,",
"                 'deferRender': true,",
"                 'info': false,",
"                 'lengthChange': false,",
"                 'ordering': d[n].length > 1,",
"                 'order': [],",
"                 'paging': true,",
"                 'scrollX': false,",
"                 'scrollY': false,",
"                 'searching': false,",
"                 'sortClasses': false,",
"                 'pageLength': 50,",
"                 'rowCallback': rowCallback,",
"                 'headerCallback': headerCallback,",
"                 'footerCallback': footerCallback,",
"                 'columnDefs': [",
"                  {targets: [0, 9, 10, 11], visible: false},",
"                  {targets: '_all', className: 'dt-center'}",
"                 ]",
"               });",
"  } else {",
"    var subtable = $(id).DataTable({",
"            'data': d[n],",
"            'columns': columns,",
"            'autoWidth': true,",
"            'deferRender': true,",
"            'info': false,",
"            'lengthChange': false,",
"            'ordering': d[n].length > 1,",
"            'order': [],",
"            'paging': true,",
"            'scrollX': false,",
"            'scrollY': false,",
"            'searching': false,",
"            'sortClasses': false,",
"            'pageLength': 50,",
"            'rowCallback': rowCallback,",
"            'headerCallback': headerCallback,",
"            'footerCallback': footerCallback,",
"            'columnDefs': [",
"              {targets: [0, 9, 10, 11], visible: false},",
"              {targets: -1, visible: false},",
"              {targets: 0, orderable: false, className: 'details-control'},",
"              {targets: '_all', className: 'dt-center'}",
"             ]",
"          }).column(0).nodes().to$().css({cursor: 'pointer'});",
"  }",

Moreover, you probably don't want the hidden columns in the Excel file. So replace this code:
  "      if (childData.length > 0) {",
  "        var colNames = Object.keys(childData[0]);",
  "        // Prepare Excel formatted row",
  ......
  "        // Append row to sheetData.",
  "        $('sheetData', sheet).append(childRow);",
  "        rowCount++; // Inc excel row counter.",
  "      }",

with
  "      if (childData.length > 0) {",
  "        var colNames = Object.keys(childData[0]).slice(1,9);",
  "        // Prepare Excel formatted row",
  "        var headerRow = '<row r=\"' + rowCount +",
  "          '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
  "          '\"><is><t></t></is></c>';",
  "        for(let i = 0; i < colNames.length; i++){",
  "          headerRow = headerRow +",
  "            '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +",
  "            '\" s=\"7\"><is><t>' + colNames[i] +",
  "            '</t></is></c>';",
  "        }",
  "        headerRow = headerRow + '</row>';",
  "        // Append header row to sheetData.",
  "        $('sheetData', sheet).append(headerRow);",
  "        rowCount++; // Inc excel row counter.",
  "      }",
  "      // The child data is an array of rows",
  "      for(let c = 0; c < childData.length; c++){",
  "        // Get row data.",
  "        var child = childData[c];",
  "        // Prepare Excel formatted row",
  "        var childRow = '<row r=\"' + rowCount +",
  "          '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
  "          '\"><is><t></t></is></c>';",
  "        for(let i = 0; i < colNames.length; i++){",
  "          childRow = childRow +",
  "            '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +",
  "            '\" s=\"5\"><is><t>' + child[colNames[i]] +",
  "            '</t></is></c>';",
  "        }",
  "        childRow = childRow + '</row>';",
  "        // Append row to sheetData.",
  "        $('sheetData', sheet).append(childRow);",
  "        rowCount++; // Inc excel row counter.",
  "      }",

EDIT 3
This doesn't work if there are some periods in the column names of a child table. Here is the fix:
  "  var columns = Object.keys(d[n][0]).map(function(x){",
  "    return {data: x.replace('.', '\\\\\\.'), title: x};",
  "  });",


Q: conditional drop-down list on row cluster values I have the following table:

Is there a way to have dynamic drop-down list including all values from only same cluster (example of possible values in Link list column)? Cluster column is big so I am looking for dynamic solution.

A: So you can do this with formulas, but it's a bit involved. Bottom line is that here is the result I came up with:

The drop-down was created dynamically using dynamic named ranges and formulas
We need to start out with some definitions. This is my test worksheet and data:

The formulas will work out using the named ranges, so you can put your "working area" (the boxed area in green) almost anywhere, including on a different (possibly hidden) worksheet.
You must define four, dynamic named ranges as follows, which match the color-shaded areas in the image above:

Many of these formulas are array formulas, so you must be careful to enter them with CTRL+SHIFT+ENTER.
Once your data areas and names are defined, the first area to populate is the UniqueClusterList (the range on the sheet is F2:M2). We're building a list of unique items, based on the data in your column of cluster values. So you need an array formula that identifies all the unique values in the range. In each cell in the range, enter the array formula CTRL+SHIFT+ENTER for each:
Cell F2    =IFERROR(LOOKUP(2,1/(COUNTIF($E$2:E2,ClusterList)=0),ClusterList),"")
Cell G2    =IFERROR(LOOKUP(2,1/(COUNTIF($E$2:F2,ClusterList)=0),ClusterList),"")
Cell H2    =IFERROR(LOOKUP(2,1/(COUNTIF($E$2:G2,ClusterList)=0),ClusterList),"")
Cell I2    =IFERROR(LOOKUP(2,1/(COUNTIF($E$2:H2,ClusterList)=0),ClusterList),"")

... and so on. Notice that only the cell address in the middle is changing.
Next, we need to build up the list of IDs for each unique Cluster value. This is also an array formula. Starting in cell F3 with CTRL+SHIFT+ENTER:
=IFERROR(INDEX(IDList, SMALL(IF(F$2=ClusterList, ROW(IDList)-2,""), ROW()-2)),"")

Then use your cursor to grab the auto-fill icon in the selection box of that cell and drag it down to cell F16. Since cells F3:F16 are now selected, re-grab the auto-fill icon and drag to the right to fill the whole range F2:M16. All of the values should pop-in as calculated by the formulas.
Your final step is to create the lookup formula for the drop-down list. So select cell C3, then on the ribbon click Data --> Data Tools --> Data Validation to get the dialog window. Now select Allow: List, and in the Source: field enter the following formula:
 =OFFSET($F$2,1,MATCH(A3,UniqueClusterList,0)-1,SUMPRODUCT(COUNTIF(IDList,OFFSET($F$2,0,MATCH(A3,UniqueClusterList,0)-1,MAXUNIQUE,1))),1)

You'll now have a drop-down in cell C3 that matches the very first image above. Drag the auto-fill selection icon all the way down to cell C20 and all of those cells will correctly calculate the drop-down list based on the available Clusters and IDs.


Q: QTabWidget inside a QSplitter switching very slow I'm new to Qt, and wanted to implement some dialogs for a program.
The GUI of the dialog is simple: there's a tree on the left, and some tabs on the right (the number of tabs may change), and there are some widgets for input in each tab.
But when I implemented this dialog with Qt5.0.2, I found it is very slow when I switch tabs. (usually more than 0.1s to switch a tab, sometimes it stopped to response for several seconds if I randomly click on the tabs for many times)
I'm wondering if I was using Qt in a wrong way, or if there is something I can do to improve the performance
Here is an example for my scenario:
    TestQT::TestQT(QWidget *parent)
    : QMainWindow(parent)
{

    QSplitter* pSplitter = new QSplitter();
    QTreeWidget* pTree = new QTreeWidget();

    pSplitter->addWidget(pTree);

    QTabWidget* pTabs = new QTabWidget();

    for (int i = 0; i < 10; i++)
    {
        QWidget* pPage = new QWidget();
        QVBoxLayout* pLayout = new QVBoxLayout();
        for (int j = 0; j < 20; j++)
        {
            QHBoxLayout* pLineLayout = new QHBoxLayout();
            pLineLayout->addWidget(new QCheckBox());
            pLineLayout->addWidget(new QLineEdit());
            pLayout->addLayout(pLineLayout);
        }
        pPage->setLayout(pLayout);

        pTabs->addTab(pPage, tr("Page%1").arg(i));
    }

    pSplitter->addWidget(pTabs);

    this->setCentralWidget(pSplitter);
}

A: I agree with Kuba. Mostly GUI malfunctions are occurred when another action is blocking the thread it is running on, so your solution in these cases is to either move the GUI or that action to another thread.
Since I only see the code for GUI here, let's try moving the GUI to another thread first. With the header QThread, add these codes to your function and see if it helps:
QThread * t1 = new QThread();
this->moveToThread(t1);
t1->start();


Q: Express app - Change base url I'm building a Q&A app following this tutorial and everything goes well, but I need to change the chance to change the base root where the app is being served via config files.
Now the app is served in localhost:8080 and I need to be served over localhost:8080/qae (for example).
I think the answer is near this piece of code:
// Setup server
var app = express();
var server = http.createServer(app);
var socketio = require('socket.io')(server, {
  serveClient: config.env !== 'production',
  path: '/socket.io-client'
});
require('./config/socketio')(socketio);
require('./config/express')(app);
require('./routes')(app);

// Start server
function startServer() {
  app.angularFullstack = server.listen(config.port, config.ip, function() {
    console.log('Express server listening on %d, in %s mode '+config.ip, config.port, app.get('env'));
  });
}

setImmediate(startServer);

(from /server/app.js)
But I can't figure it. Is it possible doing this in a simple way?
////////EDIT////////
I tried all the proposed solutions, but I'm doing something wrong and got errors. This is my routes.js in case it helps:
/**
 * Main application routes
 */

'use strict';

import errors from './components/errors';
import path from 'path';

export default function(app) {
  // Insert routes below
  app.use('/api/cpd', require('./api/cpd'));
  app.use('/api/categories', require('./api/category'));
  app.use('/api/terms', require('./api/term'));
  app.use('/api/qae', require('./api/qae'));
  app.use('/api/stats', require('./api/stat'));
  app.use('/api/tags', require('./api/tag'));
  app.use('/api/questions', require('./api/question'));
  app.use('/api/things', require('./api/thing'));
  app.use('/api/users', require('./api/user'));

  app.use('/auth', require('./auth'));

  app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });

  // All undefined asset or api routes should return a 404
  app.route('/:url(api|auth|components|app|bower_components|assets)/*')
   .get(errors[404]);

  // All other routes should redirect to the index.html
  app.route('/*')
    .get((req, res) => {
      res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
    });
}

A: You can do the following:
var app = express();
var routes = require('./routes/index');
app.set('base', '/qae');

then you need to add route
app.use('/qae', routes);

Hope this helps :)

A: You should change your rooting to this:
app.use('/qae',require('./routes'))

and in routes/index.js you can have all declarations of your routes.
In routes.js
export default function(app) {
    // Insert routes below
    app.use('/qae', require('./api'));

    app.use('/auth', require('./auth'));

    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });

    // All undefined asset or api routes should return a 404
    app.route('/:url(api|auth|components|app|bower_components|assets)/*')
    .get(errors[404]);

    // All other routes should redirect to the index.html
    app.route('/*')
      .get((req, res) => {
        res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
      });
}

create file index.js in api
const express = require('express')
const router = express.Router()

router.use('/api/cpd', require('./cpd'));
router.use('/api/categories', require('./category'));
router.use('/api/terms', require('./term'));
router.use('/api/qae', require('./qae'));
router.use('/api/stats', require('./stat'));
router.use('/api/tags', require('./tag'));
router.use('/api/questions', require('./question'));
router.use('/api/things', require('./thing'));
router.use('/api/users', require('./user'));

module.exports = router

That way all your api routes will look like /qae/api/*. If you need auth also after this prefix you need to do it same way.
Best solution is to have i app.use('/',...) including routers from subfolders.

A: If your ./routes module returned a router instead of taking an app object, then you could do this to make it available in / route:
app.use(require('./routes'));

or this to use /qae prefix:
app.use('/qae', require('./routes'));

but since you pass the app object to the function exported by ./routes then it is the ./routes module that actually registers the routes and since you didn't include its code it's hard to give you a specific example. I can only say that you will need to change the routes definitions in ./routes for a different prefix, and you'd need to return a router instead of taking app argument for the above examples to work.
Tthen you ./routes would have to look like this:
let express = require('express');
let router = express.Router();

router.get('/xxx', (req, res) => {
    // ...
});
router.get('/yyy', (req, res) => {
    // ...
});
module.exports = router;

and only then you'll be able to use:
app.use('/qae', require('./routes'));

in the main code.

A: Folder Structure
bin/
  www
server/
  routes/
    index.js
    book.js
  views/
    index.ejs
  app.js
  router.js
  error.js
public/
package.json

app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

require('./router')(app);
require('./errors')(app);

module.exports = app;

route.js
var index = require('./routes/index');
var books = require('./routes/books');

var base = '/api';

module.exports = function (app) {
    app.use(base+'/', index);
    app.use(base+'/books', books);
};

error.js
module.exports = function (app) {
    app.use(function (req, res, next) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    });

// development error handler
// will print stacktrace
    if (app.get('env') === 'development') {
        app.use(function (err, req, res, next) {
            res.status(err.status || 500);
            res.render('error', {
                message: err.message,
                error: err
            });
        });
    }
// production error handler
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: {}
        });
    });
};

index.js
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;


Q: How to get the tool id for eclipse headless build Eclipse has a headless build option and in the documentation they say we can add or replace tool options

Replace a tool option value:           -T          {toolid} {optionid=value}
Append to a tool option value:         -Ta         {toolid} {optionid=value}
Prepend to a tool option value:        -Tp         {toolid} {optionid=value}
Remove a tool option:                  -Tr         {toolid} {optionid=value}

How would someone find the {toolid} value for a build option?
I would like to change the command line arguments for this command
arm-none-eabi-objcopy -O ihex "KTV_Rear.elf"  "KTV_Rear.hex"

to
arm-none-eabi-objcopy -O binary "KTV_Rear.elf"  "KTV_Rear.bin"

I have not been able to find any documentation on how to get the tool id to pass to the -T command. Any help would be appreciated.
==================== UPDATE ========================

I tried to figure out what the tool ids were in the way that HighCommander4 suggested. Searching for "tool id" in the project gives
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler.1172133377" name="GNU ARM Cross C++ Compiler" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker.707543027" name="GNU ARM Cross C++ Linker" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker">
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver.1908892168" name="GNU ARM Cross Archiver" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting.1903643389" name="GNU ARM Cross Create Listing" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting">
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler.270131667" name="GNU ARM Cross C++ Compiler" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker.1091026714" name="GNU ARM Cross C++ Linker" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker">
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver.1404415533" name="GNU ARM Cross Archiver" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting.292770688" name="GNU ARM Cross Create Listing" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting">

The output of the build window for the command I need to modify is
Invoking: GNU ARM Cross Create Flash Image
arm-none-eabi-objcopy -O ihex "KTV_Rear.elf"  "KTV_Rear.hex"

It does not seem obvious which one of the tool ids might relate to arm-none-eabi-objcopy. I tried using the string for the tool id for the archiver with no luck.
I found this link that seems related

A: At the .cproject file you can find the tool id (use the superClass field, without the number) and for each tool you can find a list of options ids. At the invocation line you need to specify the tool id, the option id and the value for the option, like in the following example (adding my_lib_location to the libraries search path):
-Tp cdt.managedbuild.tool.gnu.c.linker.exe.release gnu.c.link.option.paths=my_lib_location


Q: Better way to manage Database class for common operations Our company work on multiple Windows Services and EXEs (more than 30). Each of the service/exe have one database class which have connection details and respective SQL queries.
Now, whenever some change come, our team need to maintain all the projects, which takes a lot of programmer's time and efforts. Also seems inappropriate.
I was wondering if there was a better architecture to manage such kind of structure. So that it can save programmer's time and repetitive effort.

What I have think is that to maintain a common DLL, which will have
  all the connection detail and SQL queries. Maintaining this structure
  using inheritance will save a lot of repetitive effort.

Is there any better way to manage this? What are your opinions?


Q: Adjust the image as per screen resolution of window I have add a JLabel in a JFrame
and one image of size 1024x768 is added in JLabel.
When I set the resolution of window screen in 1024x768 the and run the application the image is shown in full window.  But when I set the resolution of window screen in 1280x768 - the image is shown in only one third portion of window.
How can I adjust or add the image of size 1024x768 so that in any screen resolution the image will show covering the full window?  In other words the image is adjusted as per the screen resolution of window.

A:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.net.URL;
import javax.imageio.ImageIO;

class ImagePanel extends JPanel {

    Image image;

    ImagePanel(Image image) {
        this.image = image;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image,0,0,getWidth(),getHeight(),this);
    }

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://pscode.org/media/stromlo2.jpg");
        final Image image = ImageIO.read(url);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame f = new JFrame("Image");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setLocationByPlatform(true);

                ImagePanel imagePanel = new ImagePanel(image);
                imagePanel.setLayout(new GridLayout(5,10,10,10));
                imagePanel.setBorder(new EmptyBorder(20,20,20,20));
                for (int ii=1; ii<51; ii++) {
                    imagePanel.add(new JButton("" + ii));
                }

                f.setContentPane(imagePanel);
                f.pack();
                f.setVisible(true);
            }
        });
    }
}

Raw image used

A: I have faced this problem several times while i was adding image to the JFrame. Either the image size would be small or the JFrame size was small.
Here is a great site wherein you can resize your images according to the JFrame without distorting the image.
You can visit this website Go to the site
I have explained and showed how to make use of photo editor that the website provides to resize the image.
Go to my video tutorial  Go to the Video Session


Q: Status of statement (void)f() in C++14, is it ill-formed? if not, is the f() part discard-value? Is the following program ill-formed according to the C++14 standard?
int f() { return 42; }

int main() {
  (void)f();
}

If not, is the sole function call expression contained within a discard-value expression?  (note that is the subexpression, not the whole expression statement)

A:
Is the following program ill-formed according to the C++14 standard?

No. If you have some specific reason for thinking this might be invalid, you might be able to get a more detailed answer, but quoting each and every sentence of the standard in an attempt to point out that that sentence doesn't render the program invalid is not productive.

If not, is the sole function call expression contained within a discard-value expression?

The sole function call expression is the discarded-value expression.

5.2.9 Static cast [expr.static.cast]
6 Any expression can be explicitly converted to type cv void, in which case it becomes a discarded-value expression (Clause 5). [...]

I am assuming you are already aware that a C-style cast performs a static_cast if possible.


Q: C# value type with dynamic number of fields The best way to explain my problem is with a code snippet:
enum Resource { ..., Size }
class ResourceVector
{
    int[] values = new int[(int)Resource.Size];

    public static ResourceVector operator + (ResourceVector a, ResourceVector b)
    {...}

    ...
}

We are using this type everywhere as though it were a value type.  I.e. we are making the assumption that:
ResourceVector b = a;
b += c;

will not affect a, because that is how we are used to talking about vectors (and that is how a vector with a fixed number of fields does behave, if implemented as a struct).
However since that assumption is wrong, it has led to some extremely subtle bugs.
I am wondering if there is a way to make this behave as a value type, other than just expanding the members of Resource each into their own members in a struct ResourceVector (which requires touching every member of ResourceVector if we wish to add another Resource).
Oh, just in case, we are working with C# 2.0.  So no fancy-pants features :-)
Thanks.

A: I think you are confusing “value type” with “immutable type”. You actually want your ResourceVector to be an immutable type.
An immutable type is one that has no way to change its contents. Once constructed, an instance retains its value until it is garbage-collected. All operations such as addition return a new instance containing the result instead of modifying an existing instance.
string is the most well-known immutable class. All operations like Substring and Replace return a new string and don’t modify the existing strings.
Once your type is properly immutable, semantically it doesn’t matter so much anymore whether it is a value type or a reference type — but it matters to the performance. If you pass values around a lot, you should probably make it a reference type in order to avoid a lot of unnecessary copying.


Q: Migration wont recognize hstore extension created on schema_search_path I´m trying to add a column using postgresql HStore.
Since I´m running a multi tenant app (using apartment gem), I´ve created the hstore extension on a dedicated schema, called "shared_extensions", as seen here: [https://github.com/influitive/apartment#installing-extensions-into-persistent-schemas][1]
I also added the shared_extensions schema to database.yml as:
default: &default
  adapter: postgresql
  encoding: unicode
  pool: 5
  schema_search_path: "public,shared_extensions"

However, when I try to run rake db:migrate to add hstore column, I´m still receiving the error:
ActiveRecord::StatementInvalid: PG::UndefinedObject: ERROR:  type "hstore" does not exist

This is the hstore migration code:
class AddAdditionalInformationsToParties < ActiveRecord::Migration
  def change
    add_column :parties, :additional_informations, :hstore
  end
end

I´m not sure, but it looks like migrations are not recognizing the schema_search_path on database.yml file.

A: You need to enable the hstore extension in postgres.
Try running rails g migration add_hstore_extension, then edit it like below:

class AddHstoreExtension < ActiveRecord::Migration
  def self.up
    enable_extension "hstore"
  end
  def self.down
    disable_extension "hstore"
  end
end

Note that you'll need that to run before the migration which uses it.

A: I ended up adding the extension to pg_catalog, which is always implicitly on search_path, as described by Craig Ringer in this post:
Create HSTORE with multiple schemas
CREATE EXTENSION hstore WITH SCHEMA pg_catalog;


Q: Prometheus query filter not working for OR filter Is there any issue with the below query?
kube_resourcequota{resource="count/deployments.apps",type="hard",namespace="test1|test2"}

It works if I pass just one namespace.
kube_resourcequota{resource="count/deployments.apps",type="hard",namespace="test1"}

Sum also works without passing anything.
sum(kube_resourcequota{resource="count/deployments.apps",type="hard"})

A: The instant vector selector can be expressed as

*

*namespace="test1" to match label namespace exactly equal to "test1"

*<no selector on namestapce> to match all values of namespace

*namespace=~"test1|test2" to match label namespace with given regex

You made a mistake: you used a regex "test1[test2" with an exact match (=) instead of regex match (=~).
Correct expression would be:
kube_resourcequota{resource="count/deployments.apps",type="hard",namespace=~"test1|test2"}