text:
Q: Why is AMD Pro GPU slower than generic Intel GPU on hybrid laptop? My laptop is HP ZBook 14u G5 (https://support.hp.com/rs-en/document/c05873311), with two GPU:

*

*Intel UHD Graphics 630

*AMD Radeon Pro WX 3100

On Ubuntu 19.04, I'm able to see both graphic cards:
$ inxi -G

Graphics:  Device-1: Intel UHD Graphics 620 driver: i915 v: kernel
           Device-2: Advanced Micro Devices [AMD/ATI] Lexa XT [Radeon PRO WX 3100] driver: amdgpu v: kernel
           Display: x11 server: X.Org 1.20.4 driver: amdgpu resolution: 1920x1080~60Hz
           OpenGL: renderer: Mesa DRI Intel UHD Graphics 620 (Kabylake GT2) v: 4.5 Mesa 19.0.2

And I'm able to select which GPU to use for a given application using the DRI_PRIME environment variable:
$ DRI_PRIME=0 glxinfo | grep "OpenGL renderer"
OpenGL renderer string: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
$  DRI_PRIME=1 glxinfo | grep "OpenGL renderer"
OpenGL renderer string: AMD Radeon Pro WX3100 (POLARIS12, DRM 3.27.0, 5.0.0-19-generic, LLVM 8.0.0)

What bugs me is that the integrated GPU (Intel) seems to perform better than the discrete GPU (AMD Pro), whereas I expected the Pro GPU would be largely better. I have observed that in Steam games (I passed the DRI_PRIME variable to select the GPU when launching the games), but also when launching benchmarks:

*

*with Intel integrated GPU:

$ DRI_PRIME=0 glmark2
=======================================================
    glmark2 2014.03+git20150611.fa71af2d
=======================================================
    OpenGL Information
    GL_VENDOR:     Intel Open Source Technology Center
    GL_RENDERER:   Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2)
    GL_VERSION:    3.0 Mesa 19.0.2
=======================================================
[build] use-vbo=false: FPS: 2670 FrameTime: 0.375 ms
[build] use-vbo=true: FPS: 2997 FrameTime: 0.334 ms
[texture] texture-filter=nearest: FPS: 2753 FrameTime: 0.363 ms
[texture] texture-filter=linear: FPS: 2806 FrameTime: 0.356 ms
[texture] texture-filter=mipmap: FPS: 2413 FrameTime: 0.414 ms
...Ctrl+C
=======================================================
                                  glmark2 Score: 2727
=======================================================

*

*with AMD Pro discrete GPU:

$ DRI_PRIME=1 glmark2
=======================================================
    glmark2 2014.03+git20150611.fa71af2d
=======================================================
    OpenGL Information
    GL_VENDOR:     X.Org
    GL_RENDERER:   AMD Radeon Pro WX3100 (POLARIS12, DRM 3.27.0, 5.0.0-19-generic, LLVM 8.0.0)
    GL_VERSION:    4.5 (Compatibility Profile) Mesa 19.0.2
=======================================================
[build] use-vbo=false: FPS: 501 FrameTime: 1.996 ms
[build] use-vbo=true: FPS: 591 FrameTime: 1.692 ms
[texture] texture-filter=nearest: FPS: 538 FrameTime: 1.859 ms
[texture] texture-filter=linear: FPS: 589 FrameTime: 1.698 ms
[texture] texture-filter=mipmap: FPS: 598 FrameTime: 1.672 ms
...Ctrl+C
=======================================================
                                  glmark2 Score: 563
=======================================================

Is it normal? Is there a way to investigate more? Is there any hope to get better performance in Ubuntu with the AMD Pro GPU?
Thanks in advance to all.


text:
Q: Why this subquery is 10x faster than inner join I have two tables ecdict and favourite and one view which just inner join two tables.
CREATE TABLE ecdict('_id' INTEGER PRIMARY KEY, 'word' VARCHAR NOT NULL UNIQUE, 'meaning' VARCHAR, 'phonetic_string' VARCHAR, 'example' VARCHAR);
CREATE TABLE favourite('_id' INTEGER PRIMARY KEY, 'word' VARCHAR NOT NULL UNIQUE);

CREATE VIEW favourite_word as select ecdict.* from ecdict INNER JOIN favourite ON ecdict.word = favourite.word;

Here is the execution time of result:
Time: 0.010
select ecdict.* from ecdict where word in (select word from favourite);

Time: 0.226
select * from favourite_word;

Why they differ so much? It if is related to query plan, why sqlite chooses a slower one? How can I guide sqlite to choose the faster one? Thanks

A: You need to look at the query plan to see what is really happening.  The following is (informed) speculation.
When you have an inner join with two sets of indexes, you basically have two possible query plans:

*

*Scan the edict table and look up words in the favourites using the index on favourite.word.

*Scan the favourite table and look up words in edicts using the index on edicts(word).  Then look up the record in edit when there is a match.

(A unique contraint creates an index.)
All these being equal -- that is, with no information about table sizes -- the first approach would be preferred in this case.  Why?  Because there is no additional step to look up the additional columns.
When you phrase the query using in, I think that SQLite will always use the first approach.  In this case, I am guessing that the favourite table is much smaller than the edict table, so the second approach is actually better.  When you write the query as a join, both possibilities are considered and the better one is chosen.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Formsheet ios 8 constraints are same as iphones constraints I have this problem where formsheet in ios 8 is taking the constraints set for "compact - width regular -height" (that is all iPhones constraints) instead of "any- any" or "regular -width regular -height".
I have two different design for iPhone and iPad since the formsheet is consuming iPhones constraint iam
not able to achieve the same. Any help on this would be aprreciatd

A: From the UIViewController class reference:

In a horizontally regular environment, a presentation style that displays the content centered in the screen. The width and height of the content area are smaller than the screen size and a dimming view is placed underneath the content. If the device is in a landscape orientation and the keyboard is visible, the position of the view is adjusted upward so that the view remains visible. All uncovered areas are dimmed to prevent the user from interacting with them.
In a horizontally compact environment, this option behaves the same as UIModalPresentationFullScreen.

Because the form sheet presentation on iPad is compact width and regular height, these are the values you'll get when you present a form sheet.

If you don't want the default size classes you can override them.
If your view controller is a child view controller of another, you can use setOverrideTraitCollection(_:forChildViewController:) and override the size class constraints for the child controller.
If your view controller is NOT a child view controller, you're not really supposed to change the trait collection, but you can do it using this hack.

The best solution would be to design your view controller to look appropriate in the default (correct) size constraints applied for a form sheet view controller presentation. You can usually do this by avoiding setting width constraints and only setting leading and trailing constraints.

A: Another solution is to use vc.presentationController.overrideTraitCollection
    // in landscape mode, we want the horizontal traits to be the same as the main screen
    if ( UIScreen.mainScreen.traitCollection.horizontalSizeClass ==  UIUserInterfaceSizeClassRegular){

        //if you use UIModalPresentationFormSheet, the traits horizontal will be compact , even on iPad, so we have tell the presentationcontroller to force the horizontaltraits to regular
        vc.modalPresentationStyle=UIModalPresentationFormSheet;
        vc.presentationController.overrideTraitCollection = [UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassRegular ];
        [_rootViewController presentViewController:vc animated:true completion:^{}];
}

A: I found a different way to solve this for presented view controllers, such as form sheets which are not child view controllers.
I override viewWillLayoutSubviews and then layout based on the presenting view controller's trait collection.
override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()

    if let presenting = presentingViewController {
        updateLayout(forSizeClass: presenting.traitCollection.horizontalSizeClass)
    }
}

Where updateLayout(forSizeClass:) is our function which does whatever we need to do to support the trait environment.
The benefit of this approach is that we are not explicitly checking the device type (.pad or .phone) and we are not explicitly thresholding the view size (which may change in the future). This approach natively supports iPad split view, allowing your layout to fallback to an iPhone style layout when the presenting view controller hits a .compact size class.
The primary assumption here is that your presenting view controller is full screen. But for form sheets this is often the case.


text:
Q: Assert in silex with defined options Want to assert a function in Silex with some pre-defined slugs. My idea is to have this code, but to have the choice to add in the slug assert some different assertions as 'about-us', 'contact' and 'services'. Any idea?
$app->get('/{slug}', function ($slug) use ($app) {

[...]

})
->bind('page')
->assert('slug', 'about-us')
;

A: You can use regular expressions in the second argument of assert method. Add list of available slug values:
->assert('slug', 'about\-us|contact|services');


text:
Q: prevent kill frame instead of asking how to kill frame. i interested to know what technique can be used to prevent an iframe inside a page from been killed by "frame killer"

A: There is always, unfortunately a way to get round frame killers, because of the way they work. (The site that is being framed can usually, however, display a warning).
See Jeff Atwood's "disturbing revelation".
A few choice excerpt:

If an evil website decides it's going
  to frame your website, you will be
  framed. Period. Frame-busting is
  nothing more than a false sense of
  security; it doesn't work.

Frame busting code (from the linked Stack Overflow challenge):
<script type="text/javascript">
    var prevent_bust = 0
    window.onbeforeunload = function() { prevent_bust++ }
    setInterval(function() {
      if (prevent_bust > 0) {
        prevent_bust -= 2
        window.top.location = 'http://server-which-responds-with-204.com'
      }
    }, 1)
</script>

This code does the following:

*

*increments a counter every time the
browser attempts to navigate away
from the current page, via the
window.onbeforeonload event handler

*sets up a timer that fires every
millisecond via setInterval(), and if
it sees the counter incremented,
changes the current location to a
server of the attacker's control

*that server serves up a page with
HTTP status code 204, which does not
cause the browser to navigate
anywhere

A: Happily, there is nothing that works outside of Internet Explorer (which lets JS be disabled in iframes as a security feature).
If the author of a site doesn't want their pages framed, then that is their choice.


text:
Q: The "inline" keyword in C++ So the keyword "inline" will result in the call being replaced by the body of the function correct?
So I'm guessing that means we skip the call entirely? Like if we look at the .asm file we wouldn't find a call instruction?

A: Keyword inline is misleading - it is neither necessary nor sufficient for actual inlining to happen. All it does: it tells the linker to allow multiple definitions of the function, which means you can place the function in a header. Once you do it, the compiler has a better chance to inline since the function body becomes visible in more places. In modern systems, it is not important anymore if they use whole code optimization.
Once the compiler has a chance to inline, it has to decide whether it is beneficial for whatever optimization you asked it to do (e.g. optimize for speed).
If the compiler decides to inline, then what you say about .asm file is correct - no call of the function.

A:
So the keyword "inline" will result in the call being replaced by the body of the function correct?

Incorrect.

So I'm guessing that means we skip the call entirely? Like if we look at the .asm file we wouldn't find a call instruction?

Yes, if compiler expands a function call inline, then there will not be a function call indeed.
But the inline keyword does not mean that calls to the function are guaranteed to be expanded inline.


text:
Q: PHP, PDO, MySQL - Multiple INSERT vulnerable to injection? In my application (PHP) I am going to request ~3000 rows from an API and insert these in a MySQL table using the PDO driver.
Although the data to be inserted isn't user input, it is out of my hands how the data is handed to me.
Because it is important that the ~3000 inserts go as fast as possible I want to use a multiple insert like so (?,?,?),(?,?,?),....
I was wondering whether doing a multiple insert has effect on the vulnerability for a MySQL injection? Because I 'build' the query using PHP code.
My 'test' code is:
<?php

    class DBCon {
        private static $instance = null;
        private $db;

        private function __construct() {
            $this->db = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'root', '');
            $this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }

        public static function getDB() {
            if (self::$instance === null) {
                self::$instance = new self();
            }
            return self::$instance->db;
        }
    }

    function createItems($array) {
        $sql = 'INSERT INTO `table`(`text`, `int`, `bool`) VALUES ';

        $insertArray = array();
        foreach ($array as $arrayItem) {
            $sql .= '(';
            foreach ($arrayItem as $arrayItemItem) {
                array_push($insertArray, $arrayItemItem);
                $sql .= '?,';
            }
            $sql = rtrim($sql, ',');
            $sql .= '),';
        }
        $sql = rtrim($sql, ',');

        var_dump($sql);
        var_dump($insertArray);

        try {
            $query = DBCon::getDB()->prepare($sql);
            $query->execute($insertArray);
        } catch (PDOException $e) {
            echo '

query failure';
        }
    }

    $array = array(array('a piece of text',123,0),array('a piece of text',123,0));

    createItems($array);

$sql contains:
index.php:36:string 'INSERT INTO `table`(`text`, `int`, `bool`) VALUES (?,?,?),(?,?,?)' (length=65)

$insertArray contains:
index.php:37:
array (size=6)
  0 => string 'a piece of text' (length=15)
  1 => int 123
  2 => int 0
  3 => string 'a piece of text' (length=15)
  4 => int 123
  5 => int 0

A:
I was wondering whether doing a multiple insert has effect on the vulnerability for a MySQL injection? Because I 'build' the query using PHP code.

Well, in the real life we cannot avoid manual query building, thus it's all right to create a query or two dynamically. The only rule you have to follow in this case is all query parts have to be hardcoded in your script.
As long as it's followed, no injection will be ever possible.
In your case all query parts are hardcoded, thus this code is safe.

A: As long as those values are being handled by PDO parameterized queries then it will escape any attempted injections.
https://stackoverflow.com/a/134138
If you aren't using PDO, then you need to make sure all data is correctly escaped, which is a lot of work.
To see what query was actually executed by the MySQL server, you can follow these instructions to set up the general log:
https://stackoverflow.com/a/2413308


text:
Q: Javascript stop form submittion I'm using this event listener to for the submit buttons:
document.forms[formID].addEventListener('submit',validate);

I want to make the page stay as it is when submitting without refreshing or redirecting,
this is the validate function, and the return false; doesn't work
function validate() {

    CheckedN = this.name;
    CorrectAnswer = questions.correctAns[CheckedN];
    UserAnswer = -1;

    for (var i=0; i < 4; i++) {
        if (this.answerN[i].checked === true) {
            UserAnswer = i;
        }
    }

    if (UserAnswer === -1) {alert("Please choose an answer");}
    else {
        if (UserAnswer === CorrectAnswer) {alert("You are correct!");}
        else {alert("You are wrong!");}
        }

return false;
}

what am I doing wrong?
thanx

A: Edit: You've said in a comment elsewhere that you're using jQuery. That's surprising because your code isn't using it to hook up the event handler.
If you're using jQuery, this gets a lot simpler (as I mentioned below in the "off-topic" bit).
Hook it up like this:
$(document.forms[formID]).submit(validate);

And change your validate function to accept an event parameter and call preventDefault on it:
function validate(event) {
    event.preventDefault();
    // ...rest of function here
}

jQuery smooths over all of the issues listed below.

Original answer:
Some things to change (but see also the off-topic note at the very end):

*

*Your addEventListener call is missing a parameter, it should be:
document.forms[formID].addEventListener('submit',validate,false);
//                                                        ^--- required

*Your validate function will receive an event object (on standards-compliant browsers). It should have a preventDefault function on it, which when called stops the default action of the browser (submitting the form). So declare the argument and call the function on it if it's there.

*Sadly, to support IE you have to use attachEvent rather than addEventListener (which they only started supporting in IE9).

*And also sadly, to support IE you have to handle the fact that they treat the event object as a global rather than passing it in.

*AND there may not be a preventDefault function on it. sigh
So all told, hookup:
var form = document.forms[formID];
if (form.addEventListener) {
    // Standards
    form.addEventListener('submit',validate,false);
}
else if (form.attachEvent) {
    // IE
    form.attachEvent('onsubmit', validate); // No third parameter, note the "on"
}
else {
    // REALLY old browser
    form.onsubmit = validate;
}

Then the function:
function validate(event) {
    var valid;

    event = event || window.event; // Handle IE difference

    CheckedN = this.name;
    CorrectAnswer = questions.correctAns[CheckedN];
    UserAnswer = -1;

    for (var i=0; i < 4; i++) {
        if (this.answerN[i].checked === true) {
            UserAnswer = i;
        }
    }

    if (UserAnswer === -1) {
        alert("Please choose an answer");
    }
    else {
        if (UserAnswer === CorrectAnswer) {
            alert("You are correct!");
        }
        else {
            alert("You are wrong!");
        }
    }

    // Both preventDefault and return false, to cover various browser
    if (event.preventDefault) {
        event.preventDefault();
    }
    return false;
}

Off-topic: As you can see, there are a lot of browser inconsistencies that you have to deal with there. Rather than doing it yourself, I recommend using a library like jQuery, Prototype, YUI, Closure, or any of several others to smooth over those inconsistencies for you (and also provide a lot of other handy utility stuff) so you can concentrate on what you're actually trying to do without sweating the small stuff.

A: document.getElementById(formId).onsubmit = validate;

Or even simpler, in your page markup, do:
<form id="myFormId" onsubmit="return validate();">
    <!-- Form content here -->
</form>

A: This is off the top of my head but I think the html control that submits the form should be something like this:
<input type="submit" value="submit this form" onclick="return validate()"/>

A: This would work in all browsers using plain JS. Let the downvote fest begin
http://jsfiddle.net/mplungjan/zUFEw/
window.onload=function() {
  document.forms[0].onsubmit=validate;
}

function validate() {
  var CheckedN = this.name;
  var CorrectAnswer = questions.correctAns[CheckedN];
  var UserAnswer = -1;
  for (var i=0, n=this.answerN.length; i < n; i++) {
    if (this.answerN[i].checked) {
      UserAnswer = i;
      break; // assuming only one answer
    }
  }

  if (UserAnswer === -1) {alert("Please choose an answer");}
  else {
    if (UserAnswer === CorrectAnswer) {alert("You are correct!");}
    else {alert("You are wrong!");}
  }
  return false; // will always stop submission unless there is an error above
}

PS: NEVER call anything in a form for name="submit" or id="submit"

A: If you can use jquery, you can use:
event.preventDefault()

Like:
$("#formId").submit(function(event) {
...
  event.preventDefault();
...
});

http://api.jquery.com/event.preventDefault/

A: Try this
document.forms[formID].addEventListener('submit', function(event)
{
     event.preventDefault();
     CheckedN = this.name;
    CorrectAnswer = questions.correctAns[CheckedN];
    UserAnswer = -1;

    for (var i=0; i < 4; i++) {
        if (this.answerN[i].checked === true) {
            UserAnswer = i;
        }
    }

    if (UserAnswer === -1) {alert("Please choose an answer");}
    else {
        if (UserAnswer === CorrectAnswer) {alert("You are correct!");}
        else {alert("You are wrong!");}
        }

return false;

}, false);

Alternatively, you may try to just change the validate() to validate(event) and call  event.preventDefault(); in there, but I'm not 100% on that.


text:
Q: Python decoding bytes object returns an empty string Excuse me if this is a duplicate. I've searched a lot before posting this and actually found many similar posts, but couldn't solve my problem yet.
I'm trying to decode a bytes object in python 3.8 and keep failing.
The bytesObject object is like this
b'January,February,March\n0,3,0\n'
and print(type(bytesObject)) shows <class 'bytes'>.
All the below return an empty string, what am I missing here?
bytesObject.decode("UTF-8")
str(bytesObject)
str(bytesObject.decode())
repr(bytesObject)
repr(bytesObject.decode())
bytesObject.text

Its text encoding is certainly UTF-8.
I also tried csv reader and json converters too but still no success.


text:
Q: Is there any way to retrieve data from database on same page I have a page which pick data from SQL database and show in table (some columns of table are hidden). When I click on any row of table a modal launch.
I want to show detail of clicked row in modal which launch on same page without page refreshing.
Any help regarding this scenario?

A: You need to do in steps

*

*Each edit or view button should contain ID of the record

*On Click, get Record ID via JQuery

*Send AJAX or JQuery Request to fetch record based on record ID

*Publish that data in the modal

*On closing model, make all info clear

Answer Updated (JQuery exmaple)
var id = $(this).attr('id');
$.ajax({
    type: 'post',
    url: 'filename.php',
    data: "id="+ id,
    dataType: 'json',
    success: function(response) {
    //get response and populate data in model
}


text:
Q: Page Transition in windows store application I am developing windows store application, in which I want to incorporate page transitions(page entrance effects), when the other page is loaded or come to screen in response of an event in first screen. How can I do this?
Thanks.

A: this is an example how you can accomplish that..
<Page.Transitions>
     <TransitionCollection>
        <EntranceThemeTransition />
      </TransitionCollection>
   </Page.Transitions>


text:
Q: Targeting the last div before flexbox or float wraps the rest I am wondering if there is a CSS selector that would auto-magically target the last div on a row created by either flexbox or floats.
In our particular use, we have an image grid with different width images.  In its full width, there are rows with 3 images (each 33%) and rows with 2 images (50/50 or 60/40).  When viewed with a vertical tablet all images change to 50% and it is two per row, on a phone 100%.  All of the images are within a single overall container, not row containers (because of the three becoming two).
Like many grid type layouts we have a 2% margin-right, that needs to be reset to 0 on the right most div.
Currently using the traditional "last" class to remove the margin manually and a pseudo :nth-child(odd) to manipulate the vertical tablet layout. I am playing with two variations, one using floats and one using flexbox.
Is there a single css selector that would target the last div in each case?

Expanding on layouts:
On full sized monitor
|img1 - 33%|2%|img2 - 33%|2%|img3 - 33%|
|img4 - 40%|2%|img5 - 60%|
|img6 - 33%|2%|img7 - 33%|2%|img8 - 33%|
On a vertical tablet
|img1 - 50%|2%|img2 - 50%|
|img3 - 50%|2%|img4 - 50%|
|img5 - 50%|2%|img6 - 50%|
|img7 - 50%|2%|img8 - 50%|
On phone
|img1 - 100%|
|img2 - 100%|
|img3 - 100%|
|img4 - 100%|
etc
ps I know my percentages do not add up.

A: Basically what @vals said, but with some more details:

*

*Let all flex items have the same margin-right, m.

*Set the widths accordingly. For example, if you want n equal elements in a row, set width: calc(100%/n - m).

*Let the flex container overflow its containing block, in order to hide the unwanted margin margin. Use margin: -m to achieve this.

*Place the flex container in a wrapper with overflow: hidden.

.wrapper {
  overflow: hidden;
  border: 1px solid;
}
.flex {
  display: flex;
  flex-wrap: wrap;
  margin-right: -2%;
  text-align: center;
}
span {
  margin-right: 2%;
  border: 1px solid red;
  box-sizing: border-box;
}
span:nth-child(-n + 3) { width: calc(100%/2  - 2%); }
span:nth-child(n + 6)  { width: calc(100%/3  - 2%); }
span:nth-child(1)      { width: calc(100%    - 2%); }
span:nth-child(4)      { width: calc(100%*.4 - 2%); }
span:nth-child(5)      { width: calc(100%*.6 - 2%); }

    100%
    49%
    49%
    39%
    59%
    32%
    32%
    32%

A: No, there is not a cool CSS selector that can achieve this.
The only way that I know to get this efect easily is to set a wrapper to your flexbox container.
Let all the elements inside the flexbox container to have the same 2% margin right.
And set the flexbox container to have a 2% overflow to the right of the wrapper, that will be hidden. So you get the illusion that the elements align with the right border of the wrapper.


text:
Q: Ext JS 4: Ext.Component focus and blur events I have been working on this simple test code, and I can't seem to get the focus and blur events to work properly. What I'm imagining is the user moving their mouse over the window (fires focus event), and then the user moves their mouse out of the window (fires blur event). Unfortunately, this is not the case, and maybe I'm just misunderstanding blur and focus.
Ext.create('Ext.window.Window', {
  height: 300,
  width: 300,
  title: 'blah',
  autoShow: true,
  listeners: {
    focus: function() {
      alert('focused!');
    },
    blur: function() {
      alert('blurred!');
    }
  }
});

Fiddle
Now, I did find this Stack post... very interesting that you can put el inside of listeners like that. Unfortunately, it looks like when the page loads, the window gains focus and then loses it right away... same if I hover over it. So I'm confused. The API says you can use focus and blur just like every other listener (no mentioning of wrapping it in el), but this post says you need to wrap it in el?

A: This is JavaScript 101, and I still get it wrong.  Focus and blur are for when you click the element (gains view focus) and when you click out of the element (loses view focus), respectively.  The only strange thing is, why does window.focus() not actually fire the focus event?  It's most likely because it doesn't fire any events, but why is that?  You would think a method called focus would fire the focus event.


text:
Q: Van der Waals gas and non physical regions When we draw P-V diagram of a Van der Waals gas, we get loops and since in the centre region of the loops, $\frac{dP}{dV}$ is +ve. Based on these regions we argue that the gas is unstable in that region as suppressing the volume of the gas is not resisted by the gas and it happily decreases its pressure. (Taken from lectures by Prof. David Tong).
However my question is that how can we argue on the basis of Van der Waals potential that the region is an unstable region? Isn't it possible that the said region is just a manifestation of the approximate Partition Function and has nothing to do with real gases ?

Source:https://en.wikipedia.org/wiki/File:Van_der_Waals_Isotherms.PNG

A: I am not sure if this will answer your question, but I wonder about a couple of things that might be useful.
First is the equivalent diagram for a real gas.

image from https://upload.wikimedia.org/wikipedia/commons/thumb/3/3e/Real_Gas_Isotherms.svg/600px-Real_Gas_Isotherms.svg.png
Note for a real gas there are horizontal lines where a mixture of gas and liquid exists in equilibrium together. On one of the horizontal lines if the pressure is reduced more gas (or vapour) is formed above the liquid - if the pressure is increased then more liquid is formed from the gas. When all the gas is converted to liquid the pressure rises steeply as the volume is decreased. When all the liquid has vapourized to form the pressure starts to drop as the volume is increased further.
Now the key thing is that in reality the Van Der Waals gas forms a liquid on compression if it is below the critical temperature.
Now I think the most relevant thing to your question now is the following.

*

*the gas equations for the Van Der Waals gas do not allow the gas to form a liquid in the way a real gas behaves, but the term $(p + a/Vm^2)$ does mean that the pressure is reduced due intermolecular attractive forces - thus the smaller the volume the closer the gas molecules are together and the lower the pressure that they exert.

*The attractive forces between molecules mean that $dP/dV$ can be $+ve$ - the physical interpretation is that the attractive forces between the molecules pull the molecules together... this is a bit like a real gas turning into a liquid.

*The Van der Waals intermolecular potential has a minimum energy at some molecular separation $r$ - for separations greater than $r$ the potential rises... It is simple to argue that there is attraction between the molecules for separations greater than $r$.
Thus, in conclusion the Van der Waals potential tells us that molecules attract each other - and below the critical temperature this can lead to the 'unstable' behaviour you describe in your question.


text:
Q: getting the view of item on which context menu item has been called I am creating a list of TextView on which I am creating a context menu. However how do I know on which TextView the context menu was called?
Here is my code
http://snipt.org/vfyj7

A: You can get all necessary information from MenuItem:

AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

item.position contains selected item position.

A: In this particular override for your activity, you can get the id of the textView that was clicked and then do necessary operations based on the textView.
  @Override
    public boolean onContextItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        return super.onContextItemSelected(item);

        if(item.getItemId()==R.id.textView1) {
       //do something with 1st textview
     }
     else if(item.getItemId()==R.id.textView2) {
      //do something with textview 2
    } and so on....
    }


text:
Q: Ubuntu 13.10 64 bit live USB created with UNetbootin either not recognised or "Disk Error" on Dell D630 BIOS A17 I know, I know, this question has been asked so many times but I have searched and searched and tried and tried but I can't get it to work.
I'm running Windows XP on my Dell D630. I downloaded the 64 bit Ubuntu 13.10 iso from the download page and "burnt" it to a FAT32 formatted 2GB USB drive with UNetbootin. I set up my BIOS so that USB devices are first in the boot sequence and even pressed F12 at the splash screen to make absolutely sure it was trying to boot from the USB drive. I removed all other USB devices, even my wireless USB mouse, but I get the dreaded "Disk Error" message. I have followed all the answers to similar questions on setting up the BIOS correctly, so enabling USB devices in the POST menu, enabling USB emulation etc. I have read about the difference between USB-HDD and USB-ZIP but I can't find any option relating to this in the BIOS so if this is the issue then I'd like to know how else to fix it.
No worries, I tried again with another USB flash drive I had spare, this time 1GB, I did everything specified above except this time there is no disk error but instead the flash drive appears to be unrecognised. This is only my assumption: when I select USB device from the boot menu, the screen goes black with a blinking cursor ("_") for barely a second then the laptop boots as normal. I even tried removing the HDD but then I am informed that there are no bookable devices.
I can boot from a 32 bit Ubuntu 12.10 DVD if it's any help. The laptop is a Dell D630 with an Intel T7100 processor, DT781 P/N motherboard (Intel graphics version), 1GB memory in each slot (so 2GB overall) and BIOS version A17.
Help would be much appreciated

A: Try to make your usb bootable using Universal USB Installer
and try again.


text:
Q: freeswitch received audio delayed for 20-30 seconds I manage to make a very simple configuration for basic phone to phone calls using FreeSwitch, When i Calls A -> B (and B answered), A can hear B instantly, but B cannot hear A, after waiting for 20-30 seconds finally B can hear A , is there something missed so when the calls answered B can hear A without waiting for long seconds?
Click here to see picture of more detailed flow of calls
Im using Zoiper for both phone, and using these configuration
Dialplan :
    <context name="dialAndalabs">
        <extension name="666">
            <condition field="destination_number" expression="^666$">
                <action application="set_audio_level" data="read 4" />
                <action application="set_audio_level" data="write 2" />
                <action application="ring_ready"/>
                <action application="set" data="ringback=%(2000, 4000, 440.0, 480.0)"/>
                <action application="sleep" data="1000"/>
                <action application="bridge" data="user/hp-andalabs"/>
            </condition>
        </extension>
        <extension name="667">
            <condition field="destination_number" expression="^667$">
                <action application="set_audio_level" data="read 4" />
                <action application="set_audio_level" data="write 2" />
                <action application="ring_ready"/>
                <action application="set" data="ringback=%(2000, 4000, 440.0, 480.0)"/>
                <action application="sleep" data="1000"/>
                <action application="bridge" data="user/wira"/>
            </condition>
        </extension>
        <extension name="777">
            <condition field="destination_number" expression="^777$">
                <!--<action application="bridge" data="user/777"/>-->
                <action application="answer"/>
                <action application="sleep" data="10000"/>
                <action application="bridge" data="loopback/app=voicemail:default ${domain_name} ${dialed_extension}"/>
            </condition>
        </extension>
    </context>

SIP Profile :
    <profile name="exampleTestAndalabs">
        <settings>
            <!--<param name="alias" value="sip:$${local_ip_v4}:5062"/>-->
            <param name="shutdown-on-fail" value="true"/>
            <param name="user-agent-string" value="FreeSWITCH v1.6 Andalabs 2016"/>
            <param name="debug" value="0"/>
            <param name="sip-trace" value="yes"/>
            <param name="context" value="dialAndalabs"/>
            <param name="use-rtp-timer" value="true"/>
            <param name="sip-port" value="5062"/>
            <param name="dialplan" value="XML"/>
            <param name="inbound-codec-prefs" value="$${global_codec_prefs}"/>
            <param name="outbound-codec-prefs" value="$${global_codec_prefs}"/>
            <!--<param name="rtp-ip" value="192.168.7.157"/>-->
            <param name="sip-ip" value="192.168.7.157"/>
            <param name="log-auth-failures" value="true"/>
        </settings>
    </profile>

Directory :
    <domain name="$${domain}">
      <user id="wira">
        <params>
          <param name="password" value="$${default_password}"/>
          <param name="dial-string" value="${sofia_contact(${dialed_user}@${dialed_domain})}"/>
        </params>
      </user>

      <user id="hp-andalabs">
        <params>
          <param name="password" value="$${default_password}"/>
          <param name="dial-string" value="${sofia_contact(${dialed_user}@${dialed_domain})}"/>
        </params>
      </user>
    </domain>

A: what's the network topology between the phones and FreeSWITCH server? Maybe there's a firewall that is doing NAT or SIP intelligence. Also if you run packet captures, it would help to determine where the delay is occurring.


text:
Q: mutate_if, across or map_if where want to process the iteration conditional on value in another field Simple example:
mydf <- data.frame(
  x = 1:3,
  y = c(1, 0, 1),
  z = 1:3
) %>% group_by(x) %>% nest

mydf %>% mutate(blah = map_dbl(.x = data, ~ .x$z * 2))

Returns:
# A tibble: 3 x 3
# Groups:   x [3]
      x data              blah
  <int> <list>           <dbl>
1     1 <tibble [1 × 2]>     2
2     2 <tibble [1 × 2]>     4
3     3 <tibble [1 × 2]>     6

I would like to mutate or map conditional on y. If y=1, then process with .x * 2 else (y = 0) then just use NA.
Desired result:
# A tibble: 3 x 3
# Groups:   x [3]
      x data              blah
  <int> <list>           <dbl>
1     1 <tibble [1 × 2]>     2
2     2 <tibble [1 × 2]>     NA
3     3 <tibble [1 × 2]>     6

Should I use mutate_if, mutate_across, map_if? How can I get this result?

A: In case the OP needs to retain the map model in their real use case, map2() is one possibility...
mydf %>% mutate(blah = map2(x, y, ~ifelse(.y == 1, .x * 2, NA)))
  x y blah
1 1 1    2
2 2 0   NA
3 3 1    6


text:
Q: Angular event binding not working as expected I have created a form which contains details such as username and email. I have a different field aside where I want the text the user types be displayed. The event binding seems not to work within my form but when I place it outside it works. I need it to work within my form. Any help is appreciated.
Trying to do something like this
HTML
Enter text
        <input id="typeahead-basic" type="text" class="form-control" [(ngModel)]="myModel"/>

Model: {{ myModel }}

**TS**

public myModel: any;

Below is my code

**HTML**``

      <form class="shadow-lg p-3" [formGroup]="registrationForm" style="min-height: calc(100vh - 100px);position:relative">

              Create New User

Enter the name of the user you want to create here and click the "create user once complete."

          Name
          <input type="text" class="form-control" id="exampleInputName" aria-describedby="nameHelp"
                 placeholder="Enter name of user here" [(ngModel)]="myModel"> **OVER HERE**

          Organization Email
          <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
                 placeholder="username@business.org">

          Password

            <input [type]="fieldTextType ? 'text' : 'password'" class="form-control" id="exampleInputPassword1"
                   placeholder="Enter strong password here" formControlName="password">

          Confirm Password

            <input [type]="repeatFieldTextType ? 'text' : 'password'" class="form-control" id="exampleInputPassword2"
                   placeholder="Repeat strong password here" formControlName="confirmPassword">

          Role
          <select class="form-select" aria-label="Default select example">
            <option selected>Select role here</option>
            <option value="1">One</option>
            <option value="2">Two</option>
            <option value="3">Three</option>
          </select>

          <button class="btn-primary align-middle btn" style="float:none;margin:auto;display:block;border-radius:8px;">

            Create User
          </button>

      </form>

Model: {{ myModel }}
 **OVER HERE**

Email:

Preview

Enter user details on the left panel to see a profile version of the user here

**TS**

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";

@Component({
  selector: 'app-create-user',
  templateUrl: './create-user.component.html',
  styleUrls: ['./create-user.component.css']
})
export class CreateUserComponent implements OnInit {

  registrationForm: FormGroup;
  fieldTextType: boolean;
  repeatFieldTextType: boolean;

  public myModel: any;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.initRegForm();
  }

  initRegForm() {
    this.registrationForm = this.fb.group({
      email: ["", [Validators.required, Validators.email]],
      password: ["", Validators.required],
      confirmPassword: ["", Validators.required]
    });
  }

  toggleFieldTextType() {
    this.fieldTextType = !this.fieldTextType;
  }

  toggleRepeatFieldTextType() {
    this.repeatFieldTextType = !this.repeatFieldTextType;
  }

}

A: I guess it doesn't work because you need to add the name attribute to the input in order to work.
Try like this:
<input
   id="typeahead-basic"
   type="text"
   class="form-control"
   [(ngModel)]="myModel"
   name="myModel"
/>

IMPORTANT: In any case, mixing together Reactive forms and Template-Driven (ngModel) is not a good practice.


text:
Q: How to control replication? I want to disable replication of the user's first name attribute. That is Whenever I change its value, it should not be replicated. How can I do that?

A: The answer, is sort of... You can edit what gets replicated to the Global Catalog.
I can see no reason why this would be a good practice right now though. Active-Directory as a database should be the source of verifying identities between locations, not for storing mismatched data. If you want nick names, then use nicknames in a standard way that can be verified. If you want less visible attributes, then use hidden Extension attributes.
Active-Directory should be one of the places you know the data is correct and uniform.


text:
Q: Liquibase script fails I have a glassfish application which creates its DB schema with liquibase. I have migrated the same application to Spring Boot. I did not drop the DB schema. When I deploy the Spring application and the liquibase scripts run, I get
java.sql.SQLSyntaxErrorException: ORA-00955: name is already used by an existing object
when executing the changeset for creating one of the tables.
I need to specify there is no change in the liquibase scripts and the database changelog lock is acquired successfully.
Shouldn't it skip all the table creation steps? I plug in the same application to the same DB. Have you encountered this situation before?
UPDATE: is it possible that this might be related to the MD5 sum stored in the changelog file ? So the md5 computed by the new application doesn't match the one computed by the old one and the scripts are triggered, causing the obvious exception ?
Many thanks

A: I don't think you have a checksum difference - that would cause a different error message. What I think is likely is that the DATABASECHANGELOG table has a different changelog path for the changes than what is being reported by Liquibase.
Changesets are identified by 3 things - the changeset id, the author, and the path. When Liquibase is deciding whether a changeset from a changelog should be deployed to a particular database, it looks at the DATABASECHANGELOG table and retrieves that information, compares it with the information in the changelog file, and doeesn't try to deploy anything that matches up. In this case, I think it detects differences in the path and tries to re-deploy the change.


text:
Q: Replace values with 1 and empty cells with 0 to generate a heatmap? In the following df, some cells in column contains value (numeric, logical, character) and some are empty. I want to assign value 1 in all the cells that are not empty and assign value 0 to all the empty cells and want to create newdf. Using this newdf I want to generate heatmap grouped by "citizen" type in y-axis. Any help ?
structure(list(ID = c("ID123", "ID456", "ID523", "ID875", "ID782",
"ID572", "ID900"), Citizen = c("US", "CN", "MX", "US", "US",
"CA", "CA"), Ht = c("6", "NA", "5", "6", "5", NA, "6"), Wt = c("200",
"140", "160", NA, "NA", "175", NA), Age = c("NA", "45", NA, "32",
"60", "44", "30"), income = c("60", "50", "30", "20", "40", "NA",
"20"), sex = c("M", "F", "NA", NA, "M", "M", "F"), `Traffic vio` = c(TRUE,
FALSE, TRUE, FALSE, NA, TRUE, TRUE), Greets = c("Hello", "Bonjour",
"Hola", "Hi", "Hello", "Hello", "Bonjour")), row.names = c(NA,
-7L), class = c("tbl_df", "tbl", "data.frame"))

A: Try this dplyr solution with across(). You have different classes of variables so you can format all of them as character and then make the replacement. Next the code for the 0-1 replacement:
library(dplyr)
#Code
#First make variables in standard format
df %>%
  mutate(across(Ht:Greets,~as.character(.))) %>%
  #Now mutate to 0-1
  mutate(across(Ht:Greets,~ifelse(is.na(.),0,1)))

Output:
# A tibble: 7 x 9
  ID    Citizen    Ht    Wt   Age income   sex `Traffic vio` Greets
  <chr> <chr>   <dbl> <dbl> <dbl>  <dbl> <dbl>         <dbl>  <dbl>
1 ID123 US          1     1     1      1     1             1      1
2 ID456 CN          1     1     1      1     1             1      1
3 ID523 MX          1     1     0      1     1             1      1
4 ID875 US          1     0     1      1     0             1      1
5 ID782 US          1     1     1      1     1             0      1
6 ID572 CA          0     1     1      1     1             1      1
7 ID900 CA          1     0     1      1     1             1      1


text:
Q: antx.tomcat.start does not support the nested "debug" element When I start the tomcat in debug mode, it gives me the above error.
<macrodef name="tomcat">
    <element name="options" optional="yes" />
    <sequential>
        <delete dir="server/cache" failonerror="no" />
        <delete dir="server/logs" failonerror="no" />
        <delete dir="server/workspace" failonerror="no" />
        <delete dir="server/tomcat/logs" failonerror="no" />
        <antx:tomcat.start>
            <tomcat catalinahome="${catalina.home}" port="${server.port}" />
            <enovia enoviahome="${enovia.server.home}">
                <memory size="medium" />
                <classpath>
                    <pathelement location="${alt.jdk.home}/lib/tools.jar" />
                    <pathelement location="${webapp.home}/WEB-INF/classes" />
                    <pathelement location="${webapp.home}/WEB-INF/lib" />
                    <pathelement location="${catalina.home}/lib/jsp-api.jar" />
                                            <pathelement location="${catalina.home}/lib/servlet-api.jar" />
                </classpath>
                <bootstrap connectstring="${oracle.sid}" driver="${oracle.driver}" password="${schema.password}" user="${schema.user}" />
            </enovia>
            <webapp location="${webapp.home}" />
            <javahome location="${alt.jdk.home}" />
            <options />
        </antx:tomcat.start>
    </sequential>
</macrodef>

<target name="tomcat-start-debug" description="start tomcat in debug mode">
    <tomcat>
        <options>
            <jrebel location="${jrebel.jar}" />
            <debug transport="dt_socket" address="8998" server="y" suspend="n" />
        </options>
    </tomcat>
</target>

I have the same configuration in some other project, and it works. I am trying to get an solution for this. If anyone knows how to fix this, it would be helpful if its shared here.
Thanks,
Sandeep


text:
Q: There is no source available for the current location I am getting this error.
Locating source for 'C:\Users\cem\Documents\Visual Studio 2008\Projects\CS.Web.Controls\WebCropImage\CropImage.cs'. Checksum: MD5 {20 55 30 34 b8 e3 ee df 89 75 e5 b5 36 b6 13 21}
Determining whether the checksum matches for the following locations:
1: C:\Users\sun\Desktop\trunk\CS.WebControls\WebCropImage\CropImage.cs Checksum: MD5 {5d 31 b6 21 f5 1 36 8b c0 25 dd b9 1e ff d7 89} Checksum doesn't match.
2: C:\Users\sun\Downloads\WebCropImage.UI\CropImage.cs Checksum: MD5 {5d 31 b6 21 f5 1 36 8b c0 25 dd b9 1e ff d7 89} Checksum doesn't match.
The file 'C:\Users\cem\Documents\Visual Studio 2008\Projects\CS.Web.Controls\WebCropImage\CropImage.cs' does not exist.
Looking in script documents for 'C:\Users\cem\Documents\Visual Studio 2008\Projects\CS.Web.Controls\WebCropImage\CropImage.cs'...
Looking in the projects for 'C:\Users\cem\Documents\Visual Studio 2008\Projects\CS.Web.Controls\WebCropImage\CropImage.cs'.
The file was found in a project: 'C:\Users\sun\Downloads\WebCropImage.UI\CropImage.cs'.
The file was found in a project: 'C:\Users\sun\Desktop\trunk\CS.WebControls\WebCropImage\CropImage.cs'.
Determining whether the checksum matches for the following locations:
1: C:\Users\sun\Downloads\WebCropImage.UI\CropImage.cs Checksum: MD5 {5d 31 b6 21 f5 1 36 8b c0 25 dd b9 1e ff d7 89} Checksum doesn't match.
2: C:\Users\sun\Desktop\trunk\CS.WebControls\WebCropImage\CropImage.cs Checksum: MD5 {5d 31 b6 21 f5 1 36 8b c0 25 dd b9 1e ff d7 89} Checksum doesn't match.
Looking in directory 'C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\vc7\atlmfc'...
Looking in directory 'C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\vc7\crt'...
Looking in directory 'C:\Users\sun\Desktop\trunk\CS.WebControls\'...
The debug source files settings for the active solution indicate that the debugger will not ask the user to find the file: C:\Users\cem\Documents\Visual Studio 2008\Projects\CS.Web.Controls\WebCropImage\CropImage.cs.
The debugger could not locate the source file 'C:\Users\cem\Documents\Visual Studio 2008\Projects\CS.Web.Controls\WebCropImage\CropImage.cs'.

Probably it is not finding a CropImage.cs or its getting a mismatch.
I have added CS.Web.UI.CropImage.dll in the bin folder. Not sure why it still needs a .cs
Thanks
Sun

A: Likely what is happening, is that DLL that you've referenced is throwing an exception when you're calling it. When you're debugging, Visual Studio would like you show you the line of code that is throwing the error, but it doesn't know where the source is. Usually, in my environment, it will prompt you to locate the source file and open it so that it can show you additional debug information. I would usually get the error you mention, when I press cancel on that dialog since I either don't have the source, or don't care what the source is

A: Open "Solution 'YourSolutionName' property pages" window (go to main menu: Project->Properties) and then go to "Debug Source Files". Check under "Do not look for these source files" window if you have your problematic file path written in it. If yes, delete the path and try again. I think this might solve your problem.
Regards,

A: For me it was Miro's solution + I cleaned project and manually removed all filed from Debug and Release folders. This forces clean rebuild.

A: I have removed files from Bin/Debug and Bin/Release folder.Which worked for me.

A: If is an ASP.Net project, delete the temporary files. This cannot hurt. Any time a copy is made, the possibility exists that somehow it can get out of sync.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\
In my case, before I did that, I could not set any breakpoints.
The error was giving the exact same path in both MD5 statements, and saying the checksum didn't match.
After I did that, it still told me the source version was different, but I choose to use it anyway, and I was able to step through the code and set breakpoints.
Go figure.
And one more thing: If you want to know where it's getting the pdb from actually, you can go into Debug, Windows, Modules, and find the dll in question, and see the path in the Symbol File column.


text:
Q: Three.js OnDocumentMouseDown does not work with touch screen? Full code in this Glitch project. https://glitch.com/~quickest-catshark
I have declared a custom AFRAME component in public/components.js that rotates the item when dragging with mouse.
AFRAME.registerComponent('drag-rotate-component', {
    schema: { speed: { default: 10 } },
    init: function () {
        this.ifMouseDown = false;
        this.x_cord = 0;
        this.y_cord = 0;
        document.addEventListener('mousedown', this.OnDocumentMouseDown.bind(this));
        document.addEventListener('mouseup', this.OnDocumentMouseUp.bind(this));
        document.addEventListener('mousemove', this.OnDocumentMouseMove.bind(this));
    },
    // When mouse down, save x and y coordinates of mouse position
    OnDocumentMouseDown: function (event) {
        this.ifMouseDown = true;
        this.x_cord = event.clientX;
        this.y_cord = event.clientY;
    },
    OnDocumentMouseUp: function () {
        this.ifMouseDown = false;

        // Save rotation to localstorage
        let rotation = this.el.object3D.rotation.z;
        localStorage.setItem('angle', rotation);
    },
    OnDocumentMouseMove: function (event) {
        if (this.ifMouseDown) {
            // Get difference between current mouse position and previous mouse position
            var temp_x = event.clientX - this.x_cord;
            var temp_y = event.clientY - this.y_cord;

            this.el.object3D.rotation.z = temp_x * this.data.speed / 1000;
        }
    }
});

The code works as intended in the browser.
But when I access it from Chrome in my mobile phone, nothing happens when I drag my finger in the area. Doesn't work in my Surface Pro touch tablet either.
How do I get it to work in touch devices?
I tried the answe given in this question
Mouse events not working in mobile
Use event.touches[0].clientX and event.touches[0].clientY. But these return undefined.

A: You need to use touchstart, touchmove, touchend for touch and in those events you'd use event.touches[0].clientX and clientY
Further, you want probably want your event handlers to not be passive so that in touchstart you can tell the browser to ignore the touch otherwise the page will scroll/zoom/etc...
You can find an example here
Supporting Touch Interface in a canvas


text:
Q: angular js ng-show is not working Html code:

                                {{store.name}}

                                {{store.price}}
                                {{store.canPurchase}}
                                {{store.soldOut}}
                                <button ng-show="store.canPurchase">Add to Cart</button>

JS code:
    myApp.controller('StoreController', ['$scope', function($scope){
    $scope.gems=[
            {name: 'Azurite', price: '110.50', canPurchase: 'false', soldOut: 'true'},
            {name: 'Azurite +', price: '120.50', canPurchase: 'true', soldOut: 'false'}
    ];

}]);

I tried with ng-show="true" and ng-show="false", my code is working as expected.
I am printing store.canPurchase value on my html page and values are displayed correctly.
But when I give store.canPurchase in ng-show the code doesn't work.

A: remove the quotation marks and it will work fine. The false and true values of canPurchase are now strings ("") and not booleans.

$scope.gems=[
        {name: 'Azurite', price: '110.50', canPurchase: false, soldOut: true},
        {name: 'Azurite +', price: '120.50', canPurchase: true, soldOut: false}
];

Plunkr
The same goes for soldOut btw :)


text:
Q: Order List by Date and Time (in string format) Probably what I'm asking is quite simple but I don't seem to be getting this one out.
I have a list of elements containing a Date field and a Time field. The Date field is a regular DateTime and the Time field is a string.
Time is formatted like HH:mm and ranges in 24h.
Ordering my list by Date is simple by doing List.OrderBy(e => e.Date), but I don't seem to be able to later order it by Time so that the order of the records is according the date and the time.
I tried this out but it's probably a big mistake!
    List = List.OrderBy(e => e.EstimatedDate).OrderBy(e => new TimeSpan(int.Parse(e.EstimatedTime.Substring(0,e.EstimatedTime.LastIndexOf(":"))),int.Parse(e.EstimatedTime.Substring(e.EstimatedTime.LastIndexOf(":")+1)),0).TotalMinutes);

I hope someone can help me out with this one.

A: why not try something like following:
List.OrderBy(e => e.Date).ThenBy(e => DateTime.Parse(e.Time));
// May need to change DateTime.Parse(e.Time) with appropriate conversion code

A: You know ThenBy() ?
List = List.OrderBy(DATE).ThenBy(Time)

A: You want OrderBy(...).ThenBy(...); and also - not that if the time is in HH:mm you don't have to parse it - you can just sort it alphabetically, i.e.
List = List.OrderBy(e => e.EstimatedDate).ThenBy(e => e.EstimatedTime).ToList();

or via LINQ:
List = (from e in List
        orderby e.EstimatedDate, e.EstimatedTime
        select e).ToList();


text:
Q: Address of return value of method I have a get-method that returns a value:
int Foo::getValue() const
{
    return value_;
}

I'm using the following code to write this value to a binary file:
void Bar::write(const Foo& foo)
{
    /* some code... */

    file_.write(reinterpret_cast<char*>(&foo.getValue()), sizeof(int));
}

And it seems that everything works well. But I am not sure about that &foo.getValue() thing. Will it always return an address of return value of getValue() or are there any pitfalls?
EDIT1: I dont want to create a temporary var for this.
EDIT2: Yes, it compiles and works fine.
EDIT3: write is a ostream::write
EDIT4: With /Wall and /Za it will not compile: error C2102: '&' requires l-value

A: The standard forbids you to take the address of an rvalue: https://stackoverflow.com/a/28459180/2642059 A compiler that is not standard compliant may allow this behavior, but assuredly that is not behavior that will be cross platform, nor is it guaranteed to succeed even between updates to the compiler that may more closely align it with the C++ standard.
Since you are not programming for a specific compiler, but for C++, finding something that works in a specific compiler should not be your objective. Finding a way to accomplish this within the standard would be preferable.
A couple easy options for doing that would be:

*

*Turn it into an lvalue by assigning it to a temporary value. They're free! The compiler will optimize them right out

*Change the return of getValue to const int& this will allow you to work with an lvalue. Since ints are typically copied by value this probably will not have repercussions in your code base, but it could

*Create another method which could directly return (const char*)&value_, you could get in trouble abusing this one though so be careful

A: Microsoft Compiler for whatever reason has a `"feature" - it implicitly converts temporary to lvalue. You can check it by this code:
int &ref = foo.getValue();

this code as well as your should not compile. Proper code would be:
void Bar::write(const Foo& foo)
{
    /* some code... */
    int temp = foo.getValue();
    file_.write(static_cast<const char*>(&temp), sizeof(int));
}


text:
Q: Assembly not found at runtime when running a Roslyn script I am embedding a script engine based on Roslyn into my application and started facing some issues. When loading a reference into my engine, I do the following
var engine = new Roslyn.Scripting.CSharp.ScriptEngine();
engine.AddReference("MyAssemblyLocation");

Questions:

*

*If MyAssemblyLocation assembly is referencing other assemblies, how do I tell Roslyn to load them without doing an engine.AddReference("MyAssemblyLocation");

*The host application in which the script is supposed to be running has already loaded some assemblies I would like to use in the script, is there a way for Roslyn to hook itself into the already loaded dlls in memory and not load new instances?

*Finally, is there a way to tell Roslyn to recursively load all dependencies of MyAssemblyLocation
Thank you.

A: 1) Short answer: you need to AddReference on all assemblies whose types are you going to use in the script.
Details:
The C# compiler doesn't guess where the dependent files are. An assembly file doesn't specify full paths to all of its dependencies. It only contains their names and that's generally not enough for the compiler to be able to locate the assembly file.
More details:
There are two kinds of dependencies. I'll call them compile time dependencies (a) and runtime dependencies (b).
(a) Suppose you have "public class A : B {}" in assembly A.dll, "public class B { }" in assembly B.dll, and your script is using A, say you create a new instance: "new A()". The compiler requires you to add references to both A.dll and B.dll in this case, since A derives from B and the compiler needs to analyze the inheritance hierarchy of each type you use. So B.dll is a compile-time dependency of your script - the compiler needs it in order to analyze your script properly.
(b) Consider another example: "public class A { public object M() { return new B(); } }" in A.dll and the same B.dll as above. Now when compiling "new A().M()" the compiler doesn't need to know about B, since the reference to B only occurs in the body of method M and the compiler doesn't analyze bodies of imported methods. In this case it suffices to add a reference to A.dll in order to compile the script. When the script executes it calls method M. At that point the CLR loads assembly B. This gets a bit complex, so I'll skip details but in common scenarios we'll be able to locate the assembly for you, so you don't need to add the reference explicitly.
2) I'd recommend using the overload of AddReference that takes Assembly object. Something like:
engine.AddReference(typeof(SomeTypeInAssemblyFoo).Assembly) to load assembly Foo that contains type SomeTypeInAssemblyFoo.
3) Not a straightforward one. You can enumerate all references using Reflection or Roslyn APIs and load each one of them.
Feel free to ask further questions if the explanation is not clear or you wish to know more details.


text:
Q: Problems with ConstraintLayout - vertical margin doesn't work I want to build this simple layout using ConstraintLayout:

It works as expected when Title and Subtle are just single line text. The problem comes with longer text. As you can see, Title and Subtle overlap each other:

Here's the source code I use for layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#EEEEEE">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="24dp"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
            android:textAppearance="@style/TextAppearance.AppCompat.Headline"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginBottom="24dp"
            android:text="Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
            app:layout_constraintTop_toBottomOf="@+id/textView1"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintBottom_toBottomOf="parent" />

    </android.support.constraint.ConstraintLayout>

</FrameLayout>

So where's the problem?

EDIT 1 10/5/2017 1:19 PM
Seems like can be reproduced only on devices/simulators running Android 6.0 (API 23). Works as expected on devices running API 21-22, 24+.

A: I recommend you using only the ConstraintLayout which gives you chaining option. With it, you can pack two TextViews and center them vertically in ConstraintLayout itself without the FrameLayout and the problem you are facing:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EEEEEE">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="24dp"
        android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        android:textAppearance="@style/TextAppearance.AppCompat.Headline"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="24dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        android:text="Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView1" />

</android.support.constraint.ConstraintLayout>

A: On API 23 with ConstraintLayout version 1.0.0-beta5, it looks like the top margin is not respected or the height of the top TextView is not calculated correctly. I do see an overlap on API 23 but not on API 24 with this version of ConstraintLayout.
However, with ConstraintLayout version 1.1.0-beta2, everything looks OK on API 23 and API 24, so this might have been a problem that was corrected. I suggest that you upgrade to a later release of ConstraintLayout to see if the problem persists.

A: Your TextView1 doesn't have lower boundaries.
Simply add
app:layout_constraintBottom_toTopOf="@+id/textView2"

for your first textView


text:
Q: ScheduledExecutorService change delay repeatedly I have a task I want to run where the delay will keep changing (i.e. - no fixed interval).
I want a thread and loops infinitely that finds the delay value, inputs this into the executor and then once that task is done find the new delay value etc..
My current 'basic' implementation:
long targetTime = findNextTime()/1000;
long currentTime = System.curentTimeMillis()/1000;

delay = targetTime - currentTime;

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);

Runnable task = new Runnable() {

    public void run() {
        System.out.println("Test Task");

        ScheduledFuture<?> future = scheduler.schedule(this, delay, TimeUnit.SECONDS);
    }
}

How can I get it to find the new delay and keep repeating this task?
Should I poll for future to be done and then do a recursive loop? I try this and I get an error.

A: There are some answer to resolve this.Reinitialize fix delay in ScheduledExecutorService and
How to change Spring's @Scheduled fixedDelay at runtime
here i support another method to realize this-repeated submit task to ExecutorService
class Task implements Runnable {
    private static Random random = new Random();
    private ExecutorService executor;

    public Task(ExecutorService executor) {
        this.executor = executor;
    }

    @Override
    public void run() {
        try {
            System.out.println(System.currentTimeMillis() + "   Hello World");
            TimeUnit.MILLISECONDS.sleep(random.nextInt() % 100);
            executor.execute(this);
        } catch (Exception e) {

        }
    }
}


text:
Q: Regex optional parantheses into forced three groups I have a string full of parentheses like this:
(this) (should) (be) (group) (one) (thisshouldbegrouptwo) (this) (should) (be) (group) (three)

I'd like to regex this into three groups, with the constant string thisshouldbegrouptwo, optionally in parentheses, delimiting the groups:
1. Group: (this) (should) (be) (group) (one)
2. Group: (thisshouldbegrouptwo)
3. Group: (this) (should) (be) (group) (three)

The string (thisshouldbegrouptwo) is a fixed optional string, with its parentheses also optional. If it isn't present, I expect the following result:
1. Group: (this) (should) (be) (group) (one)
2. Group:
3. Group: (this) (should) (be) (group) (three)

In this case, it would also be OK if the whole string was matched in a single group.
The number of parentheses for group 1 or 3 are not significant, only the parentheses around the middle group matter, and should be with the middle group if found, not with the edge groups.
This is my regular expression so far (demo):
(\(.*\))?(?:\s(\(thisshouldbegrouptwo\)\s))?(\(.*\))

A: This regular expression will do what you want:
(.*?)(\(?thisshouldbegrouptwo\)?)(.*)|(.*)

When thisshouldbegrouptwo is present in the string, groups 1 and 3 will have the left and right context, excluding the optional parentheses that might surround group 2.
When that text is not present in the string, group 4 will contain the entire string.
Keys elements of the solution:

*

*Using a non-greedy expression first, .*? instead of .*, avoids have the opening parenthesis of group 2 lumped into group 1 instead.

*The |(.*) at the end is a catch-all, but since regular expressions are processed from left to right, you'll get the first part matching when the group two string is present.

I could not find a solution that separated the non-matching case into two groups, since there is nothing to divide them in that case, but since you said it was OK to keep it together, moving it to group 4 as this expression does should work for you.


text:
Q: How to represent custom spring cloud stream kafka binder configuration in Java auto configuration I have the following configuration with custom kafka binder configurations
spring.cloud.stream:
  bindings:
    inputBinding1:
      binder: kafka1
      destination: destination1
    inputBinding2:
      binder: kafka2
      destination: destination2
  binders:
    kafka1:
      type: kafka
      environment.spring.cloud.stream.kafka.binder:
        brokers: hostname1
    kafka2:
      type: kafka
      environment.spring.cloud.stream.kafka.binder:
        brokers: hostname2

I want to represent spring.cloud.stream.binders.kafka1 and spring.cloud.stream.binders.kafka2 in Java as Spring Beans in a shareable library. The goal being to provide boilerplate Kafka cluster configuration such as brokers and consumer/producer properties. I'd like the ability to use either binder individually or multi binder


text:
Q: Finding duplicate names where first name can be an initial or full name I am trying to find duplicates by comparing the first name and surname columns in a table. The first name can be a name or an initial.
Reading other posts I have managed to figure out how to get the duplicate surnames and list the first letter for first name. But I am unsure how to only show rows where there is a match of surname and the first letter of the first name.
SELECT *
FROM table AS a
INNER JOIN (

SELECT LEFT( firstname, 1 ) , surname
FROM table
GROUP BY surname
HAVING COUNT( * ) > 1
) AS b ON a.surname = b.surname

id | firstname | surname
**************************
1  | joe       | bloggs
2  | j         | bloggs
3  | s         | bloggs
4  | f         | doe
5  | frank     | spencer

Currently this query would return
1  | joe       | bloggs
2  | j         | bloggs
3  | s         | bloggs

Result I would like would just contain the possible duplicates.
1  | joe       | bloggs
2  | j         | bloggs

A: You probably don't want to use initials all the time, e.g., if you always strip to initials you might consider Bob X the same as Bill X.
So you need to check three cases.

*

*both firstnames are initials

*both firstnames are non initials

*only one firstname is an intial

So you can work with string methods of Mysql to check the length of either firstname and check the proper case.

A: I would join the table to itself like so:

select * into #temp from (
SELECT 1, 'joe', 'bloggs' UNION
SELECT 2, 'j', 'bloggs' UNION
SELECT 3, 'f', 'doe' UNION
SELECT 4, 'frank', 'spencer' UNION
SELECT 5, 'steven', 'woo' UNION
SELECT 6, 'steve', 'woo' UNION
SELECT 7, 'stanley', 'woo'
) x (id, firstname, surname)
select
    *
from
    #temp l
inner join
    #temp r
on
    left(l.firstname, 1) = left(r.firstname, 1)
and
    l.surname = r.surname
where
    l.id < r.id
drop table #temp
the downside to this is that the steven and stanley match.  I would suggest you think about creating a firstname alias table and use that to standardize the firstnames.

A: I don't quite get what you want. Yor provided a query, your current table and the expected result.
I've just created your table, run your query and got the expected result. What is wrong with this?
SELECT  FROM table1 AS a
INNER JOIN (
  SELECT surname FROM table1
  GROUP BY surname
  HAVING COUNT(*) > 1
) AS b ON a.surname = b.surname

This effectively result in your expected result:
joe | bloggs
j   | bloggs

Or am I missing something?
After re-reading... are you expecting to get only this?
j | bloggs

If that is the case, use this:
SELECT * FROM table1 AS a
INNER JOIN (
  SELECT surname FROM table1
  GROUP BY surname
  HAVING COUNT(*) > 1
) AS b ON a.surname = b.surname
WHERE CHAR_LENGTH(firstname) = 1

Edit:
After the expected result was properly explained I conclude the query should be:
SELECT a.firstname, a.surname FROM t1 AS a
INNER JOIN (
  SELECT LEFT(firstname, 1) AS firstChar, surname FROM t1
  GROUP BY surname, firstChar
  HAVING COUNT(surname) > 1
) AS b ON a.surname = b.surname AND b.firstChar = LEFT(a.firstname, 1)

Working example


text:
Q: Ionic-Native issue in ionic 2 I have added a Cordova file transfer plugin from Ionic native and imported transfer from ionic native to my application page
I am not getting any syntax error as well as command prompt errors
But when I run my application using Ionic serve it is showing me
{Cannot find module "ionic-native"}
Can anyone please help me on this

A: Did u check it properly, weather u have installed ionic-native ?
Plus which version of ionic are you using, in ionic 3 (launched recently) they removed ionic-native and kept it seperately in @ionic-native. And u'll have to indivisually install every plugin u r using.
http://blog.ionic.io/ionic-native-3-x/


text:
Q: How come if I enter a letter input my program gets stuck in its while loop? Sorry if I fail to be clear enough or make any mistakes, this is my first time posting.
My code runs without errors when complied but the first while loop (in int main) gets stuck looping whenever a user types a letter (like "a") for cin >> select; instead of the required 1, 2, or 3.
However, when I input "4" or any other random string of numbers, it runs fine and goes to my error message like it should.
Why is this and what can I do to make it run normally? (run the error message in response to letters entered as if they were numbers).
My code:
#include <iostream>
#include <string>
using namespace std;

void calculator();
void unavailableitem();

int main()
{
    string select;
    while (true)
    {
        cout << "\t[Main Menu]\n";
        cout << " 1. Calculator\n";
        cout << " 2. [unavailable]\n";
        cout << " 3. [unavailable]\n";
        cout << "\n Enter the number of your selection: ";
        cin >> select;

        if (select == "1")
        {
            cout << endl;
            calculator();
            break;
        }
        else if (select == "2")
        {
            unavailableitem();
            break;
        }
        else if (select == "3")
        {
            unavailableitem();
            break;
        }
        else
            cout << "\nInvalid response.\n";
    }
}

void unavailableitem()
{
    string react;
    cout << "\n \t [ITEM UNAVAILABLE]\n";
    while (true)
    {
        cout << "\nEnter 'menu' to return to main menu: ";
        cin >> react;

        if (react == "menu")
        {
            cout << endl;
            main();
            break;
        }
        else
            cout << "\nInvalid response.\n";
    }
}

void calculator()
{
    int choice;
    double num1;
    double num2;
    double answer;
    string choicesymbol;

    cout << "List of operations:\n";
    cout << " 1. Addition\n";
    cout << " 2. Subtraction\n";
    cout << " 3. Multiplication\n";
    cout << " 4. Division\n";
    cout << "Enter the number on the left to pick an operation: ";
    cin >> choice;
    cout << "\nEnter number 1: ";
    cin >> num1;
    cout << "\nEnter number 2: ";
    cin >> num2;

    if (choice == 1)
    {
        answer = num1 + num2;
        choicesymbol = " + ";
    }

    if (choice == 2)
    {
        answer = num1 - num2;
        choicesymbol = " - ";
    }

    if (choice == 3)
    {
        answer = num1 * num2;
        choicesymbol = " * ";
    }

    if (choice == 4)
    {
        answer = num1 / num2;
        choicesymbol = " / ";
    }

    cout << endl;
    cout << num1 << choicesymbol << num2 << " = " << answer;
}

New code:
#include <iostream>
#include <string>
using namespace std;

void calculator();
void unavailableitem();

int main()
{
    int select;
    while (true)
    {
        cout << "\t[Main Menu]\n";
        cout << " 1. Calculator\n";
        cout << " 2. [unavailable]\n";
        cout << " 3. [unavailable]\n";
        cout << "\n Enter the number of your selection: ";
        cin >> select;

        if(!(cin >> select))
        {
        cout << "Input must be an integer.\n";
        cin.clear();
        continue;
        }
        else if (select == 1)
        {
            cout << endl;
            calculator();
            break;
        }
        else if (select == 2)
        {
            unavailableitem();
            break;
        }
        else if (select == 3)
        {
            unavailableitem();
            break;
        }
    }
}

void unavailableitem()
{
    string react;
    cout << "\n \t [ITEM UNAVAILABLE]\n";
    while (true)
    {
        cout << "\nEnter 'menu' to return to main menu: ";
        cin >> react;

        if (react == "menu")
        {
            cout << endl;
            return;
            break;
        }
        else
            cout << "\nInvalid response.\n";
    }
}

void calculator()
{
    int choice;
    double num1;
    double num2;
    double answer;
    string choicesymbol;

    cout << "List of operations:\n";
    cout << " 1. Addition\n";
    cout << " 2. Subtraction\n";
    cout << " 3. Multiplication\n";
    cout << " 4. Division\n";
    cout << "Enter the number on the left to pick an operation: ";
    cin >> choice;
    cout << "\nEnter number 1: ";
    cin >> num1;
    cout << "\nEnter number 2: ";
    cin >> num2;

    if (choice == 1)
    {
        answer = num1 + num2;
        choicesymbol = " + ";
    }

    if (choice == 2)
    {
        answer = num1 - num2;
        choicesymbol = " - ";
    }

    if (choice == 3)
    {
        answer = num1 * num2;
        choicesymbol = " * ";
    }

    if (choice == 4)
    {
        answer = num1 / num2;
        choicesymbol = " / ";
    }

    cout << endl;
    cout << num1 << choicesymbol << num2 << " = " << answer;
}

A: Ad Ed Heal mentioned, the issue here is cin's failbit. When you do cin >> choice, and the user types "a", then the conversion to int fails. This sets cin's failbit, making all future reads from it fail until the failbit is cleared. So the next time you reach cin >> choice, the user won't even get to type anything.
You can use cin.clear() to restore to working order.
To do this a bit more robustly, you could do something like
while(true)
{
    cout >> "Enter choice [1-4]: ";
    if(!(cin >> choice))
    {
        cout << "Input must be an integer.\n";
        cin.clear();
        continue;
    }
    do_stuff_with_choice();
 }

A: I am a newbie to programming in general, but playing with your code and looking up stuff made me find some sort of solution.
The cin.clear only clears the error log of the input, and I believe that it still retains the value of the letter.
What you should add right after is a cin.ignore(#,'\n') (# being a very, very large number) to have it avoid the line and skip right through it.
Found the solution in another question that explains the use of both cin commands.


text:
Q: Machine Architecture from Ubuntu OS I have run 'lscpu' in Ubuntu 18.04.3 LTS, I just want to confirm if it's says operation mode is 32 bit and is 64 bit - is this confirmation correct? My expectation is it it possible to install 64 bit OS in my machine? I'm curious .. I am currently running ubuntu 32 bit OS. I want someone who knows better about it.
> lscpu

Architecture:        i686
CPU op-mode(s):      32-bit, 64-bit
Byte Order:          Little Endian
CPU(s):              2
On-line CPU(s) list: 0,1
Thread(s) per core:  1
Core(s) per socket:  2
Socket(s):           1
Vendor ID:           GenuineIntel
CPU family:          6
Model:               42
Model name:          Intel(R) Pentium(R) CPU B950 @ 2.10GHz
Stepping:            7
CPU MHz:             857.844
CPU max MHz:         2100.0000
CPU min MHz:         800.0000
BogoMIPS:            4190.92
L1d cache:           32K
L1i cache:           32K
L2 cache:            256K
L3 cache:            2048K
Flags:               fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx rdtscp lm constant_tsc arch_perfmon pebs bts xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl est tm2 ssse3 cx16 xtpr pdcm sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer xsave lahf_lm epb pti ssbd ibrs ibpb stibp xsaveopt dtherm arat pln pts md_clear flush_l1d

A: The output shows that the CPU is Intel(R) Pentium(R) CPU B950 @ 2.10GHz.
It supports both 32-bit and 64-bit architectures.
You can install a 64-bit Ubuntu.

A: Your cores are not different.
Both are 64-bit. Both support 32-bit Operating Systems AND 64-bit Operating Systems, and the various applications thereof.


text:
Q: Change background and font color of jpanel on button click I want to change Background color of Jpanel and its font on button click.
Can anyone tell me what i am doing wrong?
Can I set JPanel background transparent?if yes How?
On button click test4.action method is called where i need to change Jpanel background color?
Here is the code:
import java.applet.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.event.*;
import javax.swing.*;

public class test3 extends Applet {

    JPanel c;
    JScrollPane s;
    Button connect;
    Panel controls;
    Color back, fore;

    public void init() {
        back = Color.black;
        fore = Color.white;
        setBackground(Color.darkGray);
        setLayout(new BorderLayout());
        s = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        //s.setSize(100, 100);
        add("Center", s);
        c = new myCanvas11(this);
        s.setOpaque(false);
        s.setViewportView(c);
        //s.add(c);
        c.setSize(1000, 16000);
        add("North", controls = new Panel());
        controls.setLayout(new FlowLayout());
        controls.add(connect = new Button("Change Color"));
    }

    public void start() {
        // s.setScrollPosition(100, 100);
    }

    public boolean action(Event e, Object arg) {
        back = Color.magenta;
        fore = Color.blue;
        //setBackground(back);
        //invalidate();
        //repaint();
        c.setBackground(back);
        c.repaint();
        //s.getViewport().setBackground(back);
        // s.getViewport().repaint();
        //c.repaint();
        c.setFocusable(true);
        return true;
    }
}

class myCanvas11 extends JPanel implements KeyListener {

    Image buffImage;
    Graphics offscreen;
    boolean initDone = false;
    int chw, chh; // size of a char (in pixels)
    int chd; // offset of char from baseline
    int width, height; // size of applet (in pixels)
    int w, h; // size of applet (in chars)
    Font fn;
    Graphics gr;
    int nh, nw;
    test3 owner;
    static int counter = 0;

    myCanvas11(test3 t) {
        super();
        owner = t;
        nh = 16000;
        nw = 1000;
        this.setOpaque(true);
        this.setFocusable(true);
        addKeyListener(this);
    }

    public void reshape(int nx, int ny, int nw1, int nh1) {
        if (nw1 != width || nh1 != height) {
            width = nw;
            height = nh;
            gr = getGraphics();
            fn = new Font("Courier", Font.PLAIN, 11);
            if (fn != null) {
                gr.setFont(fn);
            }
            FontMetrics fnm = gr.getFontMetrics();
            chw = fnm.getMaxAdvance();
            chh = fnm.getHeight();
            chd = fnm.getDescent();
            // kludge for Windows NT and others which have too big widths
            if (chw + 1 >= chh) {
                chw = (chw + 1) / 2;
            }
            // work out size of drawing area
            h = nh / chh;
            w = nw / chw;
            buffImage = this.createImage(nw, nh);
            offscreen = buffImage.getGraphics();
            //offscreen.setColor(Color.black);
            //offscreen.fillRect(0, 0, nw, nh);
            offscreen.setColor(Color.blue);
            offscreen.setFont(fn);
            if (initDone) {
                offscreen.drawString("Hello World!", 0, 50);
            } else {
                offscreen.drawString("khushbu", 2, 50);
            }
            initDone = true;
            offscreen.drawImage(buffImage, 0, 0, this);
        }
        super.reshape(nx, ny, nw, nh);
    }

    public void paint(Graphics g) {
//       if (!initDone)
//       initpaint(g);
//       else
        g.drawImage(buffImage, 0, 0, this);
        //g.drawImage(buffImage, 0, 0, owner.back, this);

    }

    public void update(Graphics g) {
        g.drawImage(buffImage, 0, 0, this);
        super.update(g);
        //g.drawImage(buffImage, 0, 0, owner.back, this);
    }

    public void initpaint(Graphics g) {
        try {
            nh = getHeight();
            nw = getWidth();
            gr = getGraphics();
            fn = new Font("Courier", Font.PLAIN, 11);
            if (fn != null) {
                gr.setFont(fn);
            }
            FontMetrics fnm = gr.getFontMetrics();
            chw = fnm.getMaxAdvance();
            chh = fnm.getHeight();
            chd = fnm.getDescent();
            // kludge for Windows NT and others which have too big widths
            if (chw + 1 >= chh) {
                chw = (chw + 1) / 2;
            }
            // work out size of drawing area
            h = nh / chh;
            w = nw / chw;
            buffImage = this.createImage(nw, nh);
            offscreen = buffImage.getGraphics();
            //offscreen.setColor(Color.black);
            //offscreen.fillRect(0, 0, nw, nh);
            offscreen.setColor(Color.white);
            offscreen.setFont(fn);
            if (initDone) {
                offscreen.drawString("Hello World!", 0, 50);
            } else {
                offscreen.drawString("khushbu", 2, 50);
            }
            initDone = true;
            g.drawImage(buffImage, 0, 0, this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** Handle the key typed event from the text field. */
    public void keyTyped(KeyEvent e) {
    }

    /** Handle the key pressed event from the text field. */
    public void keyPressed(KeyEvent e) {
        String s;
        offscreen.setColor(owner.fore);
        offscreen.setFont(fn);
        for (int i = counter; i < counter + 25; ++i) {
            s = Integer.toString(i);
            offscreen.drawString(s, 3, i * chh);
            offscreen.drawLine(10, i * chh, 160, i * chh);
        }
        //owner.s.setScrollPosition(0, counter * 16);
        counter = counter + 25;
        repaint();
    }

    /** Handle the key released event from the text field. */
    public void keyReleased(KeyEvent e) {
    }

    public boolean keyDown(Event e, int k) {
        String s;
        offscreen.setColor(owner.fore);
        offscreen.setFont(fn);
        for (int i = counter; i < counter + 25; ++i) {
            s = Integer.toString(i);
            offscreen.drawString(s, 3, i * chh);
            offscreen.drawLine(10, i * chh, 160, i * chh);
        }
        //owner.s.setScrollPosition(0, counter * 16);
        counter = counter + 25;
        repaint();
        return true;
    }
}

A:
Can I set JPanel background transparent?if yes How?

Yes, just call setOpaque(false); on that JPanel. On the contrary, if you want the background to be painted, call setOpaque(true); on that panel.
Additional remarks:

*

*public boolean action(Event e, Object arg) is Deprecated. Add the appropriate listeners instead.

*Follow Java coding conventions and use an Uppercase letter for the first character of a class

*You should almost never call getGraphics(); on a Component

*Don't override public void paint(Graphics g) but protected void paintComponent(Graphics g). Don't forget to call super.paintComponent if you want the background to be painted

*Why do you override reshape?

*Why do you create an internal buffer? Swing already has built-in double buffering and they do a much better job.

*If you overrode already paint() why do you also override update()? You are performing the same job twice.

*Remove that gr class variable, it does not make any sense. When you use Graphics object, use the one provided as a parameter of the paintComponent method but don't keep a reference to it, as it will be disposed later.

*counter does not need to be static. Try to avoid static as much as possible.

*Try to avoid so much coupling between your classes. It makes your code harder to maintain and less predictable.

*Next time, post an SSCCE with something else than an Applet (a JFrame, for example) unless the problem you are having really requires an Applet to be reproduced.


text:
Q: Kafka Consumer: How To Catch Failover Of Brokers? I'm currently trying to design a Kafka failover system to detect when a Kafka cluster (broker) goes down, but I'm having trouble getting the Consumer to realize that the broker is down.
I see that a Consumer will continuously poll if there is no data (while it is still connected to the broker) but if the broker goes down, my Consumer just sits there doing nothing forever.
Is there a property somewhere that I need to set for it to raise an Exception or something if it is unable to communicate with the broker? Or do I need to utilize some sort of a callback?
Thanks!


text:
Q: Solving inequalities at powers greater than $2$ Usually when I see an inequality like $x^2 - 6x - 16 < 0$, I know that the answer is $-2 < x < 8$ because I can picture where the graph would lie below zero. However, for a problem like $x^2(x+5)^3(x-3) \ge 0$, I'm not sure how to set up the inequalities because I can't picture a graph like this as easily. I'm not supposed to use a calculator for this, and I highly doubt my teacher is expecting us to plot points. Is there a trick to figure out inequalities greater than the second power by using the number of exponents given?

A: Sure.  Notice how the expression has been factored for you:
$$x^2(x+5)^3(x-3)\ge 0$$
This means that the roots of the polynomial on the left hand side are $-5$, $0$, and $3$, so all of these points are definitely in our solution set.  Now, we need to check points from each of the four regions of the real line separated by these roots.  Plugging in $-6$ gives us a positive value, so we know that $(-\infty,-5]$ will be a part of the solution set.
See if you can check the other three regions to finish off the problem.  Remember that the solution set must contain the three roots.


text:
Q: Connecting to online mongo database server Hey guys l am currently having some trouble connecting to my mongo database on the server. l currently have this with code to connect to my server:
MongoClient.connect("mongodb://username:password@197.342.145.22:3085/Anime",(err,database) =>{
 if (err) return console.log(err)
  require('./app/routes')(app, database);
  app.listen(port,() => {
    console.log("listening to "+port);
  });
})

but it is returning with this error everytime l try to connect when l run my node server:
{ Error: read ECONNRESET
at exports._errnoException (util.js:1020:11)
at TCP.onread (net.js:568:26) name: 'MongoError', message: 'read ECONNRESET' }

if someone could assist me by telling me of what l am doing wrong that would be nice.
Thanks in Advance

A: Your problem is that address you provide is not valid IP address. You can see it yourself on an ip validator. Simply copy and paste 197.342.145.22 there. You will get:

The rest of your code is correct, and when you provide valid IP it is going to connect to MongoDB.


text:
Q: Secondary domain in Google Analytics I have two sites, site 01 and site 02:
site = 01 has content
site = 02 has the video
When the user clicks the button "watch" the video is not loaded on the same page, the visitor goes to the site domain 02.
Google Analytics records this visit but he tells it like bounce rate and then it does not count the visit time visitor to see the video, since for some reason the site Analytics not recognizes 02 as being my property and also an extension of site 01.
How do I fix this?


text:
Q: How to update api versions list in Kubernetes I am trying to use "autoscaling/v2beta2" apiVersion in my configuration following this tutorial. And also I am on Google Kubernetes Engine.
However I get this error:
error: unable to recognize "backend-hpa.yaml": no matches for kind "HorizontalPodAutoscaler" in version "autoscaling/v2beta2"
When I list the available api-versions:
$ kubectl api-versions

admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
apps/v1beta1
apps/v1beta2
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
batch/v1
batch/v1beta1
certificates.k8s.io/v1beta1
certmanager.k8s.io/v1alpha1
cloud.google.com/v1beta1
coordination.k8s.io/v1beta1
custom.metrics.k8s.io/v1beta1
extensions/v1beta1
external.metrics.k8s.io/v1beta1
internal.autoscaling.k8s.io/v1alpha1
metrics.k8s.io/v1beta1
networking.gke.io/v1beta1
networking.k8s.io/v1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scalingpolicy.kope.io/v1alpha1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1

So indeed I am missing autoscaling/v2beta2.
Then I check my kubernetes version:
$ kubectl version

Client Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.6", GitCommit:"abdda3f9fefa29172298a2e42f5102e777a8ec25", GitTreeState:"clean", BuildDate:"2019-05-08T13:53:53Z", GoVersion:"go1.11.5", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"13+", GitVersion:"v1.13.6-gke.13", GitCommit:"fcbc1d20b6bca1936c0317743055ac75aef608ce", GitTreeState:"clean", BuildDate:"2019-06-19T20:50:07Z", GoVersion:"go1.11.5b4", Compiler:"gc", Platform:"linux/amd64"}

So it looks like I have a version of 1.13.6. Supposedly autoscaling/v2beta2 is available since 1.12.
So why it is not available for me?

A: Unfortunaltely HPA autoscaling API v2beta2 is not available on GKE yet. It can be freely used with Kubeadm and Minikube.
There is already opened issue on issuetracker - https://issuetracker.google.com/135624588


text:
Q: Converting list of list of Int32 values to list of list of int values I have a list of lists which contain numpy int32 values. I would like to convert all of these int32 values to regular int. The reason is because as a part of my process these values are fed into a non max suppression function later on, which won't accept int32.
Below is what the structure of what my data looks like (in regular int form). I don't know how to make a test set for int32 values... Or else I would probably have this problem figured out.
List of list of ints
test_list = [[1,2,3,4],[5,6,7,8]]

Edit: Some screenshots to help understand what my data looks like.

A: Examples of a non-iterative conversion.
Use the following to keep the structure as an ndarray:
a.astype(int)

>>> array([[1, 2, 3, 4],
           [5, 6, 7, 8]])

Or even more simply, use this to convert the ndarray to a list:
a.tolist()

>>> [[1, 2, 3, 4], [5, 6, 7, 8]]

Background:
You mention that your list is of int32 values. As such, it's highly likely that the 'list' is actually a numpy.ndarray. Here is an example:
a = np.array([[1,2,3,4],[5,6,7,8]], dtype=np.int32)

>>> array([[1, 2, 3, 4],
           [5, 6, 7, 8]], dtype=int32)

If this is the case, then converting the ndarray to a 'normal' list of int values is as simple as the two examples shown above.

A: This should work:
In [167]: [[int(x) for x in sublist] for sublist in test_list]
Out[167]: [[1, 2, 3, 4], [5, 6, 7, 8]]