Q:

Multiple QWidets into one QMainWindow

I am currently learing Qt, and I am stuck on the problem of using multiple QWidgets and one QMainWindow.
I have setup a project which contains 2 QWidgets and one QMainWindow. This is my idea of using it: design both QWidgets as needed, add them to the mainwindow object, connect the buttons to the correct slots and switch the centerwidget when needed. So I started off with one QMainWindow and then added two QWidgets, including the cpp file, the h file and the ui file. On both QWidgets I added one QPushButton, and called it pushButtonConvert.
Then I went to the cpp file attached to the QMainWindow (mainwindow.cpp) and did the following:
EpochToHuman * epochToHuman = new EpochToHuman();
HumanToEpoch * humanToEpoch = new HumanToEpoch();

Up until this point everything is fine. Now I want to connect the buttons to slots in the mainwindow object, but I can not find the buttons. epochToHuman->pushButtonConvert does not seem to exist, and I can not find any other way to get to the buttons. So am I thinking in a way that is not correct, according to Qt or am I missing something?
Another try at clarifying what I want:
I want to use the elements in a QWidget in QMainWindows' cpp file. I want to be able to do things like this:
//In object MainWindow.cpp
QWidget * a = new QWidget
//Let's say a is a custom widget with a label in it. This label is called Label
a->Label->setText("Hello, World!");
//This gives an error because a does not have a member called Label
//How can I change the text on the label of a?
//And I think if I will be able to change the text of this label, I will also be able to dance around with buttons as needed.

A:

You can connect the pushButtonConvert button to MainWindow::convertFromEpochToHuman in the constructor of MainWindow, with:
connect(epochToHuman->ui->pushButtonConvert, SIGNAL(clicked(bool)), this, SLOT(convertFromEpochToHuman()));

You'll need to make the ui member public first, like you have done for HumanToEpoch.
You should move the declaration of your widgets into MainWindow.h:
// ...
private:
    Ui::MainWindow *ui;

    EpochToHuman * epochToHuman;
    HumanToEpoch * humanToEpoch;
 // ...

and initialise them like this:
epochToHuman = new EpochToHuman(this);
humanToEpoch = new HumanToEpoch(this);


Q:

Disable / uncheck checkbox in GridView (DevExpress)

Is there any way to programmatically uncheck or disable row's checkbox (just for a few, based on condition) in DevExpress.XtraGrid.Views.Grid.GridView?
GridView is binded with BindingSource. If you need any other informations, just ask. I recieve a project with DevExpress but no experience with it so sorry if my question is silly.
Thank you for your help.

A:

This is a solution I've found.
private void GridView_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
{
    if (<some condition>)
        e.Cancel = true;

}

More info here.


Q:

Proving a simple assertion in Propositional Logic

I have to prove some Propositional Logic assertions.
Given this one: $\alpha \models \beta \Leftrightarrow (\alpha \Rightarrow \beta)$ is valid
Where $\models$ is entailment
The answer is: $\alpha \Rightarrow \beta$ holds in those models where $\beta$ holds or where $\neg\alpha$ holds. This is precisely the case if $\alpha \Rightarrow \beta$ is valid.
I don't understand this answer. Could someone clarify it for me. I don't know what holds means in this context. English is not my first language.
I know that a sentence to be valid needs to be True in all models. Also that $\alpha \models \beta \Leftrightarrow$ in every model in which $\alpha$ is true, $\beta$ is also true.
Thanks

A:

You can think of the phrase "[insert something here] holds" as "[that same something] is [insert property here]". More concretely, "holds" in this context is a sort of expression that refers to some thing "holding true" or always having the property of being true.
So, when we say $\alpha \Rightarrow \beta$ holds, we mean that $\alpha \Rightarrow \beta$ is in fact true.


Q:

Magento contact form customizations

I'm trying to add a couple fields to the contact form so that my customers can indicate the year make and model of their vehicle when writing.
I have just upgraded my Magento installation from 1.4.3 to 1.7.0.1. My previous contact form was a hack job and this time I'm trying to get it working the right way. Reading all around, I tried adding <input type="text" size="15" value="" id="model_ext" name="bike_model_ext" class="required-entry input-text"> to the form.phtml in my template and then in the transaction email template in admin, {{var data.model_ext}}. But that doesn't work. I ensured that the template in the back end is correct by manipulating the text. I also know the form.phtml is correct, as I see elements when they change.
So then I overloaded the controller handling the contact form. I confirmed my controller is handling it (it came with a echo "it works"; die();) And in there, I'm looking for the POST data of the extra form element names, but here, too, I'm having troubles getting access to the data. Looking around the net, I tried this:
            $comment = $this->getRequest()->getPost('comment');
            $extras=Array( "year","make","model","model_ext" );
            foreach($extras as $field)
                    $comment .= "\n$field:\t".$this->getRequest()->getPost($field);
            $this->getRequest()->setParam('comment', $comment);
            parent::postAction();

But again, it is like my variables do not exist. Here, again, I know my code is being executed, because when I get anything wrong in there, the contact form crashes to an error message.
I'll be on it again in the morning, but hope that there is something easy I'm missing that someone here with more experience can help me with.
EDIT: ANSWERED I was using the ID to key in for the variables, needs to instead be the name.

A:

An answer for those interested by this fix.
The $_POST and $_GET value generated by a form use name and not id.
In this situation you have to use bike_model_ext instead of model_ext.
Kind Regards,


Q:

::ng-deep angular 6 style pierce ngx-chips tag-input component

Having major trouble trying to change simple style properties of this ngx-chips tags input component.
Looked up the documentation to find out that I have to do :ng-deep to the tags to change the styling https://github.com/gbuomprisco/ngx-chips/blob/master/docs/custom-themes.md
Problem is, their suggestion did not work.
Realized that the right way to use this method is ::ng-deep, not :ng-deep. But that still did not work.
I was able to go to my browser and directly change my styling, but can't seem to do this with my scss code.
Here is my scss styling:
// apply theme to the tags
::ng-deep .ng2-tag-input.bootstrap tag {
   align-items: center !important;
   background: #63c2de !important;
}

Here are the tags associated to the ngx-chips component
      <tag-input formControlName="tags" theme="bootstrap">
        <tag-input-dropdown [autocompleteItems]="uniqueTags" [matchingFn]="matchingFn">
        </tag-input-dropdown>
      </tag-input>

A:

As a look in you scss you have used this ...
::ng-deep .ng2-tag-input.bootstrap tag { ... }

In you code you haven't give any class. Please check that. If all the thing is right then try this also.
:host ::ng-deep .ng2-tag-input.bootstrap tag { ... }

Hear you should use :host to apply your css.
Note: :host will work on that component only in which you have used :host.


Q:

Read Control DropDownList from View Within the View

VS '12 asp.net C# mvc Internet App + Kendo UI , EF Code First, Kendo UI
Using Kendo DDL
 @(Html.Kendo().DropDownList()
          .Name("dropdownlist")
          .BindTo(new string[] { "Leasehold A", "Mineral Owner", "Prospect", "StrangerInTitleNote", "StrangerInTitleNoteInfo", "StrangerLeasingNote", "StrangerLeasingNoteInfo", "Subject To", "Surface Note", "Surface Note Info", "Unreleased Mortage", "Unreleased Oil and Gas Leasors", "Vesting Note" })
          )

Very simple right? - now i want to extract the selected Item and place it into an Actionlink
@Html.ActionLink("Create New", "Create", new { id =  } )', null) ....

what do I place at the id= spot. How can I get this to work. Thanks for any answers.
PS: Not familiar with MVC to much or any HTML so far, must I use a Script? - preferably I would like to not leave the view.

A:

I do it like this. May not be the best but it works for me.
Here is the link:
@Html.ActionLink("Click Me", "YourAction", new { controller = "YourController"}, new       {id="YourActionLinkName"})

The .click function
$('#YourActionLinkName').click(function (e) {

            var val = $("#dropdownlist").val();
            var href = "/YourApp/YourController/YourAction/" + val;
            this.href = ""; //clears out old href for reuse
            this.href = href; //changes href value to currently slected dropdown value

        });


Q:

Combine 2 JavaScript into 1

I'm doing a clean up for a Webscrape.
This is my current script.
var cleanup = function(results) {
 $.each(results, function(){
  this.values[0] = this.values[0].replace("Submission date: ",
  "").split(" ")[0];
    this.values[1] = this.values[1].replace("Case number: ", "");
 });
  return results;
  };

I've then found out that I need to add
  var d = "2010-10-30".slice(0, 10).split('-');
  d[1] +'/'+ d[2] +'/'+ d[0]; // 10/30/2010

in order to change the way the data is written. My current output is YYYY-MM-DD that needs to be MM/DD/YYYY
I'm having difficulties combining the 2 scripts to get the desired functions.

A:

If this.values[0] is the property in question and contains a date value in the form YYYY-MM-DD now (after the line that removed the Submission date: text), then it should be as simple as this:
 // take the date value from the field & split it
 var d = this.values[0].slice(0, 10).split('-');
 // assign the parts in new order and concatenated with the separator / back to the field
 this.values[0] = d[1] +'/'+ d[2] +'/'+ d[0];


Q:

Example of group $G$ such that $Z(G)={1}$ but $Z(H)\ne {1}$ for some $H\leq G$

I'm trying to think of an example of a group $G$ such that $Z(G)={1}$ but $Z(H)\ne {1}$ for some $H\leq G$.
I've been trying to work with $S_n$ since its center is trivial but I can't find a suitable subgroup. Is there an obvious one in $S_n$?
If not, what would be an example?

A:

The center of any cyclic subgroup would be the whole cyclic subgroup since cyclic groups are abelian, so $H=\langle (1 \ 2 \ 3 \ \ldots n)\rangle$ would work for instance.


Q:

Get application/ld+json from external url using php

from this  application/ld+json i want to get example 1.genre, 2.director, 3.dateCreated, 4.duration, 5.uploadDate
 <script type="application/ld+json">{
      "@context": "http://schema.org",
      "@type": "Movie",
      "url": "/title/tt2293640/",
      "name": "Minions",
      "image": "https://m.media-amazon.com/images/M/MV5BMTg2MTMyMzU0M15BMl5BanBnXkFtZTgwOTU3ODk4NTE@._V1_.jpg",
      "genre": [
        "Animation",
        "Action",
        "Adventure",
        "Comedy",
        "Family"
      ],
      "contentRating": "PG",
      "actor": [
        {
          "@type": "Person",
          "url": "/name/nm0000113/",
          "name": "Sandra Bullock"
        },
        {
          "@type": "Person",
          "url": "/name/nm0358316/",
          "name": "Jon Hamm"
        },
        {
          "@type": "Person",
          "url": "/name/nm0000474/",
          "name": "Michael Keaton"
        },
        {
          "@type": "Person",
          "url": "/name/nm1853544/",
          "name": "Pierre Coffin"
        }
      ],
      "director": [
        {
          "@type": "Person",
          "url": "/name/nm0049633/",
          "name": "Kyle Balda"
        },
        {
          "@type": "Person",
          "url": "/name/nm1853544/",
          "name": "Pierre Coffin"
        }
      ],
      "creator": [
        {
          "@type": "Person",
          "url": "/name/nm0528244/",
          "name": "Brian Lynch"
        },
        {
          "@type": "Organization",
          "url": "/company/co0221986/"
        },
        {
          "@type": "Organization",
          "url": "/company/co0005073/"
        }
      ],
      "description": "Minions is a movie starring Sandra Bullock, Jon Hamm, and Michael Keaton. Minions Stuart, Kevin, and Bob are recruited by Scarlet Overkill, a supervillain who, alongside her inventor husband Herb, hatches a plot to take over the...",
      "datePublished": "2015-06-17",
      "keywords": "minion,super villain,villain,invented language,teddy bear",
      "aggregateRating": {
        "@type": "AggregateRating",
        "ratingCount": 188589,
        "bestRating": "10.0",
        "worstRating": "1.0",
        "ratingValue": "6.4"
      },
      "review": {
        "@type": "Review",
        "itemReviewed": {
          "@type": "CreativeWork",
          "url": "/title/tt2293640/"
        },
        "author": {
          "@type": "Person",
          "name": "flint1961"
        },
        "dateCreated": "2015-06-27",
        "inLanguage": "English",
        "name": "Below par money spinner",
        "reviewBody": "I don\u0027t usually write reviews but this was such a disappointment that I felt I had to put something. Most of the good jokes were shown in the trailers, so if you\u0027ve seen the trailer then it\u0027s probably not worth the money. There were 3 of us watched this and although we all loved the despicable movies none of us enjoyed this. My son (11) said it felt like it was 2 hours long it was so boring. I can\u0027t really explain why it came across as so poor - but it just seemed really lazy and without Gru to play against the Minnions were just to simple. It was slapstick with no soul. The music although quite good didn\u0027t really seem to fit the film - just seemed to be tacked on at bit were they felt they should have a soundtrack and a famous song. Buy yourself a copy of despicable me and watch it again and again. Much better value for money! This just felt rushed, with loads of stock jokes, maybe hoping enough of them would hit the mark - they didn\u0027t.",
        "reviewRating": {
          "@type": "Rating",
          "worstRating": "1",
          "bestRating": "10",
          "ratingValue": "4"
        }
      },
      "duration": "PT1H31M",
      "trailer": {
        "@type": "VideoObject",
        "name": "Stuart \u0026 Dave",
        "embedUrl": "/video/imdb/vi996454425",
        "thumbnail": {
          "@type": "ImageObject",
          "contentUrl": "https://m.media-amazon.com/images/M/MV5BMTgxMzc2OTQwOV5BMl5BanBnXkFtZTgwODQ2OTgwNjE@._V1_.jpg"
        },
        "thumbnailUrl": "https://m.media-amazon.com/images/M/MV5BMTgxMzc2OTQwOV5BMl5BanBnXkFtZTgwODQ2OTgwNjE@._V1_.jpg",
        "description": "Watch an exclusive video for Minions.",
        "uploadDate": "2015-06-26T17:14:58Z"
      }
    }</script>

to get meta tag im using this code
$c = file_get_contents("https://www.imdb.com/title/$id");
$d = new DomDocument();
$d->loadHTML($c);
$xp = new domxpath($d);
foreach ($xp->query("//meta[@property='og:title']") as $ti) {
    $imdbTitle = $ti->getAttribute("content");
}
foreach ($xp->query("//meta[@property='og:image']") as $im) {
    $imdbImg = $im->getAttribute("content");
}
foreach ($xp->query("//meta[@property='og:description']") as $ode) {
    $imdbDes = $ode->getAttribute("content");
}

from this php code I want to get and 1.genre, 2.director, 3.dateCreated, 4.duration, 5.uploadDate from JSON (application/ld+json) how i can do this? some help  thanks you.

A:

You have a JSON data into a HTML page.
So you have to
1) retrieve the JSON data only
2) parse the JSON and process it
$id = 'tt0159365' ; // example id
$c = file_get_contents("https://www.imdb.com/title/$id");

// retrieve the JSON data
$d = new DomDocument();
@$d->loadHTML($c);

// parse the HTML to retrieve the "ld+json" only
$xp = new domxpath($d);
$jsonScripts = $xp->query( '//script[@type="application/ld+json"]' );
$json = trim( $jsonScripts->item(0)->nodeValue ); // get the first script only (it should be unique anyway)

// decode the JSON string we find into a associative array
$data = json_decode( $json, true );

// you can now use this array to query the data you want
$duration = $data['duration'];
echo "Duration: $duration" ;

$director = $data['director']['name'] ;
echo "Director : $director" ;


Q:

Display Custom Boolean Value in Angular ui-grid

Ok, I'm new to angular and angular ui-grid.
I'm using angularjs(v1.4) with angular-ui-grid(v3.0.7).
I have defined a grid as below
seec.gridOptions = {};
  seec.gridOptions.rowEditWaitInterval = -1;
  seec.gridOptions.onRegisterApi = function (gridApi) {
    $scope.gridApi = gridApi;
    gridApi.rowEdit.on.saveRow($scope, $scope.saveRow);
  };

seec.gridOptions.columnDefs = [
    {name: 'pouch', displayName: 'Pouch', enableCellEdit: false, enableHiding: false, width: 250},
    {name: 'content', displayName: 'Content', enableHiding: false, width: 150},
    {
      name: 'units',
      displayName: 'Number of Items',
      type: 'number',
      enableHiding: false,
      width: 150
    },
    {name: 'active', displayName: 'Status', type: 'boolean', enableHiding: false, width: 150}
  ];

The controller basically makes a http call and feeds data to the grid.
if (response.status === 200) {
    seec.gridOptions.data = angular.copy(seec.data);
}

Currently, the last item in the grid is being displayed as either 'true' or 'false' based on the boolean field value., and when I double click on the field a checkbox appears.
So, I need to display true as 'active' and false as 'inactive'.
Is there any way of doing this with angular ui-grid?

A:

There certainly is! One approach could be to use a cellTemplate and map your rowvalues to something different.
I created a Plunkr showcasing a possible setup.
There are two steps to take. First add a cellTemplate to your column:
cellTemplate: "

"

Note: Instead of ng-bind you could also use "
{{grid.appScope.mapValue(row)}}
", if you are more familiar with that.
Second step is to define your mapping function, for example:
appScopeProvider: {
  mapValue: function(row) {
    // console.log(row);
    return row.entity.active ? 'active' : 'inactive';
  },
}


Q:

How to create boxes with description fields

I'm currently having a small problem with some CSS/JS logic around creating a box inside-ish of a box. JsFiddle example : https://jsfiddle.net/pa7wt2g3/
I want to create 1 box and upon clicking the box, create a description field under it. however currently the description fields are all appering inside the first box when making additional boxes.
I suspect I have to give every box an uniqe ID which is later used to specifiy where to put the description area, but how do I go about this?

function textarea() { // Toggles dropdown and sets the dropdown and textfield as the same width as the created div
  document.getElementById('dropdown').classList.toggle("show");
  style = window.getComputedStyle(crtdiv);
  wdt = style.getPropertyValue('width');
  dropdown.style.width = wdt;
}

  document.getElementById("läggatill").onclick = function () { // Run function when läggatill is clicked
  var div = document.createElement('div'); // create div element
  div.className = 'newrect'; // apply css
  div.setAttribute("id", "crtdiv");

  var button = document.createElement('button'); // create button element
  button.setAttribute("id", "hej"); // Giving an id
  var buttontext = document.createTextNode("X"); // Sets the button value
  button.appendChild(buttontext); // Shows the value of the button
  button.className = 'hej'; // apply css
  button.setAttribute("onClick", "removeDiv(this)"); // runs the removeDiv funtion

  var dropdown = document.createElement('dropdown'); // create dropdown element
  dropdown.setAttribute("id", "dropdown"); // Giving an id
  dropdown.className = 'dropdown'; //apply css
  div.setAttribute("onClick","textarea()"); // Run textarea funtion

  var ptext = document.createElement('p'); // create p element
  var textnode = document.createTextNode("Add description"); // Sets the innerText of the p element
  ptext.appendChild(textnode); // Shows the InnerText
  ptext.className = 'text'; // apply css
  ptext.setAttribute("id", "text"); // Giving an id

  var textfield = document.createElement('Textarea'); // create textarea element
  textfield.className = 'autoExpand'; // apply css
  textfield.setAttribute("id", "textfield"); // Giving an id

  var text = document.getElementById("myText").value; //take the value of the text field
  div.innerHTML = text; // show text in the div
  if (text === "") { // Shows every element if the textfield has text in it
      return 0; // Returns nothing if the text field is empty
  } else {
      document.getElementsByTagName('span')[0].appendChild(div).appendChild(button);
      document.getElementsByTagName('span')[0].appendChild(dropdown);
      document.getElementsByClassName('dropdown')[0].appendChild(ptext);
      document.getElementsByClassName('dropdown')[0].appendChild(textfield);
  }
};
function removeDiv(elem) { // Removes div when pressing the button
  $(elem).parent('div').remove();
}
/* Start of lägga till kompetens */

.newrect {
  min-width: 55px;
  max-width: 195px;
  margin-top: 1%;
  margin-right: 1%;
  margin-left: 1%;
  margin-bottom: 0%;
  padding: 1% 3%;
  border: 1px solid green;
  border-radius: 40px;
  text-align: center;
  float: left;
  position: relative;
  background-color: white;
  z-index: 2;
  cursor: pointer;
}

.dropdown {
  display: none;
  background-color: darkgrey;
  height: 400px;
  position: absolute !important;
  margin-top: 3%;
  margin-right: 0%;
  margin-left: 0.96%;
  margin-bottom: 0%;
  z-index: 1;
}

.show {
  display: block;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

          <input id="myText" type="text" class="skriv" name="Kompetenser" autocomplete="off" autofocus>
          <input id="läggatill" class="läggatill" type="button" value="Add box">

A:

You're correct - all IDs must be unique. In order to achieve this, you'll have to refactor a large portion of your code. For example, the textarea function is triggered by clicking on the added boxes - that's fine. The problem is that the function isn't aware of which box was actually clicked - it refers to an element with a fixed ID "dropdown". Since there are multiple elements with the same ID, it has no way of knowing which box needs to be expanded.
You could simply pass this as an argument to this function and refer to the context, but then you'd have to account for the fact that you're using a global variable dropbox declared outside of the function's scope.
I've rewritten the whole thing. That's how I would implement this feature. I saw you're using jQuery in a few lines, hence my code largely depends on it. If you can't use jQuery in your final project, let me know, I'll post a version in pure vanilla JS. I also had to make some tiny CSS changes (flexbox).
Fiddle: https://jsfiddle.net/zLm2x5k6/
Snippet:

$(document).ready(() => {
    //You can use IDs here because these elements are unique
    const $addBtn = $("#läggatill");
    const $inputBox = $("#myText");
    const $flexBox = $("#flexbox");

    $addBtn.click(() => {
        //Creating a new box that contains everything we need and saving it to a variable
        //I'm using ES6 template strings to embed the value of $inputBox
        const $box = $(`

                    ${$inputBox.val()}
                    <button class="hej">X</button>

Add description

                <textarea class="autoExpand"></textarea>

        `);
        //Adding event listeneres for the box elements
        $box.find(".hej").click(function () {
            //Removing the parent .box wrapper DIV
            $(this).closest(".box").remove();
        });
        $box.find(".newrect").click(() => {
            const $dropdown = $box.find(".dropdown");
            //If the dropdown is invisible, show it. Otherwise, hide it
            if ($dropdown.css("display") === "none") {
                $box.find(".dropdown").show();
            } else {
                $box.find(".dropdown").hide();
            }
        });

        //Appending the box to the flexBox
        $box.appendTo($flexBox);
    });
});
html, body { /* So you can adjust height */
  height: 100%;
  margin: 0;
  padding: 0;
}

/* Start of lägga till kompetens */

.newrect {
  min-width: 105px;
  max-width: 195px;
  margin-top: 1%;
  margin-right: 1%;
  margin-left: 1%;
  margin-bottom: 0%;
  padding: 5px 10px 5px 10px;
  border: 1px solid green;
  border-radius: 40px;
  text-align: center;
  background-color: white;
  z-index: 2;
  cursor: pointer;
}

.flexbox{
  display: flex;
  flex-direction: row;
}

.skriv {
  border-radius: 40px 40px 40px 40px;
  outline: none;
  padding: 0 2%;
  width: 51%;
  margin: 2%;
}

.läggatill {
  border: 1px solid black;
  background-color: white;
  border-radius: 5px 5px 5px 5px;
  outline: none;
  margin: 2% 5%;
  width: 23%;
  max-width: 200px;
  float: right;
}

.dropdown {
  display: none;
  background-color: darkgrey;
  height: 400px;
  margin-top: 3%;
  margin-right: 0%;
  margin-left: 0.96%;
  margin-bottom: 0%;
  z-index: 1;
  width: 100px;
}
.dropdown textarea{
  width: 100px;
}

.show {
  display: block;
}

.hej {
  position: relative;
  border: none;
  background-color: white;
  color: darkblue;
}

.autoExpand {
  /* display: none;  */
  /* position: absolute !important; */
  margin-top: 10%;
  margin-right: 0%;
  margin-left: 0.96%;
  margin-bottom: 0%;
  z-index: 2;
  display: block;
  overflow: hidden;
  padding: 10px;
  font-size: 14px;
  border-radius: 6px;
  border: 0;
  resize: none;
}

.text {
  text-align: center;
  margin-top: 30%;
  cursor: default;
}

/* End of lägga till kompetens */

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="css/Profil.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

  <input id="myText" type="text" class="skriv" name="Kompetenser" autocomplete="off" autofocus>
  <input id="läggatill" class="läggatill" type="button" value="Add box">


Q:

Go back from Storyboards to XIB

Not knowing that Storyboards are iOS5 only I created project that could be run even on iOS 2.0, but now I can't compile it with target lower than iOS5. Is there an easy way to go back to simple XIB file?

A:

I don't think there's an automatic way to downgrade. Create new xib files for each view controller that needs them and link their view with the appropriate .h file. You should be able to copy and paste your whole UIView container view from storyboard to an xib though so it's really not that bad.
EDIT:
Also, I recently had to do this myself and a few things that weren't immediately obvious to me were that I also had to create a MainWindow.xib file, change your application plist, main.m, and my app delegate. Was definitely more complex than I expected but can confirm it can be done.


Q:

Spring: How to use @RequestBody after reading inputStream

I'm having the issue described here but it's not clear to me how to address it.
The issue is that I have an AuthenticationProvider which has to read the body of the request. When my controller method wants to use that data via @RequestMapping, however, it's empty because the Provider has already read the inputStream.
Is there a way to obtain an inputReader from Request which supports mark/reset so my provider can simply roll the stream back to it's initial state after it does the authentication? It seems crazy that the default behavior of the filter is destructive modification of the request object.

A:

The Provider should be triggered only in specific cases, so it shouldn't affect your whole application. But if you need the body in the requests handled by the provider, then you still have a workaround:

implement a servlet Filter
wrap the request
in the wrapper cache the request body, and then override the getInputStream() method to return a ByteArrayInputStream with the cached request body. That way it can be read muiltiple times.

spring's AbstractRequestLoggingFilter does something similar and has an example wrapper, you can check it.


Q:

How to keep native spatial resolution while making a chart?

I have difficulties on producing chart in native spatial resolution. Please, look at the below script. The script allows to transform hourly GSMaP data into daily data and extract the values for given period as chart. But, to produce the chart I am required to specify the spatial scale which is "10000" in my script, while I would like to extract the data as chart in native resolution. If I delete the "10000" from chart line and run the script, GEE shows error:

Please, help me to improve the script to be able to produce chart in native resolution.
var pts = /* color: #d63000 */ee.Geometry.Point([65.945, 42.027]),
    aoi = ee.Geometry.Polygon(
        [[[64.62748181270217, 43.19201550614239],
          [64.62748181270217, 40.77519027755922],
          [67.43998181270217, 40.77519027755922],
          [67.43998181270217, 43.19201550614239]]], null, false);

// Start and End Dates
var inidate = ee.Date('2014-02-01')
var enddate = ee.Date('2014-03-30')

//Import GSMaP data
var img_1 = ee.ImageCollection("JAXA/GPM_L3/GSMaP/v6/reanalysis")
    .filterDate('2000-03-01', '2014-03-01').select('hourlyPrecipRateGC');

var img_2 = ee.ImageCollection("JAXA/GPM_L3/GSMaP/v6/operational")
    .filterDate('2014-03-01', '2030-12-31').select('hourlyPrecipRateGC');

var imgcol = img_1.merge(img_2)
    .filterDate(inidate, enddate);

// Difference between start and end in days
var difdate = enddate.difference(inidate, 'day')

// Time lapse
var lapse = ee.List.sequence(0, difdate.subtract(1))
var listdates = lapse.map(function(day){
  return inidate.advance(day, 'day')
})

// Function for producing daily image collection
var daily_gsmap = ee.ImageCollection.fromImages(listdates.map(function(day){
  day = ee.Date(day);
  var daily_collection = imgcol.select('hourlyPrecipRateGC').filter(ee.Filter.date(day, day.advance(1, 'day')));
  return daily_collection.sum().clip(aoi).rename('daily_rainfall').set('date', day.format('YYYY-MM-dd'))
        .set('system:time_start', day.millis()).set('system:time_end', day.millis());
}));

//Making chart and printing it
var chart_daily = ui.Chart.image.seriesByRegion(daily_gsmap, pts, ee.Reducer.first(), 'daily_rainfall', 10000)
  .setChartType('ColumnChart');
  chart_daily.setOptions({
    title: 'Daily rainfall',
    vAxis: {title: 'Rainfall (mm)'},
    hAxis: {title: 'Date', format: 'yyyy-MM-dd'},
  });

print(chart_daily);

A:

As suggested by @Kevin, the answer for the question is reproject images after sum in return line:
// Function for producing daily image collection
var daily_gsmap = ee.ImageCollection.fromImages(listdates.map(function(day)
    {
    day = ee.Date(day);
    var daily_collection = imgcol.select('hourlyPrecipRateGC')
        .filter(ee.Filter.date(day, day.advance(1, 'day')));
    return daily_collection.sum().clip(aoi).rename('daily_rainfall')
        .reproject(imgcol.first().projection())
        .set('date', day.format('YYYY-MM-dd'))
        .set('system:time_start', day.millis())
        .set('system:time_end', day.millis());
    }));


Q:

Proof that Corr(X,Y) equals zero for uniform discrete R.V.

i) X is a discrete uniform r.v. on the set $\{-1,0,1\}$. Let $Y=X^2$ .
Prove that $Corr(X,Y)=0$.
ii) X is a discrete uniform r.v. on the set $\{-1,0,1\}$. Let $Y=X^2$. Are X and Y independent?
Confused on the fact that this uniform discrete RV has 3 parameters when Im use to seeing it with only 2. So for example to the the expected value it's just: $\frac{a+b}{2}$; however, here we have more than two options for "a" and "b". This is all under the assumptions that I can calculate E(X) and $E(Y)$; $Var(X)$ and $Var(Y)$; all to find $Cov(X,Y)$ and then $Corr(X,Y)$

A:

Uniform distribution over a finite set $\{x_1,\ldots,x_n\}$ just means $\Pr(X=x_i)=\frac{1}{n}$ for each $i$.
For your claims, with $Y=X^2$
$$
\text{Cov}(X,Y)=E(XY)-\underbrace{E(X)}_0E(Y)=E(X^3)=\frac{1}{3}1^3+\frac{1}{3}0^3+\frac{1}{3}(-1)^3=0.
$$
So $X$ and $Y$ are uncorrelated. Nonetheless, knowing $X$ gives $Y$ so $X$ and $Y$ are not independent. For example, you can note
$$
\Pr(X=1,Y=0)=\Pr(X=1,X^2=0)=0\neq\underbrace{\Pr(X=1)}_{1/3}\underbrace{\Pr(Y=0)}_{1/3}.
$$


Q:

Trying to open .php page when clicking on asp button

I am trying to integrate php pages with .net web forms.
I have just copied .php web page and paste into .net web application
Here is .net code:
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />

and Code Behind is
protected void Button1_Click(object sender, EventArgs e)
{
    Server.Transfer("register.php");
}

but it gives an Exception Given Below

Server Error in '/' Application. No http handler was found for request
  type 'POST'
Description: An unhandled exception occurred during the execution of
  the current web request. Please review the stack trace for more
  information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: No http handler was found
  for request type 'POST'
Source Error:
Line 17:         protected void Button1_Click(object sender, EventArgs
  e) Line 18:         { Line 19:
  Server.Transfer("register.php"); Line 20:             Line 21:
  }
Source File: c:\Users\Vishal\Documents\Visual Studio
  2013\Projects\TestHomePage\test3\WebForm2.aspx.cs    Line: 19
Stack Trace:
[HttpException (0x80004005): No http handler was found for request
  type 'POST']
  System.Web.HttpApplication.MapIntegratedHttpHandler(HttpContext
  context, String requestType, VirtualPath path, String pathTranslated,
  Boolean useAppConfig, Boolean convertNativeStaticFileModule) +898
  System.Web.HttpServerUtility.Execute(String path, TextWriter writer,
  Boolean preserveForm) +464
[HttpException (0x80004005): Error executing child request for
  register.php.]

A:

From https://msdn.microsoft.com/en-us/library/caxa892w(v=vs.110).aspx (the Server.Transfer docs):

"The page transferred to should be another .aspx page. For instance, a
  transfer to an .asp or .asmx page is not valid."

Try Response.Redirect("register.php"); instead. This will cause a browser redirect to the PHP page. What you're doing currently is basically asking the .NET framework to execute some PHP code.
Also, you need to ensure you've installed the PHP engine on the server and it's all properly registered with IIS, otherwise the PHP page won't execute.
Background: PHP and ASP.NET are two completely different frameworks / languages. It's not clear if this is your aim, but it's worth noting that you can't expect to do an internal transfer from one to the other preserving all your session data etc etc, they run in entirely separate contexts. You can redirect from one to the other as I've suggested, but the scripts will not function as though they were a single application unless you do a lot of fudging behind the scenes.
Depending how much PHP / .NET you've got it might be easier to just rewrite one of the languages into the other one in order to integrate them, or define some formal APIs to allow them to exchange data in an orderly fashion.


Q:

How to plot the data points in Excel using C#?

I have been trying to use data to create a graph in an excel sheet. My data source is the same workbook. Data is in sheet 1 and I want to create the graph in sheet 2. I have read through almost all the StackOverflow threads and other web resources. I can't seem to find where I have gone wrong. The graph does not show anything but the axes correctly scaled.
I want to plot column A(X Axis) against B, C, D and E in four different line/bar charts. I use Microsoft.Office.Interop.Excel namespace.
This is the code snippet.
Worksheet sheet2 = workBook.Worksheets[2];
ChartObjects chart = sheet2.ChartObjects(Type.Missing);
ChartObject[] chartObj = {chart.Add(10, 10, 550, 300), chart.Add(580, 10, 550, 300), chart.Add(10, 350, 550, 300), chart.Add(580, 350, 550, 300) };
int[,] rangeVal = { { 0, 400 }, { 0, 100 }, { 0, 300 }, { 0, 5 } };
for (int col = 2; col <= colsCount; col++)
{
     Chart myChart = chartObj[col-2].Chart;
     chartObj[col - 2].Select();

     myChart.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xlLine;
     SeriesCollection seriesCollection = myChart.SeriesCollection();

     Series series1 = seriesCollection.NewSeries();
     series1.Name = sheet1.Cells[1,col].Value.ToString();
     series1.XValues = sheet1.get_Range("A2","A" + (rowsCount + 1).ToString());
     series1.Values = sheet1.get_Range((char)((int)'A' + col - 1) + "2", (char)((int)'A' + col - 1) + (rowsCount + 1).ToString());

     series1.ChartType = XlChartType.xlLine;
     myChart.PlotBy = XlRowCol.xlRows;
     myChart.Axes(XlAxisType.xlValue).MinimumScale = rangeVal[col-2,0];
     myChart.Axes(XlAxisType.xlValue).MaximumScale = rangeVal[col-2,1];
     //myChart.SetSourceData(sheet1.get_Range((char)((int)'A' + col - 1) + "2", (char)((int)'A' + col - 1) + (rowsCount + 1).ToString()));
}

This is the screenshot of the graph with commented SetSourceData statement:

This is the screenshot of the graph with SetSourceData enabled:

And my data set does not have any zero values.
Any help would be appreciated!

A:

For anyone who is looking for answers. This was my scenario:
I read data from MySQL into a DataTable and the problem was how I saved the data in sheet1. I stored them as string values. And that's why the part where I read the data from sheet1 doesn't convert string values to numerical values. It simply takes it as 0.
The code above works perfectly otherwise.
Silly mistake! :)


Q:

Android Service

Please explain an Android Service. How does it differ from an Activity?  Does it depend on an application state such as running in the foreground/background?

A:

From the Android Developer's SDK reference for Service:

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.

It is very important to note

that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work.

This is in contrast to an activity which is best understood as something a user directly sees and interacts with (a UI.)
A service, as mentioned above, can be used for longer-running operations that will continue even if you have no foreground activity, but they can, and eventually will be killed by Android's lifecycle if left in the "background" state. If you need your service to continue running as a single instance without being killed and restarted, I would recommend placing startForeground(int id, Notification notification) in your Service's onCreate method and stopForeground(boolean removeNotification) in your Service's onDestroy method.
For example, I have an app that uses a foreground Service to record accelerometer data all night while the android device is next to the user's body. Though it is not required to be active, I also have an Activity that broadcast an Intent to a BroadcastReceiver inside the Service which tells the Service that it should also broadcast an Intent with accelerometer data as extras to a BroadcastReceiver inside the Activity.
Code:
SleepActivity
SleepAccelerometerService
Good luck and let me know if you need any more information!

A:

a Service is a context similar to Activity but has no GUI.
Important: A service doesn't run in a new thread!
Read about Service and also check out How to always run a service in the background?


Q:

Pulling Ipad xib into universal App

I am making a universal app that originally was going to be just iphone so I am converting the xib files into ipad xib files though I don't know how to call them
I have looked around and this is what I have found though I haven't got a clue of how to use it:
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        self.viewController = [[LSViewController alloc] initWithNibName:@"LSViewController_iPhone" bundle:nil];
    } else {
        self.viewController = [[LSViewController alloc] initWithNibName:@"LSViewController_iPad" bundle:nil];
}

A:

The code you have mentioned is right..
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
    self.viewController = [[LSViewController alloc] initWithNibName:@"LSViewController_iPhone" bundle:nil];
} else {
    self.viewController = [[LSViewController alloc] initWithNibName:@"LSViewController_iPad" bundle:nil];

}
You have to create 2 xib(UI) files one for iPhone and 2nd for iPad the class name for both will be same.
In the above code LSViewController_iPhone is for iPhone and LSViewController_iPad for iPad.
Now, the given if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) condition checks for the device type and load xib file accordingly.


Q:

LR(k) or LALR(k) parser generator with features similar to ANTLR

I'm currently in the process of writing a parser for some language. I've been given a grammar for this language, but this grammar has some left recursions and non-LL(*) constructs, so ANTLR doesn't do very well, even with backtracking.
Because removing these left recursions and non-LL(*) constructs is harder than it looked at first glance, I now want to try a LR(k) or LALR(k) parser generator. The higher k the better.
Can anyone recommend me a parser generator fulfilling these requirements?

The generated parser is preferably a LR(k) parser with some high (or even arbitrary) k, or at least a LALR(k) parser with some high k.
The generated parser is written in C or C++, and if it is written in C, it is linkable to C++-Code.
A feature set similar to ANTLR (especially the AST rewriting) would be nice.
Performance is not the most pressing issue, the generated parser is intended to
be used on desktop machines with much memory and cpu power.

Thanks and greetings,
Jost
PS: I'm not asking because I can't google myself, but because there is no time left to test some generators myself. So please only answer if you have experience with the recommended parser generators.

A:

You might consider LRSTAR.
I have no experience with the tool itself, but I've met the author and he seems like a pretty competent guy.  (I do build parsing engines and related technology for a living).

A:

LRSTAR 10.0 is available now.  On the comparison page, there is a comparison of LRSTAR, ANTLR and Bison.  LRSTAR now reads ANTLR's style notation using the same EBNF operators (:, |, *, +, ?).  It's a C++ based system generating LR(k) parsers in C++.  The parsers do automatic AST construction and traversal. The new version 10.0 reads Yacc/Bison grammars if there is no action code in the grammar.

A:

I have now decided to use DParser, which is a GLR-Parser generator capable of recognizing any context free language. It seems to be well programmed (look at the tests in the source distribution), but lacks a lot of the features ANTLR provides, most notably the AST-Construction tools.
As a plus, it mostly reuses ANTLRs grammar file format, which was the format my grammar is in.


Q:

Logically deducing inverse square law (physics)

Consider a hollow spherical charge with density $\rho'$ continuously varying only with respect to distance from the center $O$.

$V'=$ yellow volume
$k \in \mathbb {R}$
$\forall$ point $P$ inside the hollow sphere, electric field is zero. Now I have to prove the following two theorems:
$(1)$ Given: $\vec{E}_P=\displaystyle\int_{V'}\rho'\ f(r) (\hat{r})=0$.
To prove: $f(r)=\dfrac{k}{r^2}$
$(2)$ Given: $\vec{E}_P=\displaystyle\int_{V'}\rho'\ \vec{f}(r) = 0$.
To prove: $\vec{f}(r)=\dfrac{k\ \hat{r}}{r^2}$

Can we prove these two theorems? If yes for any, please help me to prove it.

A:

It's convenient to work with a potential $u$ so $\vec{f}=-\nabla u$. For (2) to hold for arbitrary spherically symmetric $\rho$, it must in particular work when $\rho=m\delta^3(r-a^\prime)$, viz.$$\partial_p\int_0^\pi d\theta\sin\theta u\left(\sqrt{p^2+a^{\prime2}-2pa^\prime\cos\theta}\right)=0.$$Substitute $r^2=p^2+a^{\prime2}-2pa^\prime\cos\theta$ so$$\partial_p\int_{a^\prime-p}^{a^\prime+p}\frac{rdr}{p}u(r)=0.$$But then$$\int_{a^\prime-p}^{a^\prime+p}ru(r)dr\propto p\implies(a^\prime+p)u(a^\prime+p)+(a^\prime-p)u(a^\prime-p)=\operatorname{constant},$$and the case $a^\prime=0$ shows this constant is $0$, provided we identify a radius of $-p$ with one of $p$. So$$u(r)\propto\frac1r\implies \vec{f}(r)\propto\frac{\hat{r}}{r^2}.$$The treatment of (1) is similar.


Q:

C++ Warming std vector

Why filling std::vector second time is FASTER? Even if space was reserved from the beggining?
int total = 1000000;

struct BaseClass {
  float m[16];
  int id;

  BaseClass(int _id) { id = _id; }
};

int main() {

  std::vector<BaseClass> ar;
  ar.reserve(total);

  {
    auto t_start = std::chrono::high_resolution_clock::now();
    for (int var = 0; var < total; ++var) {
      ar.emplace_back(var);
    }
    auto t_end = std::chrono::high_resolution_clock::now();
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(
                     t_end - t_start).count() << "\n";
    ar.clear();
  }

  {
    auto t_start = std::chrono::high_resolution_clock::now();
    for (int var = 0; var < total; ++var) {
      ar.emplace_back(var);
    }
    auto t_end = std::chrono::high_resolution_clock::now();
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(
                     t_end - t_start).count() << "\n";
    ar.clear();
  }

  {
    auto t_start = std::chrono::high_resolution_clock::now();
    for (int var = 0; var < total; ++var) {
      ar.emplace_back(var);
    }
    auto t_end = std::chrono::high_resolution_clock::now();
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(
                     t_end - t_start).count() << "\n";
    ar.clear();
  }

  return 0;
}

online preview:
http://coliru.stacked-crooked.com/a/229e4ba47adddb1a
RESULTS:
118
23
21
P.S. I'm asking why it becomes faster if the only reason for slowdown for vector is allocation/reallocation. And we allocated array BEFORE start.

A:

The reason that the first run is slower than the other two is that the runtime has not yet gotten the memory pages from the OS.
I instrumented your program to output the number of major and minor page faults the task had taken at the beginning, and after each of the three stages above.  (Note: This works on Linux.  No idea if it'll work on whatever OS you're on.)  Code:
Note: updated to latest, with reserve() moved to the top and wrapped in its own getrusage call.
#include <ctime>
#include <chrono>
#include <iostream>
#include <vector>

#include <sys/time.h>
#include <sys/resource.h>

using namespace std;

int total = 1000000;

struct BaseClass {
  float m[16];
  int id;

  BaseClass(int _id) { id = _id; }
};

int main() {

  std::vector<BaseClass> ar;
  struct rusage r;
  {
    auto t_start = std::chrono::high_resolution_clock::now();
     }

  getrusage(RUSAGE_SELF, &r);
  cout << "minflt: " << r.ru_minflt << " majflt: " << r.ru_majflt << endl;

  ar.reserve(total);

  getrusage(RUSAGE_SELF, &r);
  cout << "minflt: " << r.ru_minflt << " majflt: " << r.ru_majflt << endl;

  {
    auto t_start = std::chrono::high_resolution_clock::now();
    for (int var = 0; var < total; ++var) {
      ar.emplace_back(var);
    }
    auto t_end = std::chrono::high_resolution_clock::now();
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(
                     t_end - t_start).count() << "\n";
    ar.clear();
  }

  getrusage(RUSAGE_SELF, &r);
  cout << "minflt: " << r.ru_minflt << " majflt: " << r.ru_majflt << endl;

  {
    auto t_start = std::chrono::high_resolution_clock::now();
    for (int var = 0; var < total; ++var) {
      ar.emplace_back(var);
    }
    auto t_end = std::chrono::high_resolution_clock::now();
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(
                     t_end - t_start).count() << "\n";
    ar.clear();
  }

  getrusage(RUSAGE_SELF, &r);
  cout << "minflt: " << r.ru_minflt << " majflt: " << r.ru_majflt << endl;

  {
    auto t_start = std::chrono::high_resolution_clock::now();
    for (int var = 0; var < total; ++var) {
      ar.emplace_back(var);
    }
    auto t_end = std::chrono::high_resolution_clock::now();
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(
                     t_end - t_start).count() << "\n";
    ar.clear();
  }

  getrusage(RUSAGE_SELF, &r);
  cout << "minflt: " << r.ru_minflt << " majflt: " << r.ru_majflt << endl;

  return 0;
}

I then ran it on my box.  The result is enlightening:
minflt: 343 majflt: 0
minflt: 367 majflt: 0
48    minflt: 16968 majflt: 0
16
minflt: 16968 majflt: 0
15
minflt: 16968 majflt: 0

Notice that the first measured for-loop incurred over 16,000 minor faults.  Those faults are what make the memory available to the application and account for the slower running time.  No additional faults happen thereafter.  In contrast, the reserve() call itself only incurred 24 minor faults.
In most modern virtual-memory OSes, the OS implements lazy memory allocation, even if the software running on it does not.  When the runtime requests additional memory from the OS, the OS makes a note of the request.  If the request succeeds, the runtime now has a new range of virtual addresses available to it.  (Details vary depending on the API called and the OS, but the essence is the same.)  The OS may point the virtual address range to a single zero-filled page marked read-only.
The OS does not necessarily make those pages immediately available to the task.  Rather, the OS waits until the task actually tries to write to the memory it's allocated.  At that point, the OS allocates a physical page to back the virtual page allocated to the task.  That registers as a "minor fault" in UNIX parlance.  That process can be expensive.
It's that lazy allocation that your task is measuring.
To prove that, I did an strace of the application as well.  The meaningful portion is below.
getrusage(RUSAGE_SELF, {ru_utime={0, 0}, ru_stime={0, 0}, ...}) = 0
fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fe3aa339000
write(1, "minflt: 328 majflt: 0\n", 22) = 22
mmap(NULL, 68001792, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fe3a551c000
getrusage(RUSAGE_SELF, {ru_utime={0, 0}, ru_stime={0, 0}, ...}) = 0
write(1, "minflt: 352 majflt: 0\n", 22) = 22
write(1, "52\n", 3)                     = 3
getrusage(RUSAGE_SELF, {ru_utime={0, 30000}, ru_stime={0, 20000}, ...}) = 0
write(1, "minflt: 16953 majflt: 0\n", 24) = 24
write(1, "20\n", 3)                     = 3
getrusage(RUSAGE_SELF, {ru_utime={0, 50000}, ru_stime={0, 20000}, ...}) = 0
write(1, "minflt: 16953 majflt: 0\n", 24) = 24
write(1, "15\n", 3)                     = 3
getrusage(RUSAGE_SELF, {ru_utime={0, 70000}, ru_stime={0, 20000}, ...}) = 0
write(1, "minflt: 16953 majflt: 0\n", 24) = 24
munmap(0x7fe3a551c000, 68001792)        = 0
exit_group(0)                           = ?

As you can see, the task allocated memory with an mmap call between the first two getrusage system calls.  And yet, that step only incurred 24 minor faults.  So, even though C++ was not being lazy, Linux was being lazy about giving the memory to the task.
Specifically, the first mmap call appears to allocate an I/O buffer for the first write mesage.  The second mmap call (allocating 68001792 bytes) happens before the second getrusage call.  And yet, you can see only 24 additional faults occurred between the two on this run.
The hawk-eyed among you will notice the numbers are slightly different for this run than the numbers I showed above.  I've run this executable many times, and the numbers shift slightly each time.  But, they're always in the same general ballpark.


Q:

Mysterious behaviour of php

Below code works as expected. It adds 3 entries to the table 'keywords'.
<?php
include "config.php";
try{
    // $conn = new PDO(DBINFO,USER,PASS);
    // $sql = "INSERT INTO projects (title,duration, startyear, description, tags,email) VALUES (:title,:duration, :startyear, :description, :tags,:email)";
    // $stmt = $conn->prepare($sql);
    // $stmt->bindParam(':title', $_POST['title'],PDO::PARAM_STR);
    // $stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
    // $stmt->bindParam(':duration', $_POST['duration'], PDO::PARAM_STR);
    // $stmt->bindParam(':startyear', $_POST['startyear'], PDO::PARAM_STR);
    // $stmt->bindParam(':description', $_POST['description'], PDO::PARAM_STR);
    // $stmt->bindParam(':tags', $_POST['tags'], PDO::PARAM_STR);
    // $stmt->execute();

    for($i=0; $i<3; $i++){
        $conn2 = new PDO(DBINFO,USER,PASS);
        $sql2 = "INSERT INTO keywords (keyword,confidence) VALUES (:keyword,:confidence)";
        $stmt2 = $conn2->prepare($sql2);
        $a = 'asdfds';
        $stmt2->bindParam(':keyword', $a,PDO::PARAM_STR);
        $stmt2->bindParam(':confidence', $a, PDO::PARAM_STR);
        $stmt2->execute();
    }
}
catch(PDOException $pe){
    die("Could not connect to the database :".$pe->getMessage());
}
?>

However, when I run the below code (where I uncommented the first part), the entries get added 6 times to the 'keywords' table.
<?php
include "config.php";
try{
    $conn = new PDO(DBINFO,USER,PASS);
    $sql = "INSERT INTO projects (title,duration, startyear, description, tags,email) VALUES (:title,:duration, :startyear, :description, :tags,:email)";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':title', $_POST['title'],PDO::PARAM_STR);
    $stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
    $stmt->bindParam(':duration', $_POST['duration'], PDO::PARAM_STR);
    $stmt->bindParam(':startyear', $_POST['startyear'], PDO::PARAM_STR);
    $stmt->bindParam(':description', $_POST['description'], PDO::PARAM_STR);
    $stmt->bindParam(':tags', $_POST['tags'], PDO::PARAM_STR);
    $stmt->execute();

    for($i=0; $i<3; $i++){
        $conn2 = new PDO(DBINFO,USER,PASS);
        $sql2 = "INSERT INTO keywords (keyword,confidence) VALUES (:keyword,:confidence)";
        $stmt2 = $conn2->prepare($sql2);
        $a = 'asdfds';
        $stmt2->bindParam(':keyword', $a,PDO::PARAM_STR);
        $stmt2->bindParam(':confidence', $a, PDO::PARAM_STR);
        $stmt2->execute();
    }
}
catch(PDOException $pe){
    die("Could not connect to the database :".$pe->getMessage());
}
?>

I can't understand this. Any help?

A:

Why do you create 4 different connections to the same server and schema in the first place?
The loop creates connections and closes them automatically when the references to statements and connections are overwritten.
But the original connection from before the loop will stay open and is reused for the statements. If you create a third connection without closing it before the loop you'll end up with 9 entries.
So delete the references to connection objects if they are no longer needed (this includes associated statements).
Or better yet reuse connections instead of creating a new connection for every statement.


Q:

Script won't run (Error in terms.formula(formula, data = data) : 'data' argument is of the wrong type

I have run the script below numerous times and it has worked until this morning, when it suddenly produced the error message:

(Error in terms.formula(formula, data = data) : 'data' argument is of
  the wrong type.

I have not changed anything and I need to find out why it suddenly doesn't seem to work. Previous answers to similar questions have not helped.
My data:
DPUT(harvest2)
structure(list(Year = c(1971, 1972, 1973, 1974, 1975, 1976, 1977,
1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988,
1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
2011, 2012, 2013, 2014, 2015, 2016), Count = c(750, 757, 592,
693, 667, 757, 719, 670, 733, 796, 923, 921, 944, 1010, 825,
762, 825, 844, 809, 830, 768, 823, 749, 675, 700, 637, 708, 697,
754, 694, 636, 717, 786, 731, 769, 732, 710, 610.5, 593, 529,
664, 788, 731, 644, 653, 656), SexRat = c(1.91812865497076, 2.34567901234568,
1.69178082191781, 1.46766169154229, 1.30396475770925,
1.4364406779661, 1.32098765432099, 1.48584905660377, 1.5906976744186,
1.91414141414141, 1.48905109489051, 1.61382113821138, 1.52380952380952,
1.87777777777778, 1.75438596491228, 1.6695652173913, 1.81566820276498,
1.79295154185022, 1.85024154589372, 1.75446428571429, 1.83163265306122,
1.92857142857143, 1.76635514018692, 1.5, 2.26190476190476,     1.76704545454545,
2.38125, 1.80924855491329, 2.33333333333333, 1.81182795698925,
2.20446096654275, 2.02790697674419, 2.1140350877193, 2.05, 2.20183486238532,
1.90983606557377, 2.02262443438914, 1.75116279069767, 1.86842105263158,
1.87951807228916, 2.08542713567839, 2.01724137931034, 1.95833333333333,
1.81165919282511, 2.12135922330097, 1.97260273972603)), class = "data.frame",
row.names = c(NA, -46L))

My script:
# Function for the equation

lm_eqn = function(df){
  m = lm(y ~ poly(x, 3), df) #3rd degree polynomial
  eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
                   list(a = format(coef(m)[1], digits = 2),
                        b = format(coef(m)[2], digits = 2),
                        r2 = format(summary(m)$r.squared, digits = 4)))

  as.character(as.expression(eq))
}

# Make the plot

library(ggplot2)
ggplot(harvest2, aes(x = Year, y = Count)) +
  scale_y_continuous(minor_breaks = seq(500, 1100, by = 50),
                     breaks = seq(500, 1100, by = 100),
                     limits = c(500, 1100), expand = c(0, 0)) +
  scale_x_continuous(minor_breaks = seq(1970, 2018, by = 1),
                     breaks = seq(1970, 2018, by = 5), limits = c(1970, 2018)) +
  geom_point(stat = 'identity', size=2) +
  stat_smooth(method = "lm", se = TRUE, fill = NA, size = 1.3,
              formula = y ~ poly(x, 3, raw = TRUE), col = "red") +
  annotate("text", x = 1975, y = 1075, label = lm_eqn(df),
           hjust = 0, size = 3.5, parse = TRUE) +
  xlab(" ") +
  ylab("Count") +
  theme_light() +
  ggtitle(" ")

Any help much appreciated.

A:

How about using stat_poly_eq from the ggpmisc package? See this if you want to separate the equation and R2 into two lines.
library(ggplot2)
library(ggpmisc)

# define formula
formula1 <- y ~ poly(x, 3, raw = TRUE)

ggplot(harvest2, aes(x = Year, y = Count)) +
  scale_y_continuous(
    minor_breaks = seq(500, 1100, by = 50), breaks = seq(500, 1100, by = 100),
    limits = c(500, 1100), expand = c(0, 0)) +
  scale_x_continuous(
    minor_breaks = seq(1970, 2018, by = 1), breaks = seq(1970, 2018, by = 5),
    limits = c(1970, 2018)) +
  geom_point(stat = "identity", size = 2) +
  stat_smooth(
    method = "lm", se = TRUE, fill = NA, size = 1.3,
    formula = formula1, col = "red") +
  # show the equation and R2
  stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~~")),
    label.x.npc = "left", label.y.npc = "top",
    formula = formula1, parse = TRUE, size = 5) +
  xlab(" ") + ylab("Count") +
  theme_light() +
  ggtitle(" ")

Created on 2019-02-12 by the reprex package (v0.2.1.9000)


Q:

SwiftUI TextField and overlay

I want to add an overlay view (Color.black) to a textField (goal is to reduce brightness).
However, after I add the overlay view, textField is unable to use(select).
I tried allowsHitTesting(false), but no use.
Does anyone know how to solve the problem?
TextField(title: StringProtocol, text: Binding<String>)
    .overlay(Color.black.opacity(0.2))

A:

Overlays create a secondary view in front of the TextField. You can achieve the same result using background. Here's the code. Hope this helps.
import SwiftUI

struct ContentView: View {
    @State var name: String = "This is a test."
    var body: some View {
        TextFieldView(name: $name)
    }
}

struct TextFieldView: View {
    @Binding var name: String
    var body: some View {
        TextField("Name", text: $name)
            .background(
                Color.black.opacity(0.2)
            )
    }
}


Q:

How to avoid deselection of check box in extjs4.1

Can anybody tell me how to avoid deselection of check box in extjs4.1? In my application the check box should always be selected. The user shouldn't deselect the check box.

A:

You can use readOnly config property and configure your checkbox with readOnly: true. Value from this checkbox will be normally submited, but user can not uncheck the checkbox.
{
    xtype: 'checkbox',
    boxLabel: 'Read only checkbox',
    name: 'readOnly',
    readOnly: true,
    checked: true

}


Q:

Sorting by a column in MS Excel - VBA

I am trying to sort a column using VBA in Excel. This is my code,
Range("B:B").Sort _
Key1:=Range("B2"), Order1:=xlAscending

But, It sorts the header column as well. I didn't want the Header Column to be included in the sorting , So I tried the following code,
Range("B1:B").Sort _
Key1:=Range("B2"), Order1:=xlAscending

Which didn't work either. Is there anyway to tell the VBA that my first column is a header name while sorting? Kindly share your thoughts.

A:

Add the following to the code:
Header:=xlYes

So it becomes:
Range("B:B").Sort Key1:=Range("B2"), Order1:=xlAscending, Header:=xlYes


Q:

Array of classes. Stack or heap?

class temp;

temp *t;

void foo() { temp foo2; t[1] = foo2; }

int main() {
    t = new temp[100];
    foo();
    //t[1] is still in memory?
}

If i want an array of classes like this, am i going to have to use
pointer to pointer? (and use 'new'
on each element in the array) E.G:
temp **t;
if i want to make an
array of 100 ptr to ptr i have todo
temp **t = new temp[100][1]; is
there a better way to do that without
4 square brackets?

A:

The code:
t = new temp[100];

constructs an array 100 objects of type temp. A safer way to do the same thing is:
std::vector <temp> t(100);

which absolves you of ever having to call delete[] on the array.

A:

Try to avoid the new stuff at all until you exactly know what you are doing.
std::vector<temp> t(100);

will do the job in a perfect manner. You still can access it using [] operator and like in your solution.
temp foo2; t[1] = foo2;

will call the assignment operator of the temp class.
use & for passing the variable to a function.
void foo1(std::vector<temp>& lt)
{
}

void foo2(temp& lt)
{
}

foo1(t);
foo2(t[1]);


Q:

FTP Error 500 Illegal Port Command - PORT command sending different IP than source of request

The problem I'm experiencing is that I'm getting a "500 Illegal PORT command" Response from an FTP server when attempting to upload a file programmatically.
This program is a small c# application that connects to an FTP site and copies files to the default directory. This program has been in production for several years and I am confident the code itself works just fine. I've also tested the application by connecting to my own FTP site using the same application and it works. Passive mode does not seem to be an option.
When attempting to connect to our partner's FTP site, the program runs as expected until the FTP put command is executed. I have noticed when running Wireshark that the source IP of my Request is different from the IP address the PORT command is sending. I have uploaded an image of a capture here (all sensitive information has been removed using my amazing photoshop skills):
.
I have contacted the owner of the FTP site where we are attempting to transfer the files and they have opened their firewall for our new Static IP address. I can connect to their site using FTP clients from machines on both of the LAN IP's, but those PORT commands are always sent using the same LAN IP as the source of the request. I have also tried using ftp.exe from the server where the program resides, and it is successful (but the PORT command uses the same IP as the source).
So I guess the big question is how can I control what IP address the PORT command uses? Or, if I can't control it, how is the IP address and PORT determined by the ftp program?

A:

It turns out the answer really has to do with the FTP library I was using. I thought for sure this wasn't a coding issue, but after I sniffed around how the library is creating the request, I think I have found the answer.
Here is the relevant section using ILSpy (I put space around the most important line):
private Socket CreateDataSocketActive()
{
    Socket socket = new Socket(2, 1, 6);
    IPHostEntry iPHostEntry = Dns.Resolve(Dns.GetHostName());

    IPEndPoint iPEndPoint = new IPEndPoint(iPHostEntry.get_AddressList()[0], 0);

    socket.Bind(iPEndPoint);
    socket.Listen(5);
    int port = ((IPEndPoint)socket.get_LocalEndPoint()).get_Port();
    IPAddress address = ((IPEndPoint)socket.get_LocalEndPoint()).get_Address();
    this.SetDataPort((IPEndPoint)socket.get_LocalEndPoint());
    return socket;
}

It looks like the library is creating the IP endpoint by simply grabbing the first address in the list of available IP addresses. For most solutions, that is probably acceptable, but because I have multiple NICs on my server, it doesn't work for me.
I know by using FTP.exe that the server will accept connections from both of my LAN IP subnets so long as the PORT command issued is issued using the same LAN IP address as the source of the request.
I'm guessing there's some kind of validation done by the FTP server that compares the two addresses to verify they're the same. Otherwise, I could theoretically transfer a file to some other device on a completely different network once I logged into the FTP site.
Now I've just got to figure out a workaround, but that should just be a matter of finding a new library or rolling my own. If it helps anyone else who might have had the same issue, the library I was using was com.enterprisedt.net.ftp.


Q:

How to solve this mysqli error

Code 1 which works perfectly fine and updates a attendance table:
<?php
$date = $_POST['date'];
$subject = $_POST['subject'];
$con=mysqli_connect("localhost","root","","notifier");
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM student");

echo "Enter the attendance. Please untick for 'ABSENT' students and submit";
echo "
";
echo "<form action=\"d.php\" method=\"post\">";
while($row = mysqli_fetch_array($result))
{
    echo "
" .$row['classrollno'] . "&nbsp &nbsp<input type=\"checkbox\" name=\"p[]\" value=\"" . $row['studentid'] . "\" checked>";

    $sql="INSERT INTO attendance (rollno, subjectid, date)
    VALUES
    ('{$row['classrollno']}','$_POST[subject]','$_POST[date]')";

    if (!mysqli_query($con,$sql))
    {
      die('Error: ' . mysqli_error($con));
    }
}
mysqli_close($con);
echo "<input type=\"hidden\" name=\"date\" value=\"" . $date . "\">";
echo "<input type=\"hidden\" name=\"subject\" value=\"" . $subject . "\">";
    echo "<input type=\"submit\" name=\"submit\" value=\"submit\">";
echo "</form>";
?>

Code two giving error, which is supposed to update table depending on checkboxes recieved from previous page:
<?php
$con=mysqli_connect("localhost","root","","notifier");
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

foreach($_POST['p'] as $value)
{
$sql="UPDATE attendance SET presenty='P'
WHERE studentid='{$value}' AND subjectid='$_POST[subject]' AND date='$_POST[date]')";

    if (!mysqli_query($con,$sql))
    {
      die('Error: ' . mysqli_error($con));
    }
}
mysqli_close($con);
?>

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 2
but this line works perfectly fine in previous file.

A:

Line 1: UPDATE attendance SET presenty='P'
Line 2: WHERE studentid='foo' AND subjectid='bar' AND date='baz')

Error: ... near ')' at line 2
The only ) at line 2 is the closing one. Remove it.
+
You need braces around $_POST[stuff].


Q:

What is the difference between define vs define-syntax and let vs let-syntax when value is syntax-rules?

I'm in a process of implementing Hygienic macros in my Scheme implementation, I've just implemented syntax-rules, but I have this code:
(define odd?
  (syntax-rules ()
    ((_ x) (not (even? x)))))

what should be the difference between that and this:
(define-syntax odd?
  (syntax-rules ()
    ((_ x) (not (even? x)))))

from what I understand syntax-rules just return syntax transformer, why you can't just use define to assign that to symbol? Why I need to use define-syntax? What extra stuff that expression do?
Should first also work in scheme? Or only the second one?
Also what is the difference between let vs let-syntax and letrec vs letrec-syntax. Should (define|let|letrec)-syntax just typecheck if the value is syntax transformer?
EDIT:
I have this implementation, still using lisp macros:
;; -----------------------------------------------------------------------------
(define-macro (let-syntax vars . body)
  `(let ,vars
     ,@(map (lambda (rule)
              `(typecheck "let-syntax" ,(car rule) "syntax"))
            vars)
     ,@body))

;; -----------------------------------------------------------------------------
(define-macro (letrec-syntax vars . body)
  `(letrec ,vars
     ,@(map (lambda (rule)
              `(typecheck "letrec-syntax" ,(car rule) "syntax"))
            vars)
     ,@body))

;; -----------------------------------------------------------------------------
(define-macro (define-syntax name expr)
  (let ((expr-name (gensym)))
    `(define ,name
       (let ((,expr-name ,expr))
         (typecheck "define-syntax" ,expr-name "syntax")
         ,expr-name))))

This this code correct?
Should this code works?
(let ((let (lambda (x) x)))
  (let-syntax ((odd? (syntax-rules ()
                        ((_ x) (not (even? x))))))
     (odd? 11)))

A:

This question seems to imply some deep confusion about macros.
Let's imagine a language where syntax-rules returns some syntax transformer function (I am not sure this has to be true in RnRS Scheme, it is true in Racket I think), and where let and let-syntax were the same.
So let's write this function:
(define (f v)
  (let ([g v])
    (g e (i 10)
       (if (= i 0)
           i
           (e (- i 1))))))

Which we can turn into this, of course:
(define (f v n)
  (v e (i n)
     (if (<= i 0)
         i
         (e (- i 1)))))

And I will tell you in addition that there is no binding for e or i in the environment.
What is the interpreter meant to do with this definition?  Could it compile it?  Could it safely infer that i can't possibly make any sense since it is used as a function and then as a number?  Can it safely do anything at all?
The answer is that no, it can't.  Until it knows what the argument to the function is it can't do anything.  And this means that each time f is called it has to make that decision again.  In particular, v might be:
(syntax-rules ()
  [(_ name (var init) form ...)
   (letrec ([name (λ (var)
                    form ...)])
     (name init))]))

Under which the definition of f does make some kind of sense.
And things get worse: much worse.  How about this?
(define (f v1 v2 n)
  (let ([v v1])
    (v e (i n)
       ...
       (set! v (if (eq? v v1) v2 v1))
       ...)))

What this means is that a system like this wouldn't know what the code it was meant to interpret meant until, the moment it was interpreting it, or even after that point, as you can see from the second function above.
So instead of this horror, Lisps do something sane: they divide the process of evaluating bits of code into phases where each phase happens, conceptually, before the next one.
Here's a sequence for some imagined Lisp (this is kind of close to what CL does, since most of my knowledge is of that, but it is not intended to represent any particular system):

there's a phase where the code is turned from some sequence of characters to some object, possibly with the assistance of user-defined code;
there's a phase where that object is rewritten into some other object by user- and system-defined code (macros) – the result of this phase is something which is expressed in terms of functions and some small number of primitive special things, traditionally called 'special forms' which are known to the processes of stage 3 and 4;
there may be a phase where the object from phase 2 is compiled, and that phase may involve another set of user-defined macros (compiler macros);
there is a phase where the resulting code is evaluated.

And for each unit of code these phases happen in order, each phase completes before the next one begins.
This means that each phase in which the user can intervene needs its own set of defining and binding forms: it needs to be possible to say that 'this thing controls what happens at phase 2' for instance.
That's what define-syntax, let-syntax &c do: they say that 'these bindings and definitions control what happens at phase 2'.  You can't, for instance, use define or let to do that, because at phase 2, these operations don't yet have meaning: they gain meaning (possibly by themselves being macros which expand to some primitive thing) only at phase 3.  At phase 2 they are just bits of syntax which the macro is ingesting and spitting out.


Q:

How do I create the following GUI in Java Swing?

I want to create the following GUI with Java Swing.

Since I'm not experienced enough with Java Swing, I'm not sure how to exactly recreate that GUI.
I've tried using GridLayout which looks like this:

I've tried other LayoutManagers but due to my inexperience, I couldn't get anything even remotely resembling the GUI I want to achieve.
I probably have to use GridBagLayout but I've tried it and simply wasn't able to get anything done.
I'm not sure how to exactly use GridBagLayout, especially since there is a variance of the amount of colums needed (2, 2 and then 3).
Here is the code used for creating the second GUI:
import java.awt.*;
import javax.swing.*;

public class GUITest extends JFrame {

public GUITest() {
    super("Testing Title");
    Container pane = getContentPane();

    pane.setLayout(new GridLayout(3,1));

    pane.add(getHeader());
    pane.add(getTextArea());
    pane.add(getButtonPanel());

}

public JComponent getHeader() {
    JPanel labelPanel = new JPanel();
    labelPanel.setLayout(new GridLayout(1,2));
    labelPanel.setSize(getPreferredSize());

    JLabel labelLocal = new JLabel("Left value: ", JLabel.CENTER);
    JLabel labelDB = new JLabel("Right value: ", JLabel.CENTER);

    labelPanel.add(labelLocal);
    labelPanel.add(labelDB);

    return labelPanel;
}

public JComponent getTextArea() {
    JPanel textPanel = new JPanel();
    textPanel.setLayout(new GridLayout(1,2,5,0));

    JTextArea testTextArea = new JTextArea();
    testTextArea.setEditable(false);
    JScrollPane sp1 = new JScrollPane(testTextArea);

    JTextArea testTextArea2 = new JTextArea();
    JScrollPane sp2 = new JScrollPane(testTextArea2);
    testTextArea2.setEditable(false);

    testTextArea.setText("Hello Hello Hello\nTesting!\ntesterino\ntesteroni");
    testTextArea2.setText("Hello Hello Hello\nTesting!\ntest\nABC123\ncdef123\nhijk123");

    textPanel.add(sp1);
    textPanel.add(sp2);
    return textPanel;
}

public JComponent getButtonPanel() {
    JPanel inner = new JPanel();
    inner.setLayout(new FlowLayout((FlowLayout.CENTER),0,100));
    inner.add(new JButton("Do something"));
    inner.add(new JButton("Do something different"));
    inner.add(new JButton("Do something even more different"));
    return inner;
}

public static void main(String[] args) {
    GUITest e = new GUITest();
    e.setSize(700, 500);
    e.setVisible(true);
    e.setResizable(false);
    e.setDefaultCloseOperation(EXIT_ON_CLOSE);
    e.setLocationRelativeTo(null);
}
}

I'm thankful for any kind of support!

A:

You could try something like this:
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;

public class Example {

   public static void main(String[] args) {

       JFrame jFrame = new JFrame();
       jFrame.setTitle("Testing Title");
       jFrame.setLocationRelativeTo(null);

       JPanel mainPanel = new JPanel(new BorderLayout());
       mainPanel.setBorder(new EmptyBorder(5, 5, 5, 5));

       JPanel listPanel = new JPanel(new GridLayout(0, 2, 10, 0));

       JPanel leftListPanel = new JPanel(new BorderLayout(0, 10));
       JLabel leftLabel = new JLabel("Left value:");
       JTextArea leftTextArea = new JTextArea("Hello Hello Hello\nTesting!\ntest");
       JScrollPane leftScrollPane = new JScrollPane(leftTextArea);
       leftListPanel.add(leftLabel, BorderLayout.NORTH);
       leftListPanel.add(leftScrollPane, BorderLayout.CENTER);

       JPanel rightListPanel = new JPanel(new BorderLayout(0, 10));
       JLabel rightLabel = new JLabel("Right value:");
       JTextArea rightTextArea = new JTextArea("Hello Hello Hello\nTesting!\ntest");
       JScrollPane rightScrollPane = new JScrollPane(rightTextArea);
       rightListPanel.add(rightLabel, BorderLayout.NORTH);
       rightListPanel.add(rightScrollPane, BorderLayout.CENTER);

       listPanel.add(leftListPanel);
       listPanel.add(rightListPanel);
       mainPanel.add(listPanel, BorderLayout.CENTER);

       JPanel buttonsPanel = new JPanel(new BorderLayout());
       buttonsPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
       buttonsPanel.add(new JButton("Do something"), BorderLayout.WEST);
       buttonsPanel.add(new JButton("Do something different"), BorderLayout.CENTER);
       buttonsPanel.add(new JButton("Do something even more different"), BorderLayout.EAST);
       mainPanel.add(buttonsPanel, BorderLayout.SOUTH);

       jFrame.setContentPane(mainPanel);
       jFrame.pack();
       jFrame.setVisible(true);
   }
}

Explanation:
Firstly I created a main JPanel with a BorderLayout. This JPanel will be split horizontally, the CENTRE component will be another JPanel containing the text areas and labels, and the SOUTH component will be a JPanel containing the buttons.
The JPanel that contains the text areas is given a GridLayout so that it can be easily split vertically, and is also given a hgap of 10 to add some spacing.
The left and right JPanels that are put into that are both the same. They have a BorderLayout with a vgap to add spacing. The NORTH component is a JLabel and the CENTRE component is a JScrollPane containing a JTextArea.
Finally, the SOUTH component of the main JPanel is another JPanel which is given a BorderLayout again. Three JButtons are added with WEST, CENTRE and EAST attributes allocated accordingly.
The overall result looks like:

A:

Here is your code with just some little changes :)
     import java.awt.*;
     import javax.swing.*;

     public class GUITest extends JFrame {

         public GUITest() {

              super("Testing Title");
              Container pane = getContentPane();
              pane.setLayout(new BorderLayout());//Modified Layout to BorderLayout
              pane.add(getHeader(),BorderLayout.NORTH); //BorderLayout.NORTH
              pane.add(getTextArea(),BorderLayout.CENTER);//BorderLayout.CENTER
              pane.add(getButtonPanel(),BorderLayout.SOUTH);//BorderLayout.SOUTH

        }

         public JComponent getHeader() {

             JPanel labelPanel = new JPanel();
             labelPanel.setLayout(new GridLayout(1,2));
             labelPanel.setSize(getPreferredSize());
             JLabel labelLocal = new JLabel("Left value: ", JLabel.CENTER);
             JLabel labelDB = new JLabel("Right value: ", JLabel.CENTER);
             labelPanel.add(labelLocal);
             labelPanel.add(labelDB);
             return labelPanel;

         }

     public JComponent getTextArea() {

           JPanel textPanel = new JPanel();
           textPanel.setLayout(new GridLayout(1,2,5,0));
           JTextArea testTextArea = new JTextArea();
           testTextArea.setEditable(false);
           JScrollPane sp1 = new JScrollPane(testTextArea);
           JTextArea testTextArea2 = new JTextArea();
           JScrollPane sp2 = new JScrollPane(testTextArea2);
           testTextArea2.setEditable(false);
           testTextArea.setText("Hello Hello Hello\nTesting!\ntesterino\ntesteroni");
           testTextArea2.setText("Hello Hello Hello\nTesting!\ntest\nABC123\ncdef123\nhijk123");
           textPanel.add(sp1);
           textPanel.add(sp2);
           return textPanel;
   }

     public JComponent getButtonPanel() {

          JPanel inner = new JPanel();
          inner.setLayout(new FlowLayout());//Modified to standard FlowLayout
          inner.add(new JButton("Do something"));
          inner.add(new JButton("Do something different"));
          inner.add(new JButton("Do something even more different"));
          return inner;

     }

     public static void main(String[] args) {

          GUITest e = new GUITest();
          e.pack(); //Modified setSize(700,500) to pack()
          e.setVisible(true);
          e.setResizable(false);
          e.setDefaultCloseOperation(EXIT_ON_CLOSE);
          e.setLocationRelativeTo(null);
     }
}

A:

GridLayout sizes all cells the same, i.e. your outer layout with 3 rows and 1 column makes 3 cells of all the same size.
Instead, use BorderLayout for your outer container and add the top, mid and lower panels with constraints BorderLayout.NORTH, BorderLayout.CENTER and BorderLayout.SOUTH respectively


Q:

Ambiguities in IBM JRE gencon policy and verbose:gc output

I'm assisting a project in tuning their application server environments, and am seeing some rather confusing output in the verbose:gc logs from the IBM JRE, which I'm much less familiar with than Hotspot. In many cases, what is there appears to contradict what I've seen in documentation from the vendor. This is for an app running on Websphere, running on IBM's 1.7_64 JRE. This particular run was with the gencon GC policy, with a 4GB heap size. Here is a sample of the verbose:gc output for a global GC that is a source of numerous ambiguities which I'll detail below:
<exclusive-start id="8574" timestamp="2015-09-08T22:48:45.819" intervalms="2919.893">
    <response-info timems="0.229" idlems="0.069" threads="43" lastid="0000000005FF6800" lastname="WebContainer : 37" />
</exclusive-start>
<sys-start id="8575" timestamp="2015-09-08T22:48:45.820" intervalms="3028473.245" />
<cycle-start id="8576" type="global" contextid="0" timestamp="2015-09-08T22:48:45.820" intervalms="3028473.281" />
<gc-start id="8577" type="global" contextid="8576" timestamp="2015-09-08T22:48:45.820">
    <mem-info id="8578" free="462493104" total="4155310080" percent="11">
        <mem type="nursery" free="80236904" total="934084608" percent="8" />
        <mem type="tenure" free="382256200" total="3221225472" percent="11">
            <mem type="soa" free="221195336" total="3060164608" percent="7" />
            <mem type="loa" free="161060864" total="161060864" percent="100" />
        </mem>
        <remembered-set count="16780" />
    </mem-info>
</gc-start>
<allocation-stats totalBytes="745771152" >
    <allocated-bytes non-tlh="193377184" tlh="552393968" />
    <largest-consumer threadName="WebContainer : 49" threadId="000000000659E600" bytes="156075608" />
</allocation-stats>
<gc-op id="8579" type="mark" timems="609.025" contextid="8576" timestamp="2015-09-08T22:48:46.429">
    <trace-info objectcount="9486509" scancount="7257956" scanbytes="246533016" />
    <finalization candidates="1528" enqueued="411" />
    <ownableSynchronizers candidates="32" cleared="0" />
    <references type="soft" candidates="63260" cleared="0" enqueued="0" dynamicThreshold="30" maxThreshold="32" />
    <references type="weak" candidates="27120" cleared="11" enqueued="0" />
    <references type="phantom" candidates="17361" cleared="7885" enqueued="7885" />
    <stringconstants candidates="153217" cleared="105"    />
</gc-op>
<gc-op id="8580" type="classunload" timems="1.114" contextid="8576" timestamp="2015-09-08T22:48:46.430">
    <classunload-info classloadercandidates="4306" classloadersunloaded="26" classesunloaded="26" quiescems="0.000" setupms="0.955" scanms="0.108" postms="0.051" />
</gc-op>
<gc-op id="8581" type="sweep" timems="18.520" contextid="8576" timestamp="2015-09-08T22:48:46.449" />
<gc-op id="8582" type="compact" timems="2209.475" contextid="8576" timestamp="2015-09-08T22:48:48.658">
    <compact-info movecount="9482641" movebytes="539414400" reason="compact on aggressive collection" />
</gc-op>
<gc-end id="8583" type="global" contextid="8576" durationms="2839.085" timestamp="2015-09-08T22:48:48.659">
    <mem-info id="8584" free="3615704600" total="4155310080" percent="87">
        <mem type="nursery" free="834618336" total="934084608" percent="89" />
        <mem type="tenure" free="2781086264" total="3221225472" percent="86">
            <mem type="soa" free="2620025400" total="3060164608" percent="85" />
            <mem type="loa" free="161060864" total="161060864" percent="100" />
        </mem>
        <pending-finalizers system="367" default="44" reference="7885" classloader="0" />
        <remembered-set count="15785" />
    </mem-info>
</gc-end>
<cycle-end id="8585" type="global" contextid="8576" timestamp="2015-09-08T22:48:48.659" />
<sys-end id="8586" timestamp="2015-09-08T22:48:48.659" />
<exclusive-end id="8587" timestamp="2015-09-08T22:48:48.659" durationms="2839.704" />

The issues include:
1) The timestamps for GC operations (marked gc-op) seem to be for when the operation finishes, not from when it starts. IBM doc implies that the timestamp is when that operation occurred (http://www-01.ibm.com/support/knowledgecenter/SSYKE2_7.0.0/com.ibm.java.zos.71.doc/diag/tools/gcpd_verbose_operation.html). However, when looking at the timestamps and durations for the operation (identified by timems attributes), the numbers don't add up. They do add up and make sense, however, if the timestamp is interpreted as when the operation finished, not when it started. To illustrate, in the example output above the following operations were performed, and these are their provided durations and timestamps (I've rounded the numbers):

    operation - duration - timestamp
    mark - 609ms - 48:46.429
    classunload - 1ms - 48:46.430
    sweep - 19ms - 48:46.449
    compact - 2209ms - 48:48.658

As one can see, the timestamps don't make sense if they're interpreted as the start time. They do, however, if interpreted as the end time. For instance, the classunload timestamp value equals the makr timestamp plus the classunload duration (not plus the mark duration as it should be if the timestamps indicate when the operations started). Similarly, the sweep timestamp equals the classunload timestamp plus the sweep duration.
Can someone confirm if this is expected behavior, or am I simply just reading this incorrectly?
2) Another issue appears to be that the entirely of every operation in the log appears to be a full-stop-the world operation from start to finish. I expected that the scavenge GCs would all be full stops, however, all the documentation I've seen from IBM has indicated that at least part of the mark phase of the global GC should be done concurrently. However, that is also not what is occurring in the GC log entry above. In this example, it appears that everything is done as a full-stop, and that no part of the mark or either the sweep is done concurrently. Per (older) documentation at least part of the mark should be done concurrently as not all as part of the stop-the-world pause (http://www.ibm.com/developerworks/java/library/j-ibmjava2/)
Is there a setting to make the global GCs in the tenured generation run part of the cycle concurrently? I know this is being done in the IBM JREs optavgpause collector as well as the Hotspot concurrent collector, neither of which are particularly new technology, so it's not clear why gencon is always forcing a full stop-the-world every time it has to do a global collection. This is important, as the 2.8 second pause indicated above is going to make us run afoul of our SLAs with the client.
3) In the global GC above it's apparent from the occupancy numbers of the nursery that it is also being collected during this operation (the nursery shows as only 8% free before the GC and 89% after). However, I'm not seeing the relevant information regarding a GC occuring in the nursery in the output. I would expect to see a scavange operation logged here. Does anyone know why this is missing? Is this because during a global GC the nursury is also collected via the same heap walking (mark-sweep-compact) approach as the tenured space is when a global GC occurs?

A:

You're right in that you're seeing stop of the world collections indicated by the exclusive-start and exclusive-end covering the whole cycle. What I find interesting is that you're seeing a global gc at a time when the heap is not even fully allocated.
The reason I think is that you have sys-start and sys-end entries which seem to indicate that something in your application (or a remote GC) is triggering a System.gc() and you should get this resolved first and get a new set of gc logs.


Q:

logback Failover tcp appender

I'm currently attempting to use the logback-logstash-encoder to write my logs to two different logstash instances. Both of these instances will be writing to the same Elasticsearch instance.
I'm struggling to find a way to load balance between the two logstash instances.
After reading both the logback documentation and the log4j2 documentation, its clear that the TcpAppender that logback-logstash uses does not support 'load-balanced' urls (i.e. url1, url2). In log4j2, I can approximate this behavior with the FailoverAppender.
Is there similar functionality in logback? Or will I need to stand up another service to load-balance for logback?

A:

AFAIK there is no support for load balancing within TcpAppenders. However, you could achieve load balancing by adding a hardware/software load balancer in front of the logstash boxes. In case a logstash process/box dies, the TCP connection gets reset, and the next log event should cause to re-establish the connection again.
This approach would require adding a load balancer to your setup. You would use the load balancer's address in your TcpAppender. The balancer handles the availability of logstash for you.
It depends on what you want to achieve. Is it not losing any log events? Then perhaps the better approach would be to write the logs into files and push the files by logstash-forwarder to your logstash boxes. If you're concerned about connection timeouts and slowdown of your application, then either async-appender or using UDP could be your choice.
HTH, Mark


Q:

Implementing 5 modes of operation with a hash function

Is it possible to implement any of the 5 modes of operation (ECB, CBC, OFB, CFB, CTR) with a hash function?

A:

The modes you are referencing are specifically modes of operations for block ciphers, and therefore are not directly applicable to hash functions. Block cipher operations take 2 inputs, the key and a block-sized input value, and output a block-sized keyed permutation of the input. Hash functions take a variable length input, and output a fixed length value.
However, the way 3 of them work can be applied hash functions, by using HMAC or NMAC to turn the hash into a keyed pseudorandom function.
CTR:
In the block cipher we have:
$C_i = P_i \oplus Enc_k(Nonce \ || \ Ctr_i)$
Applying to the hash we have:
$C_i = P_i \oplus HMAC_k(Nonce \ || \ Ctr_i)$
OFB:
In the block cipher we have:
$O_0 = IV$
$O_i = Enc_k(O_{i-1})$
$C_i = P_i \oplus O_i$
Applying to the hash we have:
$O_0 = IV$
$O_i = HMAC_k(O_{i-1})$
$C_i = P_i \oplus O_i$
CFB:
In the block cipher we have:
$C_0 = IV$
$C_i = P_i \oplus Enc_k(C_{i-1})$
Applying to the hash we have:
$C_0 = IV$
$C_i = P_i \oplus HMAC_k(C_{i-1})$
Because of the way these modes work, by not requiring the decryption operation, a keyed one-way function can perform the same function, which is the cryptographic transformation of the input to XOR against the plaintext and generate the ciphertext. They make these schemes stream ciphers.
Because the output size of secure hash functions (SHA256 or SHA512) is generally larger than the block size of a block cipher (AES), using these hash functions may be able to encode a larger amount of plaintext before running into the problems these modes may experience with block ciphers. The additional flexibility of a variable length input also allows the hash functions to have larger nonces/IVs.
However since they are not permutations, the security proofs that apply to block ciphers may not apply to hash functions when used in these modes. Additional security may be provided by truncating the output of the hash function before encrypting the plaintext, but still feeding the full output back in the case of OFB and CFB.
From a performance perspective, most hash functions are slower than most block ciphers, by a wide margin. Using HMAC also requires additional hash operations to generate the secret initial values, however an implementation can do these once per plaintext if the IV and input length of a hash function can changed arbitrarily.


Q:

Command line to start visual studio and disable add ins/Extensions for that instance

I am writing a Visual Studio template wizard.  And to debug it I have it start a new instance of Visual Studio 2010.
My Visual Studio 2010 takes a good while to start up.  I believe that this is due the the add-ins and extensions that I have installed for visual studio.
I would rather not go disable them all (I really like them).  So I was hoping there was a way to disable them via the command line.
Just run a clean Visual Studio instance.
Is there a way to do that?

A:

Try safemode
devenv.exe /safemode

which

Starts Visual Studio in safe mode, and loads only the default environment and services, and shipped versions of third-party packages.

See http://msdn.microsoft.com/en-us/library/xee0c8y7.aspx


Q:

android read barcode value from textbox value

I want to make a small application that lets the user enter a barcode number into a text box. Then he can scan a barcode and if the barcode number in the text box matches the barcode scanned, a small message is displayed, saying 'matched'.
For some reason the barcode I enter does not find a match even though I have given the exact barcode number that I am scanning. What am I doing wrong?
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    //retrieve scan result
    IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);

    if (scanningResult != null) {
        String scanContent = scanningResult.getContents();
      //String scanFormat = scanningResult.getFormatName();
        contentTxt.setText(scanContent);
        doSomething();
    }
    else{
        Toast toast = Toast.makeText(getApplicationContext(),
            "No scan data received!", Toast.LENGTH_SHORT);
        toast.show();
    }
}
//Output a message if the barcode matches the code stated in 'scanContent'
public void doSomething(){
    if (codeNumber.getText() == contentTxt.getText()) {
        Toast toast = Toast.makeText(getApplicationContext(), "We have a match!", Toast.LENGTH_LONG);
        toast.show();
    }
    else {
        Toast toast = Toast.makeText(getApplicationContext(), "DOES NOT MATCH!", Toast.LENGTH_LONG);
        toast.show();
    }
}

A:

My guess is that you come from the world of C. Welcome friend.
In Java, one does not simply compare two String instances, since String is an object, not a primitive type.
By using the == operand, you're comparing both string objects' addresses in memeory. Since in your case they're not the same object, the result is FALSE.
To compare the values, use String.equals():
if (contentTxt.getText().toString().equals(codeNumber.getText().toString())) {


Q:

Efficiently get Observable of an array BehaviorSubjects

I have this field:
smartArray: BehaviorSubject<BehaviorSubject<object>[]>;
//Example
[{key1: 'value1', key2: value2},...];

I now want to get and subscribe to one of the properties:
getObeservablePropertyOfSmartArray(index, property){
   return this.smartArray.pipe(
         //...getelementAtIndex <---dont know how
         //lets say the elementatIndex is elem:
         elem.pipe(
         //get the property and return the Observable

         )).asObservable();
}

So I basically need the equivalent of array[index] and object[key] and return Obeservable for BehaviorSubjects.
How can I do that?

A:

you can use mergeMap to switch to that observable on the index, then you can use map to get the property value that you want
I made example for you here: https://stackblitz.com/edit/angular-qzeuzt


Q:

Correlation matrix of grouped variables in dplyr

I have a grouped data frame (using dplyr) with 50 numeric columns, which are split into groups using one of the columns. I want to calculate a matrix of correlation between all non grouping columns and one particular column.
An example with the mtcars dataset:
data(mtcars)
cor(mtcars[,2:11], mtcars[,2])

returns a list of correlations between miles per galleon and the other variables.
Let's say however, that I wish to calculate this same correlation for each group of cylinders, e.g.:
library(dplyr)
mtcars <-
    mtcars %>%
    group_by(cyl)

How would I do this? I am thinking something like
mtcars %>%
    group_by(cyl) %>%
    summarise_each(funs(cor(...))

But I do not know what to put in the ... as I don't know how to specify a column in the dplyr chain.
Related:
Linear model and dplyr - a better solution? has an answer which is very similar to @akrun's answer. Also, over on cross validated: https://stats.stackexchange.com/questions/4040/r-compute-correlation-by-group has other solutions using packages which are not dplyr.

A:

We could use do.
library(dplyr)
mtcars %>%
       group_by(cyl) %>%
       do(data.frame(Cor=t(cor(.[,3:11], .[,3]))))

NOTE: t part is contributed by @Alex
Or
library(data.table)
d1 <- copy(mtcars)
setnames(setDT(d1)[, as.list(cor(.SD, .SD[[1]])) , cyl,
                            .SDcols=3:11],  names(d1)[2:11])[]