Q: Reinitializing datatable and individual filter columns I need to initialize a Datatable and load data when a button is clicked. It works but it's creating a duplicate header under the filter columns. I have tried to destroy the Datatable but still no luck.. Hope someone can help.
I tried checking if the datatable exists then destroying the DT with the following: Also added destroy:true;
var table = $('#kt_table_1').DataTable().clear().destroy();
$('#kt_table_1 tbody').empty();
$('#kt_table_1 thead th').empty();
$("thead", table).remove();
$("thead .filter", table).empty();

var KTDatatablesSearchOptionsColumnSearch = function() {

  $.fn.dataTable.Api.register('column().title()', function() {
    return $(this.header()).text().trim();
  });

  var initTable1 = function() {

    if ($.fn.dataTable.isDataTable('#kt_table_1')) {
      console.log("yes exists");
    }

    // begin first table
    var table = $('#kt_table_1').DataTable({

      responsive: true,
      select: {
        style: 'multi',
        selector: 'td:first-child .kt-checkable',
      },

      headerCallback: function(thead, data, start, end, display) {
        thead.getElementsByTagName('th')[0].innerHTML = `

                 <input type="checkbox" value="" class="kt-group-checkable">

                 `;
      },

      buttons: [
        'print',
        'copyHtml5',
        'excelHtml5',
        'csvHtml5',
        'pdfHtml5',
      ],

      // Pagination settings
      dom: `<'row'<'col-sm-12'tr>>
                <'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>`,
      // read more: https://datatables.net/examples/basic_init/dom.html

      lengthMenu: [5, 10, 25, 50],

      pageLength: 10,

      language: {
        'lengthMenu': 'Display _MENU_',
      },

      searchDelay: 500,
      processing: true,
      serverSide: true,
      destroy: true,
      ajax: {
        url: './demo2/contents/encargos/server.php',
        type: 'POST',
        data: {
          // parameters for custom backend script demo
          columnsDef: [
            'RecordID', 'OrderID', 'Country', 'ShipCity', 'CompanyAgent', 'ShipDate', 'Status', 'Type', 'Actions', 'url'
          ],
        },
      },
      columns: [{
          data: 'RecordID'
        },
        {
          data: 'OrderID'
        },
        {
          data: 'Country'
        },
        {
          data: 'ShipCity'
        },
        {
          data: 'CompanyAgent'
        },
        {
          data: 'ShipDate'
        },
        {
          data: 'Status'
        },
        {
          data: 'Type'
        },
        {
          data: 'Actions',
          responsivePriority: -1
        },
      ],

      initComplete: function() {

        var thisTable = this;

        var rowFilter = $('

').appendTo($(table.table().header()));

        this.api().columns().every(function() {

          var column = this;
          var input;

          switch (column.title()) {
            case 'Record ID':
            case 'Order ID':
            case 'Ship City':
            case 'Company Agent':
              input = $(`<input type="text" class="form-control form-control-sm form-filter kt-input" data-col-index="` + column.index() + `"/>`);
              break;

            case 'Country':
              input = $(`<select class="form-control form-control-sm form-filter kt-input" title="Select" data-col-index="` + column.index() + `">
                <option value="">Select</option></select>`);
              column.data().unique().sort().each(function(d, j) {
                $(input).append('<option value="' + d + '">' + d + '</option>');
              });
              break;

            case 'Status':
              var status = {
                1: {
                  'title': 'Pending',
                  'class': 'kt-badge--brand'
                },
                2: {
                  'title': 'Delivered',
                  'class': ' kt-badge--danger'
                },
                3: {
                  'title': 'Canceled',
                  'class': ' kt-badge--primary'
                },
                4: {
                  'title': 'Success',
                  'class': ' kt-badge--success'
                },
                5: {
                  'title': 'Info',
                  'class': ' kt-badge--info'
                },
                6: {
                  'title': 'Danger',
                  'class': ' kt-badge--danger'
                },
                7: {
                  'title': 'Warning',
                  'class': ' kt-badge--warning'
                },
              };
              input = $(`<select class="form-control form-control-sm form-filter kt-input" title="Select" data-col-index="` + column.index() + `">
                <option value="">Select</option></select>`);
              column.data().unique().sort().each(function(d, j) {
                $(input).append('<option value="' + d + '">' + status[d].title + '</option>');
              });
              break;

            case 'Type':
              var status = {
                1: {
                  'title': 'Online',
                  'state': 'danger'
                },
                2: {
                  'title': 'Retail',
                  'state': 'primary'
                },
                3: {
                  'title': 'Direct',
                  'state': 'success'
                },
              };
              input = $(`<select class="form-control form-control-sm form-filter kt-input" title="Select" data-col-index="` + column.index() + `">
                <option value="">Select</option></select>`);
              column.data().unique().sort().each(function(d, j) {
                $(input).append('<option value="' + d + '">' + status[d].title + '</option>');
              });
              break;

            case 'Ship Date':
              input = $(`

                <input type="text" class="form-control form-control-sm kt-input" readonly placeholder="From" data-date-format="dd-mm-yyyy" id="kt_datepicker_1"
                 data-col-index="` + column.index() + `"/>

                <input type="text" class="form-control form-control-sm kt-input" readonly placeholder="To" data-date-format="dd-mm-yyyy" id="kt_datepicker_2"
                 data-col-index="` + column.index() + `"/>

`);
              break;

            case 'Actions':
              var search = $(`<button class="btn btn-brand kt-btn btn-sm kt-btn--icon">

                 Search

                </button>`);

              var reset = $(`<button class="btn btn-secondary kt-btn btn-sm kt-btn--icon">

                 Reset

                </button>`);

              $('').append(search).append(reset).appendTo(rowFilter);

              $(search).on('click', function(e) {
                e.preventDefault();
                var params = {};
                $(rowFilter).find('.kt-input').each(function() {
                  var i = $(this).data('col-index');
                  if (params[i]) {
                    params[i] += '|' + $(this).val();
                  } else {
                    params[i] = $(this).val();
                  }
                });
                $.each(params, function(i, val) {
                  // apply search params to datatable
                  table.column(i).search(val ? val : '', false, false);
                });
                table.table().draw();
              });

              $(reset).on('click', function(e) {
                e.preventDefault();
                $(rowFilter).find('.kt-input').each(function(i) {
                  $(this).val('');
                  table.column($(this).data('col-index')).search('', false, false);
                });
                table.table().draw();
              });
              break;
          }

          if (column.title() !== 'Actions') {
            $(input).appendTo($('').appendTo(rowFilter));
          }

        });

        // hide search column for responsive table
        var hideSearchColumnResponsive = function() {
          thisTable.api().columns().every(function() {
            var column = this
            if (column.responsiveHidden()) {
              $(rowFilter).find('th').eq(column.index()).show();
            } else {
              $(rowFilter).find('th').eq(column.index()).hide();
            }
          })
        };

        // init on datatable load
        hideSearchColumnResponsive();
        // recheck on window resize
        window.onresize = hideSearchColumnResponsive;

        $('#kt_datepicker_1,#kt_datepicker_2').datepicker({
          autoclose: true
        });
      },
      columnDefs: [{
          targets: 0,
          orderable: false,
          render: function(data, type, full, meta) {

            return '<input type="checkbox" value="' + data + '" class="kt-checkable">';

          },
        },
        {
          targets: -1,
          title: 'Actions',
          orderable: false,
          render: function(data, type, full, meta) {

            console.log(full);

            var id = full['RecordID'];
            var url = full['url'];

            return `

                 <a class="dropdown-item" href="` + url + `/edit.php"> Edit Details
                  Update Status
                  Generate Report

                 `;
          },
        },
        {
          targets: 5,
          width: '150px',
        },
        {
          targets: 6,
          render: function(data, type, full, meta) {
            var status = {
              1: {
                'title': 'Pending',
                'class': 'kt-badge--brand'
              },
              2: {
                'title': 'Delivered',
                'class': ' kt-badge--danger'
              },
              3: {
                'title': 'Canceled',
                'class': ' kt-badge--primary'
              },
              4: {
                'title': 'Success',
                'class': ' kt-badge--success'
              },
              5: {
                'title': 'Info',
                'class': ' kt-badge--info'
              },
              6: {
                'title': 'Danger',
                'class': ' kt-badge--danger'
              },
              7: {
                'title': 'Warning',
                'class': ' kt-badge--warning'
              },
            };
            if (typeof status[data] === 'undefined') {
              return data;
            }
            return '' + status[data].title + '';
          },
        },
        {
          targets: 7,
          render: function(data, type, full, meta) {
            var status = {
              1: {
                'title': 'Online',
                'state': 'danger'
              },
              2: {
                'title': 'Retail',
                'state': 'primary'
              },
              3: {
                'title': 'Direct',
                'state': 'success'
              },
            };
            if (typeof status[data] === 'undefined') {
              return data;
            }
            return ' ' +
              '' + status[data].title + '';
          },
        },
        {
          targets: 8,
          orderable: false,
        },
      ],
    });

    table.on('change', '.kt-group-checkable', function() {
      var set = $(this).closest('table').find('td:first-child .kt-checkable');
      var checked = $(this).is(':checked');

      $(set).each(function() {
        if (checked) {
          $(this).prop('checked', true);
          table.rows($(this).closest('tr')).select();
        } else {
          $(this).prop('checked', false);
          table.rows($(this).closest('tr')).deselect();
        }
      });
    });

    $('#export_print').on('click', function(e) {
      e.preventDefault();
      table.button(0).trigger();
    });

    $('#export_copy').on('click', function(e) {
      e.preventDefault();
      table.button(1).trigger();
    });

    $('#export_excel').on('click', function(e) {
      e.preventDefault();
      table.button(2).trigger();
    });

    $('#export_csv').on('click', function(e) {
      e.preventDefault();
      table.button(3).trigger();
    });

    $('#export_pdf').on('click', function(e) {
      e.preventDefault();
      table.button(4).trigger();
    });

    $('#action_delete').on('click', function(e) {

      e.preventDefault();

      var count = table.rows({
        selected: true
      }).count();

      if (count > 0) { // at-least one checkbox checked

        var ids = [];

        $('.kt-checkable').each(function() {

          if ($(this).is(':checked')) {
            ids.push($(this).val());
          }

        });

        var ids_string = ids.toString(); // array to string conversion

        if (confirm("Eliminar " + ids_string + " ?")) {

          $.ajax({
            type: "POST",
            url: "./demo2/modules/production/encargos/delete_group.php",
            data: {
              data_ids: ids_string
            },
            dataType: "json",
            success: function(result) {
              console.log(result);
              table.ajax.reload();
              NotifyPage('Eliminado correctamente', 'danger');
            },
            async: false
          });

        }

      }

    });

  };

  return {

    //main function to initiate the module
    init: function() {
      initTable1();
    },

  };

}();

jQuery(document).ready(function() {
  KTDatatablesSearchOptionsColumnSearch.init();
});


Q: Input type file in Chrome will not popup when served via https File input boxes aren't working in Chrome for me, I have reduced this down to pretty much just a single input box, and it still doesn't work.  Works in IE and FireFox, and Edge.  What can I do to get this to work?  Using version 88.0.4324.190.  It works in Chrome if I just get the file from the file system or via IIS and a http connection, but it doesn't work if the connection is https, despite there being no certificate problems.
<!DOCTYPE html>
<html>
<head>
    <title>
        Input type file not working
    </title>
</head>
<body>
    <form name="aspnetForm" method="post" action="./test.aspx" id="aspnetForm" enctype="multipart/form-data">
        <input type="file" name="atest" id="atestid" />
    </form>
</body>
</html>


Q: Javascript cant find my function in a promise I want to debug a function that returns a promise and for that I need a sleep function. I found this one:
function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

and it works when used outside of a promise. However when I want to use it in a promise, I get the error, that sleep was not found. This is my code:
async function f(filename) {
  return new Promise((resolve, reject) => {
    await sleep(1000);

    /*
      rest of function
    */
  });
}

A: Try to replace return new Promise((resolve, reject) => {}) in function f with return new Promise(async(resolve, reject) => {}). I hope it will solve your problem
async function f(filename) {
  return new Promise(async (resolve, reject) => {
    await sleep(1000);

    /*
      rest of function
    */
  });
}

A:
However when I want to use it in a promise

You should never create another promise inside the new Promise executor. Instead, call the sleep function inside the surrounding function f (which you already marked as async, presumably to use the await keyword):
async function f(filename) {
  await sleep(1000);
  return new Promise((resolve, reject) => {
    /* rest of function  */
  });
}

Your problem was also that the (resolve, reject) => {…} function is not async, so trying to use await inside there was a syntax error (in strict mode) and might also have caused the error message about the unexpected sleep token after the await.

A: Hi try using below code add async in the return code because you are using await inside the return
function sleep(ms) {
    return new Promise((resolve) => {
        console.log('inside sleep');
      setTimeout(resolve, ms);
    });
  }
   function f(filename) {
    return new Promise( async(resolve, reject) => {
      await sleep(7000);

      /*
        rest of function
      */
    });
  }


Q: How to make WhatsApp for iOS fetch image for preview set in og tag in my website? I am trying to set og:image tag for my website so that users can see the thumbnail image when the website link is shared. Now the thumbnail is working fine facebook, twitter and Linkedin. But when I share the link on WhatsApp it only works for android. In the case of WhatsApp for ios, it tries to load the image but fails and only website description is sent with the website link.
I have already followed all the answers available on this forum.The image I am trying to use for thumbnail is 669 × 378 px and is 89KB in size. There are no errors according to the facebook debugger. My website is in WordPress, so I was using Yoast SEO earlier but to solve this problem I tried by adding meta tags manually as well, but nothing works for WhatsApp for IOS.
These are the metatags found by facebook debugger for my website https://www.indiadappfest.com
These are the raw tags that we found
Meta Tag    <meta property="og:locale" content="en_US" />
Meta Tag    <meta property="og:type" content="website" />
Meta Tag    <meta property="og:title" content="India Dapp Fest 2019 | Asia's top-notch revelation on blockchain based applications" />
Meta Tag    <meta property="og:description" content="India Dapp Fest is a top-notch conference focussed on blockchain, enabling conscious decentralization and inturn, ushering in a change to pave the path for future work assemblies" />
Meta Tag    <meta property="og:url" content="https://www.indiadappfest.com" />
Meta Tag    <meta property="og:site_name" content="India Dapp Fest 2019" />
Meta Tag    <meta property="og:image" content="https://www.indiadappfest.com/wp-content/uploads/2019/03/thumbnail-2-low-resolution.jpg" />
Meta Tag    <meta property="og:image:secure_url" content="https://www.indiadappfest.com/wp-content/uploads/2019/03/thumbnail-2-low-resolution.jpg" />
Meta Tag    <meta property="og:updated_time" content="1553416119" />

Someone, please help me to fix it for ios.

A: As per the open graph documentation you should use 1:1 i.e square images, apart from that remove the yoast seo plugin and add the meta tags manually (i used a plugin called scripts and styles). This helped me solve the problem for the thumbnail in WhatsApp for ios. You might also want to add another meta tag with a rectangular image as Facebook will skew the 1:1 image when you'll share it on Facebook.


Q: Change meta description/keywords dynamically with php Im trying to grab some info from the db and use it as meta desc and keyword. But something isnt working as it supposed to.
EDIT: after alot of help i got it semi working. If there is no blogID i want it to fallback on the other part... that part of the script aint working, any ideas?
<?php
$dsn = "sqlsrv:Server=localhost;Database=blog";
$conn = new PDO($dsn, "**********", "********");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$id = $_GET['postID'];
$sql = "SELECT * FROM blog_posts WHERE blogID=:id ORDER BY blogID DESC";
 $stmt = $conn->prepare($sql);
                    $stmt->execute (array($id));
                    while($metta = $stmt->fetch(PDO::FETCH_BOTH) )

if (isset($metta['blogID']) && !empty($metta['blogID'])) {
$keywords = $metta['keywords'];
$description = $metta['description'];
} else {
$keywords = "blalbalbalblabla";
$description = "blabla";
}

?>

A: It might not be the prettiest code... but it works!
<?php
$dsn = "sqlsrv:Server=localhost;Database=blog";
$conn = new PDO($dsn, "*****", "*******");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$id = $_GET['postID'];
$sql = "SELECT * FROM blog_posts WHERE blogID=:id";
 $stmt = $conn->prepare($sql);
                    $stmt->execute (array($id));
                    $metta = $stmt->fetch(PDO::FETCH_BOTH);

if (isset($_GET['postID'])) {
$keywords = $metta['keywords'];
$description = $metta['description'];

}
sqlsrv_close($con);
?>

<meta name="description" content="<?= isset($description) ? $description : 'blablabla'; ?>">
        <meta name="keywords" content="<?= isset($keywords) ? $keywords : 'blablabla'; ?>">


Q: Java tutorial method example Here there is a snippet taken from here:
import static java.nio.file.StandardOpenOption.*;

Path logfile = ...;

// Convert the string to a
// byte array.
String s = ...;
byte data[] = s.getBytes();

try (OutputStream out = new BufferedOutputStream(
                 logfile.newOutputStream(CREATE, APPEND))) {
    ...
    out.write(data, 0, data.length);
} catch (IOException x) {
    System.err.println(x);
}

However I cannot compile the logfile (which is a Path object) with newOutputStream method... only with Files.newOutputStream(path,StandardOpenOption..);

A: Path only contains information about where a file (or other thing) is located,  it does not provide any information on how to process it. As you know the Path is a file then you can use the File class to process it, in this case to open a stream on it.
In language terms Path does not have a newOutputStream method so it will fail to compile.
From Oracle documentation on Path

Paths may be used with the Files class to operate on files, directories, and other types of files.


Q: Insert csv file data into mysql table which contains more columns I want to add the data from a csv file to a table in the DB but the table contains more columns than the file. The query should be such that some of the columns are filled by the csv file and some others should be filled with a specific value in the query. Lets say my csv file have data written in the format: "value1,value2" in every line. I want to add the data in a table containing 3 columns. First two columns should be filled with data from the file and in the third column should be the value "1". So far I have the following query which only fills the 2 columns of the table with data from the csv file:
LOAD DATA LOCAL INFILE 'target_file'
INTO TABLE table_name FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n' (col1,col2);

A: You can mark default value "1" for the third field and then import the csv file. Or you can mark the fields as nullable that are not included in the csv file, then execute a query to update the null values.


Q: Can Scala REPL on SBT call people's own scripts? (Like OptiML?) I know sbt console will open an interactive Scala REPL and load in all the library dependencies so people can test Scala code right there. However, I wonder if there's anyway to use and treat in a way so that people can interact with my programs directly, instead of interacting with libraries.
For example, if I write a Vector class, how can someone call it from sbt console or any other Scala REPL interface??
Think of it as that you are trying to write a Scala library but you want to provide a simple REPL interface for people to interact with it, like R, instead of asking people to add the library as dependency.
The effect is similar as described here: http://stanford-ppl.github.io/Delite/optiml/getting_started.html

A: Maybe this will help.
You can use initialCommands key in sbt to do this
So in build.sbt if you put
initialCommands in console := """import my.project._
val myObj = MyObject("Hello", "World")
    """

after you type 'console', you can start using myObj or the classes in my.project
http://www.scala-sbt.org/0.13.5/docs/Howto/scala.html#initial

A: Yes you can, but you cannot use modified code without reloading the REPL. Just run:
sbt "~ ; console"

And then import your classes with import your.package._ and use them from there.
If you make any changes to your library code, just hit CTRL+D or :quit and it will detect file changes, compile them and enter the REPL again. You can then use the history (navigating with the arrows up/down) to execute anything from the previous session again.


Q: How do I remove the top margin in a web page? I have had this problem with every web page I have created.  There is always a top margin above the 'main container' div I use to place my content in the center of the page.  I am using a css style sheet and have set margins and padding in the body to 0px and set the margin and padding to 0 in the div:
body{
    margin-top: 0px;
    margin-bottom: 0px;
    margin-left: 0px;
    margin-right: 0px;
    padding: 0;
    color: black;
    font-size: 10pt;
    font-family: "Trebuchet MS", sans-serif;
    background-color: #E2E2E2;
}

div.mainContainer{
    height: auto;
    width: 68em;
    background-color: #FFFFFF;
    margin: 0 auto;
    padding: 0;
}

I have looked online many times, but all I can see to do is set these margin and padding attributes.  Is there something else I should be doing?  The margin exists in IE and Firefox.
Here is a more thorough look at the code (it is in the beginning stages of creation, so there isn't much in it...)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <title></title>

        <link href="../Styles/KB_styles1.css" rel="stylesheet" type="text/css" />

Here is the information

Here is the CSS:
@charset "utf-8";
/* CSS Document */

body{
    margin-top: 0px;
    margin-bottom: 0px;
    margin-left: 0px;
    margin-right: 0px;
    padding: 0;
    color: black;
    font-size: 10pt;
    font-family: "Trebuchet MS", sans-serif;
    background-color: #E2E2E2;
}

/* ---Section Dividers --------------------------------------------------------------*/
div.mainContainer{
    position: relative;
    height: auto;
    width: 68em;
    background-color: #FFFFFF;
    margin: 0 auto;
    padding: 0;
}

div.header{
    padding: 0;
    margin: 0;
}

div.leftSidebar{
    float: left;
    width: 22%;
    height: 40em;
    margin: 0;
}

div.mainContent{
    margin-left: 25%;
}

div.footer{
    clear: both;
    padding-bottom: 0em;
    margin: 0;
}

/* Hide from IE5-mac. Only IE-win sees this. \*/
   * html div.leftSidebar { margin-right: 5px; }
   * html div.mainContent {height: 1%; margin-left: 0;}
/* End hide from IE5/mac */

A: You can prevent the effects of margin collapsing with:
body { overflow: hidden }

That will make the body margins remain accurate.

A: I had similar problem, got this resolved by the following CSS:
body {
    margin: 0 !important;
    padding: 0 !important;
}

A: I had same problem. It was resolved by following css line;
h1{margin-top:0px}

My main div contained h1 tag in the beginning.

A: The best way to reset margins for all elements is to use the css asterisk rule.
Add this to the top of your css under the @charset:
* {
   margin: 0px;
   padding: 0px;
}

This will take away all the preset margins and padding with all elements body,h1,h2,p,etc.
Now you can make the top or header of your page flush with the browser along with any images or text in other divs.

A: I have been having a similar issue. I wanted a percentage height and top-margin for my container div, but the body would take on the margin of the container div.
I think I figured out a solution.
Here is my original (problem) code:
html {
    height:100%;
}

body {
    height:100%;
    margin-top:0%;
    padding:0%;
}

#pageContainer {
    position:relative;
    width:96%;                  /* 100% - (margin * 2) */
    height:96%;                 /* 100% - (margin * 2) */
    margin:2% auto 0% auto;
    padding:0%;
}

My solution was to set the height of the body the same as the height of the container.
    html {
        height:100%;
    }
body {
    height:96%;     /* 100% * (pageContainer*2) */
    margin-top:0%;
    padding:0%;
}

#pageContainer {
    position:relative;
    width:96%;                  /* 100% - (margin * 2) */
    height:96%;                 /* 100% - (margin * 2) */
    margin:2% auto 0% auto;
    padding:0%;
}

I haven't tested it in every browser, but this seems to work.

A: The same issue has been driving me crazy for several hours. What I found and you may want to check is html encoding. In my html file I declared utf-8 encoding and used Notepad++ to enter html code in utf-8 format. What I DID forget of was UTF-8 BOM and No BOM difference. It seems when utf-8 declared html file is written as UTF-8 BOM there is some invisible extra character at the begining of the file. The character (non-printable I guess) effects in one row of "text" at the top of the rendered page. And you cannot see the difference in source-view of the browser (Chrome in my case). Both nice and spoiled files seem identical to the very character, still one of them renders nicely and the other one shows this freaking upper margin.
To wrap it up the solution is to convert the file to UTF-8 NO BOM and one can do it in i.e. Notepad++.

A: A lot of elements in CSS have default padding and margins set on them. So, when you start building a new site, it's always good to have a reset.css file ready. Add this to make to rub the default values, so you have more control over your web page.
/* CSS reset */
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td {
    margin:0;
    padding:0;
}
html,body {
    margin:0;
    padding:0;
}

/* Extra options you might want to consider*/

table {
    border-collapse:collapse;
    border-spacing:0;
}
fieldset,img {
    border:0;
}
input{
    border:1px solid #b0b0b0;
    padding:3px 5px 4px;
    color:#979797;
    width:190px;
}
address,caption,cite,code,dfn,th,var {
    font-style:normal;
    font-weight:normal;
}
ol,ul {
    list-style:none;
}
caption,th {
    text-align:left;
}
h1,h2,h3,h4,h5,h6 {
    font-size:100%;
    font-weight:normal;
}
q:before,q:after {
    content:'';
}
abbr,acronym {
    border:0;
}

I hope this helps all fellow developers this is something that bugged for me a while when I was learning.

A: Is your first element h1 or similar?  That element's margin-top could be causing what seems like a margin on body.

A: Here is the code that everyone was asking for -- its at the very beginning of development so there isn't much in it yet, which may be helpful...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <title></title>

    <link href="../Styles/KB_styles1.css" rel="stylesheet" type="text/css" />

Here is the css:
@charset "utf-8";
/* CSS Document */

body{
    margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px;
    padding: 0;
    color: black; font-size: 10pt; font-family: "Trebuchet MS", sans-serif;
    background-color: #E2E2E2;}

html{padding: 0; margin: 0;}

/* ---Section Dividers -----------------------------------------------*/
div.mainContainer{
    height: auto; width: 68em;
    background-color: #FFFFFF;
    margin: 0 auto; padding: 0;}

div.header{padding: 0; margin-bottom: 1em;}

div.leftSidebar{
    float: left;
    width: 22%; height: 40em;
    margin: 0;}

div.mainContent{margin-left: 25%;}

div.footer{
    clear: both;
    padding-bottom: 0em; margin: 0;}

/* Hide from IE5-mac. Only IE-win sees this. \*/
* html div.leftSidebar { margin-right: 5px; }
* html div.mainContent {height: 1%; margin-left: 0;}
/* End hide from IE5/mac */

A: Try margin -10px:
body { margin-top:-10px; }

A: For opera just add this in header
<link rel='stylesheet' media='handheld' href='body.css' />

This makes opera use most of your customised css.

A: It is a
 element that creates the top margin. You removed all top margins except of that element.

A: same problem, h1 was causing it to have that massive margin-top. after that you can use body{margin: 0;} and its looks good. another way is using *{margin: 0;} but it might mess up margins of other elements for you.

A: I had this exact same problem.  For me, this was the only thing that worked:
div.mainContainer { padding-top: 1px; }

It actually works with any number that's not zero.  I really have no idea why this took care of it.  I'm not that knowledgeable about CSS and HTML and it seems counterintuitive. Setting the body, html, h1 margins and paddings to 0 had no effect for me.  I also had an h1 at the top of my page

A:

body{
margin:0;
padding:0;
}
Example

A: I tried almost every online technique, but i still got the top space in my website, when ever i open it with opera mini mobile phone browser, so i decided to try fix it on my own, and i got it right!
i realize when even you display a page in a single layout, it fits the website to the screen, and some css functions are disabled, since margin, padding, float and position functions are disabled automatically when you fit to screen, and the body always add inbuilt padding at the top. so i decieded to look for at least one function that works, guess what? "display". let me show you how!

eg:

 and so on..

If you notice, the body{display:inline;} removes the inbuilt padding in the body, but without #top{display:inline-block;}, the div still wont display well, so you must include the

element before any code on your page! so simple.. hope this helps? you can thank me if it works, http://www.facebook.com/exploxi

A: you may also check if:
{float: left;}

and
{clear: both;}

are used correctly in your css.

A: style="text-align:center;margin-top:0;" cz-shortcut-listen="true"

paste this at your body tag!
this will remove the top margin


Q: Return a value / cancel installation with vbscript custom action I have a custom action in my installer that opens a message box using a vbscript custom action.
<CustomAction Id="EXENotFound" Script="vbscript" Return="check">
      <![CDATA[
        Dim i
        If session.Property("REMINDEX_SHORTCUT") = "" Then
          i = MsgBox(session.Property("TextProp"), 1)
        End If
      ]]>
</CustomAction>

I want to cancel the installation if the value of i = 2 (if cancel is pressed in the message box). I think I can get the installation to cancel if my script returns a value of 3, but it only ever returns 0. I've tried this:
Dim i
If session.Property("REMINDEX_SHORTCUT") = "" Then
  i = MsgBox(session.Property("TextProp"), 1)
End If
If i = 2 Then
  return 3
End If

which throws some error about 'type mismatch'.
I also tried this when I got desperate:
<CustomAction Id="EXENotFound" Script="vbscript" Return="check">
          <![CDATA[
            Dim i
            If session.Property("REMINDEX_SHORTCUT") = "" Then
              i = MsgBox(session.Property("TextProp"), 1)
            End If
            If i = 2 Then
              EXENotFound = 3
            End If
          ]]>
</CustomAction>

I've done extensive research online but have not been able to find how to cancel the installation from a custom action or even how to simply return 3 manually.
Any suggestions would be greatly appreciated

A: I only dabbled with WiX a little, and it's been some years since then, but I think you need to put your code in a function:
<CustomAction Id="EXENotFound" Script="vbscript" Return="check">
  <![CDATA[
    Function AskUser
      AskUser = 0
      If session.Property("REMINDEX_SHORTCUT") = "" Then
        AskUser = MsgBox(session.Property("TextProp"), 1)
      End If
    End Function
  ]]>
</CustomAction>

A: If you're in the UI sequence, then the correct way to do this is to show a standard dialog built using your MSI development tool, and wire up the Cancel logic if that's one of the choices. That's mostly covered by other answers. The correct way to show a message in the execute sequence (from a custom action) is to call MsiProcessMessage (or installer object or DTF managed CA equivalents). Return IDCANCEL if appropriate.
https://msdn.microsoft.com/en-us/library/aa370354(v=vs.85).aspx
http://microsoft.public.platformsdk.msi.narkive.com/oKHfPSZc/using-msiprocessmessage-in-a-c-custom-action


Q: Setting current user for required model field I have a model where one of the required fields is the currently signed in user. I do the following when creating a new record for the model:
views.py
def post(self, request):
    bound_form = self.form_class(request.POST)
    if bound_form.is_valid():
        new_position = bound_form.save()

The problem is that this only works when the user has selected them self on the form. I need a way to set the current user automatically and simply don't display the user field on the form. I have tried this:
def post(self, request):
    bound_form = self.form_class(request.POST)
    if bound_form.is_valid():
        new_position = bound_form.save(commit=False)
        new_position.user = request.user
        new_position.save()

However this does not work because the bound_form is not valid because it is missing a user which is a required field on the model. Where else can the user be set before trying to save the form? In the template, or the get method of the view?

A: You should use exclude=('user',) in class Meta: of your form. @Daniel Roseman is also right.


Q: Null safety operator for function variable in Kotlin In my Kotlin app I have nullable variable like this
private var myCallback : (() -> Unit)? = null

Is it possible to use null safety operator ? to call it? This gives me a compilation error.
myCallback?()

I found only this ugly way for a call if it is not null
 if(myCallback != null)
     myCallback!!()

A: You can call it as follows:
 myCallback?.invoke()

The () syntax on variables of function types is simply syntax sugar for the invoke() operator, which can be called using the regular safe call syntax if you expand it.


Q: Creating a simple Node.js web service for use with AJAX I have a basic Node.js http server set up as per the docs, I'm trying to create a very simple web service I can talk to with Javascript (AJAX) which I'll then hook up to Arduino.  It's a test piece, I may go down the road of something else but this is proving to be fun.  Anyway, here is the server-side javascript:
var http = require('http');
var _return = 'Bing Bong';

  http.createServer(function (req, res) {
        res.writeHead(200, {'Content-Type': 'application/jsonp'});

    //do stuff
    res.end('_return(\'Hello :-)\' + _return)');
}).listen(process.env.VMC_APP_PORT || 1337, null);

And this is the client side:
function experimentFive(node) {
    console.log('X5 Func started');

    console.log('Calling Node.js service');

    var nodeURL = node;

    $.ajax({
        url: nodeURL,
        dataType: "jsonp",
        jsonpCallback: "_return",
        cache: false,
        timeout: 50000,
        success: function(data) {
            console.log('Data is: ' + data);
            $("#nodeString").text(" ");
            $("#nodeString").append(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log('error : ' + textStatus + " " + errorThrown);
        }
    });
}

experimentFive('http://fingerpuk.eu01.aws.af.cm/');

This works, I get the data back but not as I'd expect.  What I'd like to be able to do is change some data server side and receive that back.  I get back the string in the res.end plus:
function () {
        responseContainer = arguments;
    }

Instead of the variable's data.  No matter how I try to get that data back, it is either undefined or this response.
From research I think the variable is not having it's data set before the callback fires, so it's empty.  But if I set an initial value the data is still undefined.
Am I missing something very simple here?  Should I just go back to C#?
Cheers.

A: One possible way of accomplishing this would be to use ExpressJS with NodeJS to handle routing your endpoints. By doing this you can set up routes such as GET /media/movies/, fire an AJAX request to this route, then have it return JSON data that you can handle on your app.
Here's an example of ExpressJS routing in an app that I made:
var groups = require('../app/controllers/groups');

// find a group by email
app.post('/groups/find', groups.searchGroupsByEmail);

Here is a great tutorial that I used when getting started with Express. It walks through the entire process from installing Node.JS (which you've already done) to setting up the ExpressJS routing to handle incoming HTTP requests.
Creating a REST API using Node.js, Express, and MongoDB


Q: Keyboard Issues with Ionic4 I have developed an android application using Ionic4. The issue I am facing is when the keyboard appears it covers the Input field, screen is not moving up.
I have solved this issue in Ionic 3 by the following lines of code. But this does not works in Ionic4. Somebody please help.
imports: [
    IonicModule.forRoot(MyApp, {
    scrollAssist: true,
    autoFocusAssist: true
    })
  ],

HTML

    <form [formGroup]="credentialsForm" class="width-100">
        <ion-list>
            <ion-item no-padding class="transparent-border">

            </ion-item>
            <ion-item no-padding>
                <ion-label position="floating" color="primary">Username</ion-label>
                <ion-input type="text" color="primary" mode="ios" maxLength="5" formControlName="userName" required></ion-input>
            </ion-item>
            Username
                is mandatory
            <ion-item no-padding>
                <ion-label position="floating" color="primary">Password</ion-label>
                <ion-input color="primary" type="password" mode="ios" formControlName="password" required></ion-input>
            </ion-item>
            Password
                is mandatory
            <ion-item no-padding class="transparent-border">

Create an Account

Forgot password?

            </ion-item>
        </ion-list>
    </form>
    <ion-button (click)="doLogin()" expand="block" shape="round" class="signin-button" color="vibrant">Sign
        In</ion-button>

A: Try this
ngAfterViewInit(): void {
window.addEventListener('keyboardDidShow', this.customScroll);
}

private customScroll() {
 this.content.scrollTo(0, 100); // 100 replaced by your value
}


Q: SQL: "Where" or "AND" what performs better on large database? I have this SQL query. It runs on the same table and creates a dataset with three columns. My concern is whether I should Use 'WHERE' clause or 'AND'. I have this feeling that 'AND' will be more efficient and faster than 'WHERE'. Please advise.
1st one is with 'WHERE' and 2nd one is without it.

*

*SELECT DISTINCT t1.rpsrespondent AS id_num,t1.rpscontent AS PID, t2.RpsContent AS SeqNo
FROM table t1
INNER JOIN table t2 ON t1.rpsrespondent=t2.rpsrespondent
INNER JOIN table t3 ON t3.rpsrespondent=t1.rpsrespondent
WHERE t1.RpsQuestion='PID' AND t2.RpsQuestion = 'VISITID'
AND t3.rpsquestion ='INT99' AND t3.rpscontent in('36','37')

*SELECT DISTINCT t1.rpsrespondent AS id_num,t1.rpscontent AS PID, t2.RpsContent AS SeqNo
FROM table t1
INNER JOIN table t2 ON t1.rpsrespondent=t2.rpsrespondent
AND t1.RpsQuestion='PID' AND t2.RpsQuestion = 'VISITID'
INNER JOIN table t3 ON t3.rpsrespondent=t1.rpsrespondent
AND t3.rpsquestion ='INT99' AND t3.rpscontent in('36','37')

A: With an INNER JOIN, it makes no difference if predicates are specified in the JOIN or WHERE clauses.  The queries are semantically identical so the SQL Server optimizer should generate the same (optimal) executional plan.  You will get the same performance as a result.


Q: Slow add column I have an 8 million row table in an RDS mysql instance which is read replicated.
When adding a new column (int / length 2 / default 0) the primary DB reached 100% and hung until reboot.
So, I ran a test on my local machine - same table / same new column (not read replicated) and the change was instant.
Please advise why such an issue would occur? Any ideas welcome


Q: Django admin, change current value of ForeignKey widget in my Django admin application I have one ForeignKey field with its relative widget in change page.

I wish to add a link to change view of current selected product instead of simple text of current product.
My models is composed of: WeddingList, Product and WeddingListProducts for m2m relationship...
In my admin.py the ProductAdmin class is an inline of WeddingListAdmin class.
This is my admin.py
class WeddingListProductsInline(admin.TabularInline):
    model = WeddingListProducts
    form = WeddingListProductsAdminForm
    extra = 0

class WeddingListAdmin(admin.ModelAdmin):
    inlines = (WeddingListProductsInline,)

Thanks in advance for help!

A: Ok, I've solved my problem.
My solution is to override admin/edit_inline.html template with these code:

        {% if inline_admin_form.original or inline_admin_form.show_url %}

                {% if inline_admin_form.original %}

                        {{ inline_admin_form.original }}

                {% endif %}

        {% endif %}

and set the template attribute of my ModelAdmin class to corresponding url of new template.
admin.py
class MyModelInline(admin.TabularInline):
    template = "admin/myapp/mymodel/edit_inline/tabular.html"

Please comment for any better solutions! Bye ;)


Q: Bootbox alert not on focus I'm calling bootbox confirm function, but it isn't on focus. All my page get this gray effect, including the bootbox window. What am I doing wrong?

Here's how I am calling bootbox confirm function:
$(".js-delete").on("click", function () {
            var tr = $(this).closest('tr');
            var button = $(this);

            bootbox.confirm("Você tem certeza que deseja deletar esse registro de cliente?", function (result) {
                if (result) {
                    $.ajax({
                        type: "POST",
                        url: "@Url.Action("Delete","Customers")",
                        ajaxasync: true,
                        data: { id: button.attr("customer-id") },
                        success: tr.remove()
                    });
                }
            });
        });


Q: network graph using igraph() from lm() regression output I'd like to get a visual overview of the output of a linear regression model.
I'd like to be build a network plot with unidirectional edges using the output from a regression model, and I'd like to only include predictors with a p-value <0.05 (so to end up with a structure like the one I've plotted manually below).
Ideally, I'd also like the edges to be green when there is a positive association, red when there is a negative association, and to be thicker when there is a strong association.
It's my first time working with network/network-like graphs, and I'm at loss. Any help would be much appreciated.
# PACKAGES
library(dplyr)
library(broom)
library(igraph)

# DATA
mtcars

# MODEL AND OUTPUT
mymodel = mtcars %>% do(myfit = lm(mpg ~  wt + gear +carb, data = .))
mymodCoef = tidy(mymodel, myfit)
mymodCoef <- as.data.frame(mymodCoef)

# WHAT I'D LIKE TO PLOT TO LOOK LIKE
plot(graph_from_literal(wt--+mpg, carb--+mpg))

A: You need to create a data frame representing an edge list in the format of:

*

*column1 = node where the edge is coming from

*column2 = node where the edge is going to

*columnn... = attributes you want to store in the edge

Then you will need to input that df into graph_from_data_frame
Two of the attributes you can store in the edge list are color and width which will automatically be plotted in igraph's base plot function.
edge_list <- mymodCoef %>%
  mutate(source = term,
         target = 'mpg',
         color = sapply(statistic, function(x){ifelse(x<0, 'red', 'green')}),
         width = abs(statistic)/(max(abs(statistic))) * 10) %>%
  filter(p.value <= .05) %>%
  select(source, target, color, statistic, width)

g <- graph_from_data_frame(edge_list, directed = F)

plot(g)

If you wanted to explicitly plot the color and width, then
plot(g, edge.width = E(g)$width, edge.color = E(g)$color)

Sometimes you'll need to play around with scales - for instance, the difference in statistic scores are at most 2 and will look identical if you used the raw statistic score as the line width. If you want to get scaling for free, then you can use ggraph:
library(ggraph)
ggraph(g) +
  geom_edge_link(aes(edge_colour = color,
                     edge_width = abs(statistic))) +
  geom_node_text(aes(label = name)) +
  scale_edge_color_manual(values = c('green' = 'green', 'red' = 'red'))

If you want to learn more about plotting with igraph, then some of the best tutorials for plotting in igraph can be found in Katherine Ognyanova's website: http://kateto.net/netscix2016


Q: traversing an array one less time each time Lets say I have an array of [1,2,3,4,5]
I want to attempt to traverse the array one less each time, while adding the numbers.
First time:
1+2+3+4+5 = 15

Second time:
2+3+4+5 = 14

Third time:
3+4+5 = 12

Fourth time:
4+5 = 9

Fifth time:
5 = 5

any help would be greatly appreciated!
Thank you so much.
-AbysssCoder

A: Since you tagged your question with MATLAB...
>> x = [1,2,3,4,5]; % define array
>> cumsum(x, 'reverse') % cumulative sum in reverse order
ans =
    15    14    12     9     5

A: int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
    int sum = 0;
    for (int j = i; j < arr.length; j++) {
        sum += arr[j];
    }
    System.out.println(sum);
}

Something like this?


Q: Hash three 32-bit integers into a 64-bit integer? Looking for some ways to hash three 32-bit integers into a single 64-bit integer.  Interested in knowing a fast way of doing this but with as few collisions as possible.  Thanks.


Q: Advice on reading indexes I'm trying to figure out the right way to read lucene index only once whilst running the application multiple times, how can I do that in java?
Because indexed data will not change so reading them each time would not be necessary. Can someone explain me the logic of it reading them only once? thank you
UPDATE :
public List initTableObject() throws IOException {
        Directory fSDirectory = FSDirectory.open(new File(INDEX_NAME));
        List<String>termList = new ArrayList<String>();

        RAMDirectory directory = new RAMDirectory(fSDirectory);

        IndexReader iReader = IndexReader.open(fSDirectory);
        FilterIndexReader fReader = new FilterIndexReader(iReader);

    //  int numOfDocs = fReader.numDocs();
        TermEnum terms = fReader.terms();

        while (terms.next()){
            Term term = terms.term();
            String termText = term.text();
            termList.add(termText);
            }
            iReader.close();
            return termList;
    }

I'm really new with lucene and this, so here is what I've got so far I'm just not there yet with RAMDirectory.
This method retrieves list because I need this index list to compare with some files that I have. How can I store this list to the RAM so I can use it in my other part of application for comparison ?

A: I think the answer on this question might be of use.


Q: Is there a best practice for where to log when running multiple instances of an application with Docker? I am trying to create an application that will be run on multiple Docker instances on multiple machines. Since  my containers will be running nginx as their command, docker logs would show the output of nginx logs, which is fine. However, that begs the question: where should my application log?
The options I have thought about are the following.
Log on the host file system
As far as I can tell, to be able to identify which Docker container has written to the log, I must create something like /var/logs/myapplication, and create a folder for each container, and tell my application inside the container to write into that directory. For example, I would have to create /var/logs/myapplication/instance-1 and mount that as a volume inside my Docker container.
The problem in this approach is that it's hard to collect logs. I will have to ssh to different machines, go in the /var/logs/myapplication directory of each machine and get the logs out to read them. It's perfectly fine when I know there's a question, but confusing when I am trying to monitor the whole system.
Logging in the database
In this method, all Docker containers will write to a database, and one of the columns of the database will be container_name so that I can filter logs based on container name.
The problem with this approach is that I haven't ever used a database for keeping logs, and I'm not really sure if they are meant to be used like this.
Back to the original question
So my question is, is there a proven best-practice for logging when you have multiple machines with multiple containers on each?


Q: How to include and exclude checkboxes from being calculated? Netbeans IDE I was wondering if there is a way I can write a code where I have 6 checkboxes and I want to have them calculated as a final sum, I want to write it to have the selected ones included into the calculation only. I asked my teacher about it and all I got was the we did this in class crap but no we didn't, he sent me this code to use but it's not excluding the checkboxes it's all or nothing.
    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jCheckBox1.isSelected() == true) {jCheckBox1.setText("50");}
    }

    private void jCheckBox2ActionPerformed(java.awt.event.ActionEvent evt) {
if (jCheckBox2.isSelected() == true) {jCheckBox2.setText("50");}
    }

    private void jCheckBox3ActionPerformed(java.awt.event.ActionEvent evt) {
if (jCheckBox3.isSelected() == true) {jCheckBox3.setText("50");}

    }

    private void jCheckBox4ActionPerformed(java.awt.event.ActionEvent evt) {
if (jCheckBox4.isSelected() == true) {jCheckBox4.setText("50");}
    }

    private void jCheckBox5ActionPerformed(java.awt.event.ActionEvent evt) {
if (jCheckBox5.isSelected() == true) {jCheckBox5.setText("50");}
    }

    private void jCheckBox6ActionPerformed(java.awt.event.ActionEvent evt) {
if (jCheckBox6.isSelected() == true) {jCheckBox6.setText("50");}
    }

And then he told me to declare variables so I did what he told me in this code
double Box1, Box2, Box3, Box4, Box5, Box6;
Box1 = Double.parseDouble(jCheckBox1.getText());
Box2 = Double.parseDouble(jCheckBox2.getText());
Box3 = Double.parseDouble(jCheckBox3.getText());
Box4 = Double.parseDouble(jCheckBox4.getText());
Box5 = Double.parseDouble(jCheckBox5.getText());
Box6 = Double.parseDouble(jCheckBox6.getText());
sum = Box1+Box2+Box3+Box4+Box5+Box6;

I have tried getting it into the next form with a few selected boxes but all I get is a huge red error and it's getting me frustrated.

A: See,you are defining the cases--- if the checkboxes have been selected, but what about them if they aren't selected!These might be picking some Garbage values as per your bottom piece of code!
So,you better provide an else statement along with each if-statement. Also,there is no need to write actionPerformed() for each of the Checkboxes! It would be achieved even using a single JButton.Else you'll have several problems implementing that as to how to set Default values and all!
You can try this.I think it'll work fine. :-
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
  Double cb1,cb2,cb3,cb4,cb5,cb6;
  Double total=0d;
  if (jCheckBox1.isSelected() == true) {jCheckBox1.setText("50");}
   else jCheckBox1.setText("");
  if (jCheckBox2.isSelected() == true) {jCheckBox2.setText("50");}
   else jCheckBox2.setText("");
  if (jCheckBox3.isSelected() == true) {jCheckBox3.setText("50");}
   else jCheckBox3.setText("");
  if (jCheckBox4.isSelected() == true) {jCheckBox4.setText("50");}
   else jCheckBox4.setText("");
  if (jCheckBox5.isSelected() == true) {jCheckBox5.setText("50");}
   else jCheckBox5.setText("");
  if (jCheckBox6.isSelected() == true) {jCheckBox6.setText("50");}
   else jCheckBox6.setText("");
  cb1=Double.parseDouble((jCheckBox1.getText().equals(""))?"0":"50");
  cb2=Double.parseDouble((jCheckBox2.getText().equals(""))?"0":"50");
  cb3=Double.parseDouble((jCheckBox3.getText().equals(""))?"0":"50");
  cb4=Double.parseDouble((jCheckBox4.getText().equals(""))?"0":"50");
  cb5=Double.parseDouble((jCheckBox5.getText().equals(""))?"0":"50");
  cb6=Double.parseDouble((jCheckBox6.getText().equals(""))?"0":"50");
  total=cb1+cb2+cb3+cb4+cb5+cb6;
  jLabel1.setText("The total comes out to be :- "+total);
}

A: Use an else in your Ifs and set the text to "0" if it's not selected.
Also, when you initialize your checkboxes, set a default text of "0".


Q: ActionPerformed and ActionListener My program asks the user: How many course have you completed? So, the users has to enter the number of courses completed on a JTextField component. My program then converts the String that has been entered in the JTextField into a Integer. When I run my program, I get a numberformatException. I tried debugging, and I noticed that my program converts the String into a Integer before the user can write anything. The program doesn't wait for the user to type anything. How can I make so my program waits for the user to enter a number before continuing to execute the code?
public class content extends JPanel implements ActionListener
{

     String number = "";
     JTextField NumtextField = new JTextField(5);

     @Override
     public void actionPerformed(ActionEvent e)
     {
         number = NumtextField.getNumtextField().getText();
     }

     int size = Integer.parseInt(number);

}

A: Move int size = Integer.parseInt(number); inside actionPerformed:
 public void actionPerformed(ActionEvent e){
 number = NumtextField.getNumtextField().getText();
 int size = Integer.parseInt(number);
 }

When the program starts, its trying to parse "", which is not a valid number string hence why you are getting an exception.
Also maybe you should put that inside a try{}catch{} block, so in case you get an exception in real time you can handle it:
try {
 int size = Integer.parseInt(number);
}
catch (NumberFormatException e) {
System.out.println("Thats not a valid number");
}


Q: find numbers in array that add up to a given number c++ I am writing this code that takes the input file and sorts all the integers from that file into an array. Then it takes the sum chosen by the user  and goes through all the combinations (one by one /professors orders/) to find a pair that equal the desired sum. some of the code is funky because we are required to use a C++03 compiler -sigh-. The program has no errors but when I run it it says
There were 1600 checks made to find the products of your desired sum and
the two numbers that add to your sum are 40 and 40
Segmentation fault (core dumped)
(the desired sum was not one that could have been found in the input file so it should have said " the program did not find any matches. try again. ")
The code is very messy and Im sorry but I have spent hours moving stuff around and adding new things or trying something new to try and make it work.
I have a feeling it is a problem with how I am declaring the boolean variables or maybe how I am passing them.
int x, i, n1, n2, pos1 = 0, pos2 = 0,accesses = 0;
bool fail = false;

int readSortedArray (int array[20], int count, istream& infile)
{
count = 0;
while(infile >> array[count])
{
    count++;

}

return count;
}

int findproducts (int array[20], int& n1, int& n2, int count, int sum, int& accesses, bool fail, istream& infile)
{
bool found = true;
while(found == true)
{
for( i = 0; i < count; i++)
{
pos1++;
n1 = array[i];
pos2 = 0;
for( x = 0; x < count; x++)
{
pos2++; accesses ++;
n2 = array[x];
if(sum == n1 + n2)
{
    found = false;
    fail = false;
}
if(sum != n1 + n2)
{
    fail = true;
}
}
}
}

return fail;
}

int main ()
{
 int array[20];
 int answer, sum, count = 0;

std::string input_filename;
ifstream infile;

cout << "Please enter name of the input file: ";
cin >> input_filename;
infile.open(input_filename.c_str());
if (!infile)
{
    cout << "Could not open input file one\n";
    return 0;
}

cout << "Please enter the prefered sum ";
cin >> sum;

count = readSortedArray(array, count, infile);

fail = findproducts(array, n1, n2, count, sum, accesses, fail, infile);

cout << "There were " << accesses << " checks made to find the products of your desired sum and" << endl;

if(fail == true)
{
    cout << " the program did not find any matches. try again. ";
}
if(fail == false)
{
cout << endl << "the two numbers that add to your sum are " << n1 << " and " << n2 << endl << ". These were found in position " << pos1 << " and " << pos2;
}

 return 0;
}

A: I incorporated Karan S Warraich's comment about the bool type. I also removed the file parameter to findProducts. But the big issue was the while loop ran forever when it did not find anything. I got rid of it. Also, it was important to get out of the for before the good numbers were lost again and fail was reset. As you note, a number of code cleanups are possible (like found now does nothing, and fail need not be set within findproducts), but here is something that works
bool findproducts (int array[20], int& n1, int& n2, int count, int sum, int& accesses, bool fail)
{
bool found = true;
for( i = 0; i < count; i++)
{
    pos1++;
    n1 = array[i];
    pos2 = 0;
    for( x = 0; x < count; x++)

        {
        pos2++; accesses++;
        n2 = array[x];
        if(sum == n1 + n2)
        {
        found = false;
        fail = false;
        return false;
        }

        }
}

return true;
}

A: In your findproduct function you are returning bool value while your function is of int type that is either make your function a bool return type or return 1 for true and 0 for false


Q: MySql soterd procedure IF ELSE and while loop I want to create a stored procedure in MySQL where I loop through the records and return rows if certain condition is true.
For eg: I have a table with columns PRIMARY, TRANSTYPE, DATE, AMOUNT. Now PRIMARY can be either 0 or 1 and TRANSTYPE can BE A,B,C.

Now what I want to do is return row where PRIMARY="0" if TRANSTYPE = "A" and return row where PRIMARY="1" if TRANSTYPE = "B" or TRANSTYPE = "C"
Currently I am doing this with PHP, but I want to do it with MySql stored procedure.

A: SELECT * FROM <table>
    WHERE
         (PRIMARY="0" AND TRANSTYPE = "A") OR
         (PRIMARY="1" AND TRANSTYPE = "B") OR
         (PRIMARY="1" AND TRANSTYPE = "C")

A: you can do
 CREATE PROCEDURE PROC_NAME()
    BEGIN
       select * from table
       where (TRANSTYPE = 'A' and PRIMARY = '0')
          or (TRANSTYPE in ('B','C') and PRIMARY = '1');
    END;


Q: Print proper mathematical formatting When I use sympy to get the square root of 8, the output is ugly:
2*2**(1/2)
import sympy

In [2]: sympy.sqrt(8)

Out[2]: 2*2**(1/2)

Is there any way to make sympy print output in proper mathematical notation (i.e. using the proper symbol for square root) ?
UPDATE:
when I follow the suggestions from @pqnet:
from sympy import *
x, y, z = symbols('x y z')
init_printing()
init_session()

I get following error:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-23-21d886bf3e54> in <module>()
      2 x, y, z = symbols('x y z')
      3 init_printing()
----> 4 init_session()

/usr/lib/python2.7/dist-packages/sympy/interactive/session.pyc in init_session(ipython, pretty_print, order, use_unicode, quiet, argv)
    154                 # and False means don't add the line to IPython's history.
    155                 ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False)
--> 156                 mainloop = ip.mainloop
    157             else:
    158                 mainloop = ip.interact

AttributeError: 'ZMQInteractiveShell' object has no attribute 'mainloop'

A: The simplest way to do it is this:
sympy.pprint(sympy.sqrt(8))

For me (using rxvt-unicode and ipython) it gives
    ___
2⋅╲╱ 2

A: In an ipython notebook you can enable Sympy's graphical math typesetting with the init_printing function:
import sympy
sympy.init_printing(use_latex='mathjax')

After that, sympy will intercept the output of each cell and format it using math fonts and symbols. Try:
sympy.sqrt(8)

See also:

*

*Printing section in the Sympy Tutorial.


Q: Cannot reopen Jupyter notebooks on Google Cloud Dataproc cluster after stopping cluster I was using Google Cloud Dataproc to run a Jupyter notebook (following these instructions: https://cloud.google.com/dataproc/docs/tutorials/jupyter-notebook).
I ran a notebook, saved it, and then at some point later on, stopped the cluster (using the GUI). Then later I restarted the cluster and tried to run Jupyter notebook again with the same instructions but in the last step, when I try to open Jupyter in Chrome I get:
"This site can't be reached. The webpage at http://<my-cluster-name>:8123/ might be temporarily down or it may have moved permanently to a new web address. ERR_SOCKS_CONNECTION_FAILED."

Also (I don't know if this helps) in the terminal window where I configured my browser, I have a message:
ERROR:child_thread_impl.cc(762)] Request for unknown Channel-associated interface: ui::mojom::GpuMain
Google Chrome[695:8548] NSWindow warning: adding an unknown subview: <FullSizeContentView: 0x7fdfd3e291e0>. Break on NSLog to debug.
Google Chrome[695:8548] Call stack:
(
"+callStackSymbols disabled for performance reasons"
)

In the terminal window where I ssh-ed to my cluster I have these messages:
channel 3: open failed: connect failed: Connection refused
channel 4: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused
channel 6: open failed: connect failed: Connection refused
channel 12: open failed: connect failed: Connection refused
channel 12: open failed: administratively prohibited: open failed
channel 13: open failed: administratively prohibited: open failed
channel 14: open failed: administratively prohibited: open failed
channel 14: open failed: connect failed: Connection refused
channel 8: open failed: connect failed: Connection refused

Also, earlier BEFORE I had stopped the cluster I could close the jupyter notebooks, disconnect from the cluster, and reopen the jupyter notebook. I only ran into this problem after I had stopped the cluster. Any ideas what might be going on?

A: This is because the current initialization action explicitly launches the jupyter notebook service calling launch-jupyter-kernel.sh. Initialization actions aren't the same as GCE startup-scripts in that they don't re-run on startup; the intent normally is that initialization actions need not be idempotent, but instead if they want to restart on startup need to add some init.d/systemd configs to do so explicitly.
For the one-off case, you can just SSH into the master, then do:
sudo su
source /etc/profile.d/conda.sh
nohup jupyter notebook --allow-root --no-browser >> /var/log/jupyter_notebook.log 2>&1 &

If you want this to happen automatically on startup, you can try to put that in a startup script via GCE metadata, though if you're doing that at cluster creation time you'll need to make sure it doesn't collide with the Dataproc initialization action (also, startup scripts might run before the dataproc init action, so the first attempt you might just want to allow to fail silently).
Longer term, we should update the initialization action to add the entry into init.d/systemd so that the init action itself configures auto restart on reboot. There's no one dedicated to this at the moment, but if you or anyone you know is up to the task, contributions are always well appreciated; I filed https://github.com/GoogleCloudPlatform/dataproc-initialization-actions/issues/108 to track this feature.

A: I fixed the problem by connecting to master machine using ssh and created a systemd service(followed dennis-huo's comment above).

*

*go to /usr/lib/systemd/system

*sudo su

*create a systemd unit file called "jupyter-notebook.service" with content
[Unit]
Description=Start Jupyter Notebook Server at reboot

[Service]
Type=simple
ExecStart=/opt/conda/bin/jupyter notebook --allow-root  --no-browser

[Install]
WantedBy=multi-user.target

*systemctl daemon-reload

*systemctl enable jupyter-notebook.service

*systemctl start jupyter-notebook.service

Next step will be to include above code into dataproc-initialization-actions.
Hope that helps.


Q: Calculating the closest color in a dictionary to an input I have a dictionary of colors (below) and a color such as #4a7dac which is 'steelblue'. I want to find the name of the closest hex colour in the dictinary to this colour. So the algorithm would decide on #0000ff and return 'blue'.
colors= {
    "red":"#FF0000",
    "yellow":"#FFFF00",
    "green":"#008000",
    "blue":"#0000FF",
    "black":"#000000",
    "white":"#FFFFFF",
    "gray":"#808080",
}

I have thought about calculating some sort of 'distance' between colors, but don't know how to go about writing this.

A: We can create a function that takes two hex strings and returns the sum of the differences between the individual colour components. If you can't understand how the following works, just comment.
def diff(h1, h2):
    def hexs_to_ints(s):
        return [int(s[i:i+2], 16) for i in range(1,7,2)]
    return sum(abs(i - j) for i, j in zip(*map(hexs_to_ints, (h1, h2))))

And we can test it:
>>> diff('#ff00ff', '#0000ff')
255
>>> diff('#0000ff', '#00000a')
245

So now, we can create a function that uses this function to complete the task:
def get_col_name(hex, colors):
    return min([(n,diff(hex,c)) for n,c in colors.items()], key=lambda t: t[1])[0]

Unfortunately, this doesn't work for your colors, since it chooses gray which is [128, 128, 128] so very near to steelblue which is [74, 125, 172] - nearer than blue which is [0, 0, 255]. This means the difference is smaller to gray that to blue. I'll try to think of a better method, but maybe someone has some insight and can drop a comment?

A: How about converting them into RGB and find the dominatant color?
For example
RED FF0000         rgb(255,0,0)
BLUE 0000FF        rgb(0,0,255)
steelblue 4A7DAC   rgb(74,125,172)

You can most likely achieve this target with the RGB rather than the HEX
The rest you can see this algo: https://stackoverflow.com/a/9018100/6198978
EDIT
The thing is RGB and HEX calculation will not be able to work with Grey color as every color just has closest distance to the grey. For that purpose you can use the HSV values of the color, I am editing the code with the HSV implemented as well :D
Learned alot :D
I was having fun with it here you go:
    import math
    colors= {
    "red":"#FF0000",
    "yellow":"#FFFF00",
    "green":"#008000",
    "blue":"#0000FF",
    "black":"#000000",
    "white":"#FFFFFF",
    "grey": "#808080"
}

# function for HSV TAKEN FROM HERE: https://gist.github.com/mathebox/e0805f72e7db3269ec22
def rgb_to_hsv(r, g, b):
    r = float(r)
    g = float(g)
    b = float(b)
    high = max(r, g, b)
    low = min(r, g, b)
    h, s, v = high, high, high

    d = high - low
    s = 0 if high == 0 else d/high

    if high == low:
        h = 0.0
    else:
        h = {
            r: (g - b) / d + (6 if g < b else 0),
            g: (b - r) / d + 2,
            b: (r - g) / d + 4,
        }[high]
        h /= 6

return h, s, v

# COLOR YOU WANT TO TEST TESTED
check = "#808000".lstrip('#')
checkRGB = tuple(int(check[i:i+2], 16) for i in (0, 2 ,4))
checkHSV = rgb_to_hsv(checkRGB[0], checkRGB[1], checkRGB[2])

colorsRGB = {}
colorsHSV = {}

for c, v in colors.items():
    h = v.lstrip('#')
    colorsRGB[c] = tuple(int(h[i:i+2], 16) for i in (0, 2 ,4))

for c, v in colorsRGB.items():
    colorsHSV[c] = tuple(rgb_to_hsv(v[0], v[1], v[2]))

def colourdistanceRGB(color1, color2):
    r = float(color2[0] - color1[0])
    g = float(color2[1] - color1[1])
    b = float(color2[2] - color1[2])
    return math.sqrt( ((abs(r))**2) + ((abs(g))**2) + ((abs(b))**2) )

def colourdistanceHSV(color1, color2):
    dh = min(abs(color2[0]-color1[0]), 360-abs(color2[0]-color1[0])) / 180.0
    ds = abs(color2[1]-color1[1])
    dv = abs(color2[2]-color1[2]) / 255.0
    return math.sqrt(dh*dh+ds*ds+dv*dv)

resultRGB = {}
resultHSV = {}

for k, v in colorsRGB.items():
    resultRGB[k]=colourdistanceRGB(v, checkRGB)

for k,v in colorsHSV.items():
    resultHSV[k]=colourdistanceHSV(v, checkHSV)

#THIS WILL NOT WORK FOR GREY
print("RESULT WITH RGB FORMULA")
print(resultRGB)
print(min(resultRGB, key=resultRGB.get))

#THIS WILL WORK FOR EVEN GREY
print(resultHSV)
print(min(resultHSV, key=resultHSV.get))

#OUTPUT FOR RGB
#check = "#808000"  output=GREY
#check = "#4A7DAC"  output=GREY :D

#OUTPUT FOR RGB
#check = "#808000"  output=GREEN
#check = "#4A7DAC"  output=BLUE:D


Q: 'input' is not defined Pylance(reportUndefinedVariable)
it just started happening, now all "input()" gets yellow underline
But code works properly

A: a=int(input())

if u r keeping any integer values.

A: That happens because you are using input. Use raw_input instead. raw_input is what you have to use with python 2.

A: This problem does not occur in my pylance.
It seems that there are some errors in your vscode's pylance. It doesn't recognize the input() method.
You can try to update the pylance in the extension store or add the following code in settings.json:
  "python.analysis.diagnosticSeverityOverrides": {
    "reportUndefinedVariable": "none"
  }


Q: Check if NSAlert is currently showing up I am using an NSAlert to display error messages on the main screen of my app.
Basically, the NSAlert is a property of my main view controller
class ViewController: NSViewController {

    var alert: NSAlert?

    ...

}

And when I receive some notifications, I display some messages
func operationDidFail(notification: NSNotification)
{
    dispatch_async(dispatch_get_main_queue(), {

        self.alert = NSAlert()
        self.alert.messageText = "Operation failed"
        alert.runModal();
    })
}

Now, if I get several notifications, the alert shows up for every notification. I mean, it shows up with the first message, I click on "Ok", it disappears and then shows up again with the second message etc... Which is a normal behaviour.
What I would like to achieve is to avoid this sequence of error message. I actually only care about the first one.
Is there a way to know if my alert view is currently being displayed ?
Something like alert.isVisible as on iOS's UIAlertView ?

A: From your code, I suspect that notification is triggered in background thread. In this case, any checks that alert is visible right now will not help. Your code will not start subsequent block execution until first block will finish, because runModal method will block, running NSRunLoop in modal mode.
To fix your problem, you can introduce atomic bool property and check it before dispatch_async.
Objective-C solution:
- (void)operationDidFail:(NSNotification *)note {
    if (!self.alertDispatched) {
        self.alertDispatched = YES;
        dispatch_async(dispatch_get_main_queue(), ^{
            self.alert = [NSAlert new];
            self.alert.messageText = @"Operation failed";
            [self.alert runModal];
            self.alertDispatched = NO;
        });
    }
}

Same code using Swift:
func operationDidFail(notification: NSNotification)
{
    if !self.alertDispatched {
        self.alertDispatched = true
        dispatch_async(dispatch_get_main_queue(), {
            self.alert = NSAlert()
            self.alert.messageText = "Operation failed"
            self.alert.runModal();
            self.alertDispatched = false
        })
    }
}

A: Instead of run modal you could try
- beginSheetModalForWindow:completionHandler:

source: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSAlert_Class/#//apple_ref/occ/instm/NSAlert/beginSheetModalForWindow:completionHandler:
In the completion handler set the alert property to nil.
And only show the alert if the alert property is nil ( which would be every first time after dismissing the alert).
EDIT : I don't see the documentation say anything about any kind of flag you look for.


Q: Makefile and Bash script for C++ with command line arguments For my homework, I just wrote a c++ program that should supply a command line argument(e.g. -l) when you run it. Now, I need to compile and run my program in Unix. So, I need a makefile and a bash script(the name is cddb) to invoke my program.
My question is that the sequence of two files. The requirement is like I should enter cddb -l to run the program. So, is it like I should write a bash script which invokes the makefile and pass the argument to makefile. Then the makefile taken the argument and compile and run my cpp file?

A: The idea of command line arguments is to change the behaviour of your executable file at run time, so you don't need to re-compile your source code if you want slightly different behaviour.
Just call your program like ./cddb -l and parse the command line arguments in your source code. To parse the arguments you can use the argv and argc variables declared in the main function signature.


Q: How do I make window.onbeforeunload wait for animation? Consider the following JavaScript code, with an animation library (i.e. scriptaculous) to boot.
window.onbeforeunload = function(event) {
    document.body.fade();
}

Leaving the page is instantaneous and doesn't wait for the animation to complete. Even though everywhere I look people say JS doesn't support threads, something is running in parallel here, because it seems the one will not wait for the other. Am I right about the threads, and is there any way to achieve what I'm trying to do here?

A: A bit late but I think give an answer is interesting for futur SO users.
So there is multiple way to sync your code to this and so you should add a custom waiter.
window.onbeforeunload = function(event) {
    document.body.fade();
    while ((new Date()).getTime() < (new Date()).getTime()) + (1 *1000));
}

I guess you could also try with promises:
function sleep(time) {
  return new Promise((resolve) => {
    setTimeout(() => {
      return resolve(null);
    }, time);
  });
}

window.onbeforeunload = async function(event) {
    document.body.fade();
    await sleep(1 * 1000);
}


Q: Use plain mode to access kafka I have a Kafka cluster on OpenShift cloud, a customer outside of cloud send message to Kafka cluster, then we set authentication and authorization for Kafka cluster and topic, ans create an user.
Now from external customer can publish messages to kafka topic via SSL or SASL via port 9094, now app inside OpenShift want to consume messages via port 9092 with plain mode, that means, app inside OpenShift doesn't want to use any authentication or authorization to access that topic, do you think if it is possible?
This is my Kafka cluster listener
  kafka:
    authorization:
      type: simple
    listeners:
      external:
        authentication:
          type: tls
        port: 9094
        tls: true
        type: route
      plain:
        port: 9092
        tls: false
        type: internal


Q: Inheriting from bad template instantiations in C++ Consider the following code:
struct Foo
{
    Foo operator+(const Foo &rhs) const;
    // notice lack of: Foo operator*(const Foo &rhs) const;
};

template <class T>
struct Bar
{
    T x, y;
    T add() const { return x + y; }
    T mul() const { return x * y; }
};

I have two questions:

*

*Can I inherit from Bar<Foo> and override mul() to something meaningful?

*Can I inherit from Bar<Foo> without overriding mul() if I never use mul() anywhere?

A: *

*Bar<Foo>::mul() isn't a virtual function, so it cannot be overridden.

*Yes, if you don't use a template member function then it does not get instantiated and you don't get any errors that would result from instantiating it.
You can hide Bar<Foo>::mul() by providing a function of the same signature in a subclass, and because of 2, Bar<Foo>::mul() won't be instantiated. However this is probably not a good practice. Readers are likely to get confused about the hiding vs. overriding, and there's not much benefit to doing this over simply using a different function name and never using mul(), or providing an explicit specialization of Bar for Foo.

A: *

*sure

*sure

Templates are really a kind of smart preprocessor, they're not compiled. If you don't use something, you can write complete (syntactically correct) rubbish, i.e you may inherit from
template <class T>
struct Bar
{
    T x, y;
    T add() const { return x + y; }
    T mul() const { return x.who cares what-s in here; }
};

P.S. since your + operator is used in a const function, it should be declared as const too.
EDIT: OK, not all compilers support this, here's one that compiles with gcc:
template <class T>
struct Bar
{
    T x, y;
    T add() const { return x + y; }
    T mul() const { T::was_brillig & T::he::slith(y.toves).WTF?!0:-0; }
};


Q: How to send image in PHP mail function I want to send image in mail.How to add image so that it will show in the email
I want to add image to the CLIENT MESSAGE BODY.
How to use html in client message body?
Here is my code :
<?php
/* subject and email varialbles*/

$emailSbuject = 'Enquiry';
$webMaster = 'vivek@a.com';
$emailSbuject2 = 'Thank you';
$client = ' $emailFeild\r\n';
/*gathering data variables*/

$nameFeild = $_POST['name'];
$cityFeild = $_POST['city'];
$countryFeild = $_POST['country'];
$emailFeild = $_POST['email'];
$phoneFeild = $_POST['phone'];
$otherFeild = $_POST['other'];
$questionFeild = $_POST['question'];
$commentFeild = $_POST['comment'];
$phone1Feild = $_POST['phone1'];
$hear1Feild = $_POST['hear1'];
$hear2Feild = $_POST['hear2'];
$hear3Feild = $_POST['hear3'];
$hear4Feild = $_POST['hear4'];
$referralFeild = $_POST['referral'];
$otherhearFeild = $_POST['otherhear'];

// admin message body
$body= <<<EOD
Contact Form Details of $nameFeild

Name: $nameFeild \n
City: $cityFeild \n
Country: $countryFeild \n
Email: $emailFeild \n
Contact Phone: $phoneFeild \n
Other Phone: $otherFeild \n
Question: $questionFeild \n
Comment: $commentFeild \n
Contact Over: $phone1Feild \n
Known Us through: \n

 $hear1Feild
 $hear2Feild
 $hear3Feild
 $hear4Feild
 $referralFeild
 $otherhearFeild
EOD;
// Client message body
$body2 = <<<EOD

Dear $nameFeild

         Thank u for contacting IntaxFin. One of our representatives will contact you the     soonest. If you have more questions or information needed, please let us know. We are happy to serve     you! \n

        -From
         IntaxFin Team \n http://www.intaxfin.com \n

         Like us on Facebook \n
         Follow us on Twitter \n
         Connect with us on LinkedIn \n

-------------------------------------------------------------------------------------------------                     e-mail was automatically sent by IntaxFin Administration Directory and is for your reference. Please do not reply to this e-mail address.

Powered by HexCode Technologies Pvt. Ltd.

EOD;
    $headers = "From: $emailFeild\r\n";
    $header = "From: $noreply@intaxfin.com\r\n";
    $success = mail($webMaster,$emailSbuject,$body,$headers);
    $success1 = @mail($emailFeild,$emailSbuject2,$body2,$header);
    /*Result*/

    $theResults = <<<EOD
EOD;

echo  "$theResults";

header("Location: http://www.intaxfin.com/thankyou.html");
exit;
?>

A: You cannot display images on text/plain emails as shown above. You must send it as text/html.
So you first have to extend your headers like this:
$header = "From: $noreply@intaxfin.com\nMIME-Version: 1.0\nContent-Type: text/html; charset=utf-8\n";

Then you must update your mailcontent replacing \n or linebreaks with html tags
 or even

Then you also can include image tags having the image you want to show in the email

This will be downloaded from your webserver when recipient opens it.
.
BUT the much better way will be to use phpMailer Class
Using this, you will be able to include any images IN your email, without need to download it from any website. It is easy to learn and absolutely customizable.
By the way: You should use quotation marks for your $body and $body2 values...
$body= "<<<EOD
Contact Form Details of $nameFeild

Name: $nameFeild \n
City: $cityFeild \n
Country: $countryFeild \n"

A: $headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

$message = "
<title>Your email at the time</title>

"
mail($email_to, $email_subject , $message,$headers);


Q: C# prefixing parameter names with @
Possible Duplicate:
What does the @ symbol before a variable name mean in C#?
Duplicate:
What does the @ symbol before a variable name mean in C#?

Sometimes I see some C# code where a method-parameter is prefixed with an @, like this:
public static void SomeStaticMethod( SomeType @parameterName ) { }

What is the meaning of this ?  Does it has some significant special meaning ?
I am creating an EventListener in NHibernate, and when I let VS.NET generate the interface methods, it generates the OnPostLoad method like this:
public class PostLoadEventListener : IPostLoadEventListener
{
    public void OnPostLoad( PostLoadEvent @event )
    {

    }
}

Why is this ?

A: The @ prefix allows you to use reserved words like class, interface, events, etc as variable names in C#. So you can do
int @int = 1

A: event is a C# keyword, the @ is an escape character that allows you to use a keyword as a variable name.

A: Try and make a variable named class and see what happens -- You'll notice you get an error.
This lets you used reserved words as variable names.
Unrelated, you'll also notice strings prefixed with @ as well -- This isn't the same thing...
string says = @"He said ""This literal string lets me use \ normally
    and even line breaks"".";

This allows you to use 'literal' value of the string, meaning you can have new lines or characters without escapes, etc...


Q: How to combine and if statement with a formula to concatenate? Trying to combine two formulas together but can't figure out how to get them to work. The concatenate formula is
=IF(OR(UPPER(D6)="",UPPER(D6)="N"),A6,A6&" - "&D6)

The formula was created so that if "Y" was entered in a checkbox (yes), then it would combine two different parts to create a result in a separate box. If "N" is entered then it would not concatenate.
The formula was originally
=IF(OR((AND((A6<>""),(D6<>""))),(AND((B6<>""),(D6<>"")))),IF(A6="",B6,A6),"")

I'm trying to figure out how to put a concatenate formula somewhere in this one, haven't had any luck so far.. Thank you.

A: Most Excel worksheet formulas are not case sensitive, so you don't need UPPER().
Your original formula has a logic error. It can only return TRUE if A is NOT blank. But in the TRUE part, you have another IF statement that is only TRUE if A6 is blank. That situation never happens.
How complicated the formula will be depends on what the logic is. If the result should always be one thing for "n" or a blank input, and another thing for a "y" input, maybe you only need to test for "y" instead of testing for "" and "n".
=if(and(A1="y",B1="y"),X&" - "&Y,X)

If that does not answer your question, please edit your question, provide a data sample and the desired result and explain the logic. Then post a comment, so people get alerted about the update.


Q: Javascript - Regex/replace optimization I have a script which allows to replace undesired HTML tags and escape quotes to "improve" security and prevent mainly script tag and onload injection, etc.... This script is used to "texturize" content retrieved from innerHTML.
However, it multiples near by 3 my execution time (in a loop). I would like to know if there is a better way or better regex to do it:
function safe_content( text ) {

    text = text.replace( /<script[^>]*>.*?<\/script>/gi, '' );
    text = text.replace( /(<p[^>]*>|<\/p>)/g, '' );
    text = text.replace( /'/g, '’' ).replace( /'/g, '’' ).replace( /[\u2019]/g, '’' );
    text = text.replace( /"/g, '”' ).replace( /"/g, '”' ).replace( /"/g, '”' ).replace( /[\u201D]/g, '”' );
    text = text.replace( /([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g, '$1="$2"' );
    return text.trim();

};

EDIT: here a fiddle: https://fiddle.jshell.net/srnoe3s4/1/. Fiddle don't like script tags in javascript string apparently so I didn't add it.

A: I'll just deal with performance and naive security checks since writing a sanitizer is not something you can do on the corner of a table. If you want to save time, avoid calling multiple times replace() if you replace with the same value, which leads you to this:
function safe_content( text ) {
    text = text.replace( /<script[^>]*>.*?<\/script>|(<\/?p[^>]*>)/gi, '' );
    text = text.replace( /'|'|[\u2019]/g, '’');
    text = text.replace( /"|"|"|[\u201D]/g, '”' )
    text = text.replace( /([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g, '$1="$2"' );
    return text.trim();
};

If you take into account dan1111's comment about weird string input that will break this implementation, you can add while(/foo/.test(input)) to avoid the issue:
function safe_content( text ) {
    while(/<script[^>]*>.*?<\/script>|(<\/?p[^>]*>)/gi.test(text))
        text = text.replace( /<script[^>]*>.*?<\/script>|(<\/?p[^>]*>)/gi, '' );
    while(/'|'|[\u2019]/g.test(text))
        text = text.replace( /'|'|[\u2019]/g, '’');
    while(/"|"|"|[\u201D]/g.test(text))
        text = text.replace( /"|"|"|[\u201D]/g, '”' )
    while(/([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g.test(text))
        text = text.replace( /([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g, '$1="$2"' );
    return text.trim();
};

in standard tests cases, this will not be a lot slower than the previous code. But if the input enter in the scope of dan1111's comment, it might be slower. See perf demo


Q: Spring Boot SAML 2.0 support I’m implementing sample application which is supposed to combine SAML 2.0, Oauth 2.0 and UMA 2.0. I’ve generated Spring Boot template using initializr.
I’m stuck at the beginning by saml2ogin(). It looks like SAML 2.0 support is missed. RelyingPartyRegistrationRepository is not available. When I browse imports in HttpSecurity class, I have org.springframework.security.saml2 – Cannot resolve symbol “saml2”.
According to the documentation:
https://docs.spring.io/spring-security/site/docs/5.3.x/reference/html5/
SAML 2.0 support should by bundled in spring-boot-starter-security
Have I missed something?
My build.gradle:
plugins {
    id 'org.springframework.boot' version '2.2.6.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    testImplementation 'org.springframework.security:spring-security-test'
}

test {
    useJUnitPlatform()
}

A: implementation 'org.springframework.security:spring-security-saml2-service-provider'

As far as I can tell that dependency is marked as optional, so it has to be included explicitly.
https://github.com/spring-projects/spring-security/blob/master/config/spring-security-config.gradle


Q: Modifying XML file, replacement elements I were trying use those code to Modify XML files in C#.
    XDocument doc = XDocument.Load(@"movies.xml");
    String target = textBox1.Text;

    var node = doc.Descendants("movie").FirstOrDefault(movie => movie.Element("title").Value == target);

    node.SetElementValue("title", this.textBox1.Text);
    node.SetElementValue("year", this.comboBox1.Text);

    Console.WriteLine(node);
    doc.Save(@"movies.xml");

the problem is: when I change 'year' element, everything works perfectly. However, when I change the title which I used as a keyword to search in XML file. The code does not do it in this way. Return a NULL error.
My XML file:
<movielist>
  <movie>
    <title>a movie name</title>
    <year>2015</year>
  </movie>
  <movie>
    <title>Another movie name</title>
    <year>2000</year>
  </movie>
</movielist>

How can I fix it?

A: Ok, I fixed.  String target should be out of the function( like put it in main). If not, It will always overwritten.


Q: twitter bootstrap layout strange behaviour I have a strange behaviour in screen layout, I do not understand the possible cause:(
I have a vertical grey line on the left and the right of the screen,
See screenshot here:

BTW, I developed using Rails 3 and using Twitter Bootstrap 2.3.2
In facts I do not foresee / I do not want these lines ... I presume it could be some CSS setting (on my one customization css code...), sorry for my ignorance there,
watching the shot here do suggest you something about why the grey vertical line on the left marging and the right margin of the screen layout ?
thanks a lot
giorgio
scss customization file used: http://solyaris4.altervista.org/custom.css.scss

A: Without looking at any CSS and HTML code it is pretty difficult to tell.
But since it looks like you are using the Google Chrome browser, hover over the grey stripe with your mouse, right-click and select Inspect Element.  You can then review the html and css code related to what you are looking at.  You can also open the Chrome dev console at any time by hitting the CTRL-SHIFT-i keys.


Q: How to add a dynamic button in an external java class? I am having problems with creating public void onCreate(Bundle SavedInstanceState) in another java class.For this reason i cant create a dynamic button in java.I don't know what to do..
this is my java class
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback
{
    public static final int WIDTH = 856;
    public static final int HEIGHT = 480;
    public static final int MOVESPEED = -5;
    private long smokeStartTime;
    private long missileStartTime;
    private MainThread thread;
    private Background bg;
    private Player player;
    private ArrayList<Smokepuff> smoke;
    private ArrayList<Missile> missiles;
    private ArrayList<TopBorder> topborder;
    private ArrayList<BotBorder> botborder;
    private Random rand = new Random();
    private int maxBorderHeight;
    private int minBorderHeight;
    private boolean topDown = true;
    private boolean botDown = true;
    private boolean newGameCreated;

    public void onCreate(Bundle SavedInstanceState) {
        super.onCreate(SavedInstanceState);
    }

this is my main java which has contentView of this java class..
public class Game extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //turn title off
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        //set to full screen
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(new GamePanel(this));

    }

Please help me to find a solution and create a dynamic button in the GamePanel java class.

A:  //in your activity add this for button
    LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);

    //set the properties for button
    Button btnTag = new Button(this);
    btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    btnTag.setText("Button");
    btnTag.setId(some_random_id);

    //add button to the layout
    layout.addView(btnTag);


Q: How to determine first and last call of module scoped fixture within session? I have a module scoped fixture that requires to know if it is called for the first or for the last time within a session, is there a way to get this information within fixture?
This is required for managing lifecycle of a shared resource that depends on module scoped options which basically should look like this:
@pytest.fixture(scope='module', autouse=True)
def module_runner():

    if not session_start and resource_reload_condition:
        shared_resource.dispatch()

    shared_resource.set_module_level_options()

    if resource_reload_condition:
        shared_resource.provision()

    yield

    if resource_reload_condition:
        shared_resource.dispatch()

    shared_resource.rollback_module_level_options()

    if not session_end and resource_reload_condition:
        shared_resource.provision()


Q: How to detect Web Cam is attached or not Using java How to detect whether the Web cam is attached to computer or not by using Java?

A: JMF (Java Media Framework) should be able to detect any media, including a webcam.
Potentially through CaptureDeviceManager.getDeviceList();

For "installing JMF on Linux", one way is simply to:

*

*download it.

*Change directories to the install location.

*Run the command

:
  % /bin/sh ./jmf-2_1_1e-linux-i586.bin

A: Here is a piece of code I use in a simple Webcam client with JMF:
Format format = new RGBFormat();
MediaLocator cameraLocator = null;
// get device list
Vector deviceList = CaptureDeviceManager.getDeviceList(format);
// if devices available
if(deviceList != null && deviceList.size() > 0) {
  // pick first
  CaptureDeviceInfo device = (CaptureDeviceInfo) deviceList.get(0);
  cameraLocator = device.getLocator();
}

It picks the first available webcam. Of course, after having the webcam you can store the cameraLocator and try to re-open it on the 2nd run.


Q: Angular JS, scope updates in Async callback I've got a series of 2 AJAX requests, with the latter depending on the results of the first. I've put them into the promise of the first returned object. ie.
var productResource = $resource('http://urlhere');
$scope.product = productResource.get();

$scope.product.$promise.then(function(data) {

    var depResource = $resource('http://deps/' + data.code );
    $scope.deps = depResource.get();

    $scope.$apply();

});

I can see the resource is hit with the appropriate data pulled down in my network tab, but my HTML is not updated. I've just got it within {{ }} brackets to see the results. ie.
Prod -  {{ product }}
Deps -  {{ deps }}

product resolves the product recieved, but deps remain blank. Why is this?

A: you don't need to $apply since everything is inside the angular event loop what you need is not to destroy the reference to your binding by reassigning the product object.
when you linked your html product either didn't existed or was pointing to an mem address.
when you did
$scope.product = productResource.get();

you reassigned that variable to a different address so the binding was broken. but your html was not rebinded to the new address, this is more likely your problem, you can try making the variable null before reassigning it, not sure thats going to work, or  you could make products initially an empty object and then extend it with
productResource.get();


Q: Destroy a session I Want to destroy a session in my project such that when I click on Logout, it goes to a page "KillSession.jsp" , in that file I've written "session.invalidate();" and then I redirect the user to the Login page.
But if I use the back button on my browser, it goes back to the page I have visited before even when I've logged out.
What to do?

A: Your browser caches it, You need to add header to force your browser not to force it

A: Make sure that you don't cache the last page before you log out. You could do something like:
response.setHeader("Cache-Control","no-cache,no-store,must-revalidate");
response.setHeader("Pragma","no-cache");
response.setDateHeader("Expires", 0);