text:
Q: append /remove anchor name from current url without refresh I want that on click event to append/remove the anchor name "#on" to be added to the current url without reloading the page, or use the href='#on' from links because it makes my page jump
Eg: http://www.example.com/page.html#on so I can get the detect the users that come from that url
and call the On() function
function On()
{
   //append to current url the anchor "#on"
}

function Off()
{
  //remove from the current url the anchor "#on"
}

$('.on').live('click', function() {
  On();
  return false;
});

$('.off').live('click', function() {
  Off();
  return false;
});

A: You don't really need jQuery for that, you can get/set the anchor name using location.hash. If you put it in your jQuery ready function, you can do some action if it's set to a certain value:
$(function(){
    // Remove the # from the hash, as different browsers may or may not include it
    var hash = location.hash.replace('#','');

    if(hash != ''){
        // Show the hash if it's set
        alert(hash);

        // Clear the hash in the URL
        location.hash = '';
    }
});

Note that when removing the hash, the trailing # might stay in the address bar. If you want to respond to live changes of the anchor, you can bind a callback to the hashchange event:
$(document).bind("hashchange", function(){
    // Anchor has changed.
});

If you want to prevent your page jumping to the top when clearing the anchor, you can bind the hashchange event to jump back to the previous scroll position. Check out this example: http://jsfiddle.net/yVf7V/
var lastPos = 0;

$('#on').click(function(){
    location.hash = 'blah';
});

$('#off').click(function(){
    lastPos = $(window).scrollTop();
    location.hash = '';
});

$(window).bind('hashchange',function(event){
    var hash = location.hash.replace('#','');
    if(hash == '') $(window).scrollTop(lastPos);
    alert(hash);
});

A: if you are using jquery try this code
$("a[href^=#]").on("click", function(e) {
    e.preventDefault();
    history.pushState({}, "", this.href);
});

A: Calling history.pushState({}, "", link) is similar to setting window.location = "#foo", in that both will also create and activate another history entry associated with the current document.
Note that pushState() never causes a hashchange event to be fired, even if the new URL differs from the old URL only in its hash.
const url = new URL(window.location);
url.hash = '#foo';
window.history.pushState({}, '', url);

https://developer.mozilla.org/en-US/docs/Web/API/History/pushState#examples
https://developer.mozilla.org/en-US/docs/Web/API/Window/hashchange_event


text:
Q: Access parent object property of image element I have a list of cats. Each cat object has a property cat.clicks that record the number of times the cat image has been clicked. The cat image's onclick calls the method cat.clickCat.
But of course 'this' in the clickCat method refers to the image element and not the cat object which contains the property 'clicks'.
How do I display and update the number of clicks on the image?

function Cat(src, name) {
  this.src = src;
  this.name = name;
  this.clicks = 0; //property recording no. of clicks
}

Cat.prototype.createCatItem = function() {
  let catDisplay = document.createElement("div");
  catDisplay.id = "catDisplay"
    let catName = document.createElement("h2");
    let catImg = document.createElement("img");
    let catCounter = document.createElement("div");
    catCounter.id = "clicker";
    catName.innerHTML = this.name;
    catImg.src = this.src;
    catImg.onclick = this.clickCat; //call the clickCat method
  catDisplay.appendChild(catName);
  catDisplay.appendChild(catImg);
  catDisplay.appendChild(catCounter);
  return catDisplay;
}

Cat.prototype.clickCat = function() {
  this.clicks += 1; //how to access the object property clicks from this method?
  let clickerDiv = document.getElementById("clicker")
  clickerDiv.innerHTML = ''
  clickerDiv.innerHTML = 'clicks = ' + this.clicks;
}

function App() {
  this.cats = [];
}

App.prototype.add = function(cat) {
  this.cats.push(cat)
}

App.prototype.listCats = function() {
  let container = document.getElementById("container");
  let ul = document.createElement("ul");
  for (let i=0; i<this.cats.length; i++){
    let li = document.createElement("li");
    li.innerHTML = this.cats[i].name;
    li.onclick = this.displayCat;
    ul.appendChild(li);
  }
  container.appendChild(ul);
}

App.prototype.displayCat = function() {
  let container = document.getElementById("container");
  let catDisplay = document.getElementById("catDisplay")
  let cats = app.cats;
  let chosenCat = cats.filter(cat => cat.name === this.innerHTML);
  let chosenCatItem = chosenCat[0].createCatItem();
  container.removeChild(catDisplay);
  container.appendChild(chosenCatItem);
  console.log(chosenCat);
}

App.prototype.showFirstCat = function() {
  let container = document.getElementById("container");
  let catDisplay = document.getElementById("catDisplay")
  let firstCat = app.cats[0].createCatItem();
  container.appendChild(firstCat);
}

let app = new App;

let tea = new Cat("http://placehold.it/350x150", "tea");
let snowball = new Cat("http://placehold.it/350x200", "snowball");
let triksy = new Cat("http://placehold.it/350x300", "triksy");
let vera = new Cat("http://placehold.it/350x350", "vera");
let jon = new Cat("http://placehold.it/350x400", "jon");

app.add(tea)
app.add(snowball)
app.add(triksy)
app.add(vera)
app.add(jon)

app.listCats();
app.showFirstCat();

My Cat Clicker

A: First of all .. beware of using this ... this always refer the object currently responsible to execute the scripts in browser ... so in your case the image is responsible for executing the click event and it has no property called clicks .. and that's why clicks is NaN
A good practice is preserve this into a variable to avoid the system replacement when executing (that=this)
    Cat.prototype.createCatItem = function() {
        let that=this; //preserving this value

        let catDisplay = document.createElement("div");
        catDisplay.id = "catDisplay"
        let catName = document.createElement("h2");
        let catImg = document.createElement("img");
        let catCounter = document.createElement("div");
        catCounter.id = "clicker";
        catName.innerHTML = this.name;
        catImg.src = this.src;
        catImg.onclick = function() {
            //alert(this);
            that.clicks += 1; //how to access the object property clicks from this method?
            let clickerDiv = document.getElementById("clicker")
            clickerDiv.innerHTML = ''
            clickerDiv.innerHTML = 'clicks = ' + that.clicks;
        }
        catDisplay.appendChild(catName);
        catDisplay.appendChild(catImg);
        catDisplay.appendChild(catCounter);
        return catDisplay;
    }

    //Cat.prototype.clickCat = function() {
    //    this.clicks += 1; //how to access the object property clicks from this method?
    //    let clickerDiv = document.getElementById("clicker")
    //    clickerDiv.innerHTML = ''
    //    clickerDiv.innerHTML = 'clicks = ' + this.clicks;
    //}

redpajama_set_name: RedPajamaStackExchange


text:
Q: LightGBM install error r, unable to troubleshoot This is the error that I am getting. I also tried all the other install options on their website and no luck. I am kind of lost on how I should trouble shoot this. Any help would be greatly appreciated.
 > install_github("Microsoft/LightGBM", subdir = "R-package")
 Downloading GitHub repo Microsoft/LightGBM@master
 from URL https://api.github.com/repos/Microsoft/LightGBM/zipball/master
 Installing lightgbm
 Installing 1 package: data.table
 Installing package into 'C:/Users/XXXXXXXXXX/Documents/R/win-library/3.4'
 (as 'lib' is unspecified)
 trying URL
 'https://cran.rstudio.com/bin/windows/contrib/3.4/data.table_1.10.4-3.zip'
 Content type 'application/zip' length 1577027 bytes (1.5 MB)
 downloaded 1.5 MB

 package 'data.table' successfully unpacked and MD5 sums checked
 Warning: cannot remove prior installation of package 'data.table'

 The downloaded binary packages are in

 C:\Users\XXXXXXXXXXXXX\AppData\Local\Temp\Rtmpa409YJ\downloaded_packages
 "C:/PROGRA~1/R/R-34~1.1/bin/x64/R" --no-site-file --no-environ --no-save --
 no-restore --quiet CMD INSTALL "C:/Users/XXXXXX  \
  XXXXX/AppData/Local/Temp/Rtmpa409YJ/devtools15b8405627ba/Microsoft-
LightGBM-04d4811/R-package" --library="C:/Users/XXXXXXXXX  \
  XXXXXXXXX/Documents/R/win-library/3.4" --install-tests

 ERROR: dependency 'data.table' is not available for package 'lightgbm'
* removing 'C:/Users/XXXXXXXXXX/Documents/R/win-library/3.4/lightgbm'
Installation failed: Command failed (1)
Warning message:
GitHub repo contains submodules, may not function as expected!

R.Version()
$platform
[1] "x86_64-w64-mingw32"

$arch
[1] "x86_64"

$os
[1] "mingw32"

$system
[1] "x86_64, mingw32"

$status
[1] ""

$major
[1] "3"

$minor
[1] "4.1"

$year
[1] "2017"

$month
[1] "06"

$day
[1] "30"

$`svn rev`
[1] "72865"

$language
[1] "R"

$version.string
[1] "R version 3.4.1 (2017-06-30)"

$nickname
[1] "Single Candle"

Stackoverlfow thinks that this post has to much code so I need to add more text to it so I am going to ramble on here about nothing so I can hit the character limit. I am bitterly sorry if you are reading this because I am wasting your time as well as my time writing this but systems are systems so I guess I just have to keep going. Kind of like Dory in finding Nemo. Just keep swimming, just keep swimming.

A: you can solve this by going into R studio and installing the data.table package. I had the same problem and this worked for me


text:
Q: Cannot encode 0th element of array in php I am working on a php script for multiple file uploading and getting json data from server for the file uploaded. However, the json response is not coming how it is supposed to be
php script

$con= new mysqli('localhost','root','','app');

$name='Dp User id ';
if(!empty($_FILES['files']['name'])&&!empty($_POST['id']))
    {
        $id=$_POST['id'];
        $files=$_FILES['files'];

        $response=array();
        $uploaded=array();
        $failed=array();

        $allowed=array('txt','jpeg','sig','pak','dll','jpg');

        foreach($files['name'] as $position=>$file_name)
        {

            $file_tmp=$files['tmp_name'][$position];
            $file_size=$files['size'][$position];
            $file_error=$files['error'][$position];

            $file_ext1=explode('.', $file_name);
            $file_ext=strtolower(end($file_ext1));

            if(in_array($file_ext,$allowed))
            {
                if($file_error===0)
                {
                    if($file_size<=2097152)
                    {
                        $file_name_new=$name.$id.'.'.$file_ext;
                        $upload_url =  $_SERVER['DOCUMENT_ROOT'].'/app2/User Files/User Id-'.$id.'/';
                        $file_destination=$upload_url.$file_name_new;
                        $Sql_Query = $con -> prepare("UPDATE profile SET pic= ? WHERE id = ?");
                        $Sql_Query -> bind_param("si", $file_destination,$id);
                        $sql = $Sql_Query -> execute();

                        if(move_uploaded_file($file_tmp,$file_destination))
                              {

                                //$uploaded[$position]=$file_destination.'
';
                                array_push($uploaded,array($position=>$file_destination.'
'));
                        }else{
                              $failed[$position]="[{$file_name}] failed to upload".mysqli_error($con).'
';
                        }
                    }else{
                          $failed[$position]="[$file_name] is too large.".mysqli_error($con).'
';
                    }
                }else{
                      $failed[$position]="[$file_name] has error {$file_error}".mysqli_error($con).'
';
                }
            }else{
                  $failed[$position]="[$file_name] has {$file_ext} which is not allowed".mysqli_error($con).'
';
            }
    }

        if(!empty($uploaded))
        {
             echo (json_encode(array(
               "success"=>1,
               "message" => $uploaded)));
        }

        if(!empty($failed))
        {
          echo json_encode(array(
            "success" => 0,
            "message" => $failed));
        }
    }

    mysqli_close($con);

    ?>

I want json to be returned for this script like this
{"success":1,
"message":[{"C:\/Apache24\/htdocs\/app2\/User Files\/User Id-94\/Dp User id 94.jpg
"},
{"1":"C:\/Apache24\/htdocs\/app2\/User Files\/User Id-94\/Dp User id 94.jpg
"},
{"2":"C:\/Apache24\/htdocs\/app2\/User Files\/User Id-94\/Dp User id 94.jpg
"}]}

but the json is coming like this
 {"success":1,
"message":[["C:\/Apache24\/htdocs\/app2\/User Files\/User Id-94\/Dp User id 94.jpg
"],
{"1":"C:\/Apache24\/htdocs\/app2\/User Files\/User Id-94\/Dp User id 94.jpg
"},
{"2":"C:\/Apache24\/htdocs\/app2\/User Files\/User Id-94\/Dp User id 94.jpg
"}]}

The 0th element is between the array, and i want it to be between object like the rest. Whenever i choose files and upload it, the 0th one always end up showing like this in response.Any help will be appreciated
Thanks in advance

A: php array with integer keys (including implicitly cast strings) starting from 0 gets encoded as JSON array but not JSON object. Meanwhile php array with string keys or integer keys not starting from 0 (I think that's your case here) will get encoded into JSON object by json_encode.
In your case you have two options:

*

*If you want your output to contain all objects instead of array for 1st (0)
element, just increase your $position variable by 1 when pushing elements
into your $uploaded and $failed arrays:
array_push($uploaded,array($position+1=>$file_destination.'
'));
                                    ^^

$failed[$position+1]=...
                 ^^

That of course will result in 1-based instead of zero-based list in your JSON output.

*Alternatively you can also pass JSON_FORCE_OBJECT as a second parameter to json_encode but that will get rid of your outer array for message...


text:
Q: Why don't Google's MX servers match the SSL certificate CN? Before sending an email to a google account my script looked up the MX records for google's email servers. The results are:
gmail-smtp-in.l.google.com
alt1.gmail-smtp-in.l.google.com
alt2.gmail-smtp-in.l.google.com
alt3.gmail-smtp-in.l.google.com
alt4.gmail-smtp-in.l.google.com

I then successfully connected to gmail-smtp-in.l.google.com and after EHLO I started a STARTTLS request to switch to SSL. However, I set the script to check and make sure the host(s) listed in the certificate match the domain I was connecting too.
stream_context_set_option($fh, 'ssl', 'CN_match', 'gmail-smtp-in.l.google.com`);

However, this is where things break. I got the following error:
stream_socket_enable_crypto(): Peer certificate CN='mx.google.com' did not match expected CN='gmail-smtp-in.l.google.com'

I checked to find out where nslookup mx.google.com was located and found it doesn't exist.
Server:     127.0.0.1
Address:    127.0.0.1#53

** server can't find mx.google.com: NXDOMAIN

Why doesn't the SSL certificate match the domains using it? Am I missing something?
The following is the cert my script received from them.
Array
(
    [name] => /C=US/ST=California/L=Mountain View/O=Google Inc/CN=mx.google.com
    [subject] => Array
        (
            [C] => US
            [ST] => California
            [L] => Mountain View
            [O] => Google Inc
            [CN] => mx.google.com
        )

    [hash] => fbf7dda6
    [issuer] => Array
        (
            [C] => US
            [O] => Google Inc
            [CN] => Google Internet Authority
        )

    [version] => 2
    [serialNumber] => 280762463620984597407910
    [validFrom] => 120912115656Z
    [validTo] => 130607194327Z
    [validFrom_time_t] => 1347451016
    [validTo_time_t] => 1370634207
    [purposes] => Array
        (
            [1] => Array
                (
                    [0] => 1
                    [1] =>
                    [2] => sslclient
                )

            [2] => Array
                (
                    [0] => 1
                    [1] =>
                    [2] => sslserver
                )

            [3] => Array
                (
                    [0] => 1
                    [1] =>
                    [2] => nssslserver
                )

            [4] => Array
                (
                    [0] =>
                    [1] =>
                    [2] => smimesign
                )

            [5] => Array
                (
                    [0] =>
                    [1] =>
                    [2] => smimeencrypt
                )

            [6] => Array
                (
                    [0] => 1
                    [1] =>
                    [2] => crlsign
                )

            [7] => Array
                (
                    [0] => 1
                    [1] => 1
                    [2] => any
                )

            [8] => Array
                (
                    [0] => 1
                    [1] =>
                    [2] => ocsphelper
                )

        )

    [extensions] => Array
        (
            [extendedKeyUsage] => TLS Web Server Authentication, TLS Web Client Authentication
            [subjectKeyIdentifier] => 69:B3:67:5C:04:7F:16:EF:C1:85:FB:E8:2D:E4:FC:21:E9:7D:93:AF
            [authorityKeyIdentifier] => keyid:BF:C0:30:EB:F5:43:11:3E:67:BA:9E:91:FB:FC:6A:DA:E3:6B:12:24

            [crlDistributionPoints] => URI:http://www.gstatic.com/GoogleInternetAuthority/GoogleInternetAuthority.crl

            [authorityInfoAccess] => CA Issuers - URI:http://www.gstatic.com/GoogleInternetAuthority/GoogleInternetAuthority.crt

            [basicConstraints] => CA:FALSE
            [subjectAltName] => DNS:mx.google.com
        )

)

A: There are two possible reasons for this.

*

*Firstly SMTP host name matching has traditionally been defined quite vaguely. You can check the historical notes about this in RFC 6125 (a recent RFC about best practicises for host name verification, not yet widely implemented). RFC 3207 (Secure SMTP over Transport Layer Security) doesn't give much details as to where the host name should be in the certificate. RFC 4954 (SMTP Service Extension for Authentication) gives more details and talks about Subject Alternative Names, but it's in the context of SASL. Ambiguous or vague host name matching specifications are often a reason why no correct attempt to match the host name is made at all, unfortunately.

*Secondly, SSL/TLS is rarely used between Mail Transfer Agents (MTA). What you're doing by getting the MX DNS record and trying to send an e-mail directly to it is typically done my MTAs, not so much by a Mail Submission Agent.
Typical usage of SSL/TLS for SMTP is between a Mail User Agent (the e-mail client) and a Mail Submission Agent (your ISP's e-mail server, where you have to authenticate).
SSL/TLS between MTAs is hard to set up, because not every server supports it and it's hard to know which MTAs will support it. Some people advocate "optimistic TLS" support, whereby you try to see whether the server you're talking to supports TLS and fall back to plain SMTP if it doesn't. There's unfortunately little to gain by doing so, since you're obviously vulnerable to MITM attacks as soon as you're willing to downgrade anyway.
In addition, the MX entry you get may itself have been compromised (at least without DNSSEC).
Overall, this actually makes it quite hard to rely on any form of transport security for e-mail beyond the MUA/MSA connection. This probably explains why there's little emphasis on configuring MX servers properly for SSL/TLS.


text:
Q: JavaScript inheritence and array I defined my classes like that:
function Employee () {
    this.name = "";
    this.val = new Array();
}

function WorkerBee () {
    this.beeQueen = "lola";

    this.setVal = function(val) {
        this.val.push(val);
    };
}
WorkerBee.prototype = new Employee;

function SalesPerson () {
    this.dept = "development";
}
SalesPerson.prototype = new WorkerBee;

function Engineer () {
    this.dept = "R&D";
}
Engineer.prototype = new WorkerBee;

Problem: all the objects I create share the same val array:
var mark = new WorkerBee;
mark.name = "Mark";
mark.setVal('00000')

var louis = new SalesPerson;
louis.name = "Louis";
louis.setVal('11111')

var ricky = new SalesPerson;
ricky.name = "Ricky";
ricky.setVal('33333')

var john = new Engineer;
john.name = "John";
john.setVal('55555');

This:
html += "

Name: " + mark.name;
html += "
Val: " + mark.val;

html += "

Name: " + louis.name;
html += "
Val: " + louis.val;

html += "

Name: " + ricky.name;
html += "
Val: " + ricky.val;

html += "

Name: " + john.name;
html += "
Val: " + john.val;

displays:
Name: Mark
Val: 00000,11111,33333,55555

Name: Louis
Val: 00000,11111,33333,55555

Name: Ricky
Val: 00000,11111,33333,55555

Name: John
Val: 00000,11111,33333,55555

I read http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/ and http://javascriptweblog.wordpress.com/2010/06/07/understanding-javascript-prototypes/ but I'm still confused!
When I use a string instead of an array this works well (because the reference to the string is overwritten I suppose) but how to do it with array ?
So I can have:
Name: Mark
Val: 00000
Name: Louis
Val: 11111
Name: Ricky
Val: 33333
Name: John
Val: 55555

A: You need to apply the "parent" constructor in your "inheriting" constructor functions:
function WorkerBee () {
    Employee.apply(this);
    /*...*/
}
WorkerBee.prototype = new Employee();

Do the same for all your "inherited" constructor functions:
function SalesPerson () {
    WorkerBee.apply(this);
    /*...*/
}
SalesPerson.prototype = new WorkerBee();

function Engineer () {
    WorkerBee.apply(this);
    /*...*/
}
Engineer.prototype = new WorkerBee();

See the example on jsfiddle.
And like @austincheney pointed out, JavaScript has no "classes" - only functions (which are objects), constructors (which are functions) and objects.

JavaScript uses prototypal inheritance. This means that when you try to access a property (or function) of an object which doesn't exist, it will delegate to the prototype object.
Consider:
var isaacNewton = {
    name: 'Isaac Newton'
};

function Scientist() {}
Scientist.prototype = isaacNewton;

var neilDeGrasseTyson = new Scientist();

console.log(neilDeGrasseTyson.name);

isaacNewton.name = 'Sir Isaac Newton';

console.log(neilDeGrasseTyson.name);

The output here is:
Isaac Newton
Sir Isaac Newton

Object neilDeGrasseTyson hasn't inherited the name property. It simply doesn't have one. Since it doesn't have a property name when we try to access name the neilDeGrasseTyson  object will delegate to the prototype object Scientist.prototype, and return the value of Scientist.prototype.name which is isaacNewton.name.
In your code, objects mark, louis, ricky and john don't have a property val. All those calls to setVal end up manipulating WorkerBee.prototype.val since none of those objects have their own val property. By applying the Employee constructor to them, you introduce the properties of an Employee to them, so they don't have to delegate.
To drive the point home a little more, another solution would have been to put the method setVal in Employee and give each "inheriting" constructor a this.val property: http://jsfiddle.net/FDCXF/1/

A: 1) JavaScript does not have classes.
2) JavaScript only has function scope and not block scope.
3) A variable is only provided scope with the "var" keyword.
Re-engineer your code knowing this and see if you still encounter this problem.


text:
Q: Rails convention for case statement in view I am new  to ruby and rails so thought I'd ask a question on conventions.
I have a view which produces a list of items in a table and I was asked to make a change and in doing so have added a case statement to the view which I don't think is the correct way of doing things so thought that I would double check.
The change I made was just to add a class to the tr depending on the value of the last table column.
list.rhtml

        ID #
        Organisation
        Product
        Carrier
        Carrier Ref
        Post Code
        Status

    <%= render :partial => 'circuit/list_item', :collection => @circuits %>

list_item.rhtml
<%
# code I have added
@tr_class = ''

case list_item.status
when 'Handover'
  @tr_class = ''
when 'Unprocessed'
  @tr_class = 'high_priority'
when 'Ceased'
  @tr_class = 'low_priority'
else
  @tr_class = ''
end
# end of newly added code
%>

<tr class="<%= @tr_class %>">
    <a href='/circuit/update/<%= list_item.id %>'><%= list_item.id_padded %>
    <%= list_item.organisation.name if list_item.has_organisation? %>
    <%= list_item.product_name %>
    <%= list_item.carrier.name %>
    <%= list_item.carrier_reference %>
    <%= list_item.b_end_postcode %>
    <%= list_item.status %>

Is there a Rails pattern or convention that can get the case statement out of this view?

A: If understand properly your question, I think you should put the case statement inside a helper function:
app/helpers/list_helper.rb
module ListHelper
  def tr_class_for_status(status)
    case status
    when 'Unprocessed'
      'high_priority'
    when 'Ceased'
      'low_priority'
    else
      ''
    end
  end
end

_list_item.rhtml
<tr class="<%= tr_class_for_status(list_item.status) %>">


text:
Q: How to ajax update an item in the footer of a PrimeFaces dataTable? This is a visual of the table I have:

+---------+------------+-------------------+
| Header1 |  Header2   | Header3           |
+---------+------------+-------------------+
| Row A   |  Input A   | Calc'ed output A  |
| Row B   |  Input B   | Calc'ed output B  |
| etc..   |  etc..     |  etc..            |
+---------+------------+-------------------+
|    Total:          Total calc'ed output  |
+------------------------------------------+

And the stripped-down code:
<p:dataTable id="myTable" value="#{myBean.someList}"
    var="currentItem">

    <p:column headerText="Header1">
        <h:outputText value="#{currentItem.name}" />
    </p:column>

    <p:column headerText="Header2">
        <pe:inputNumber value="#{currentItem.inputVal}">
            <p:ajax event="change" listener="#{myBean.changeListener}"
                update="outputVal outputTotal" />
        </pe:inputNumber>
    </p:column>

    <p:column headerText="Header3">
        <h:outputText id="outputVal" value="#{currentItem.outputVal}" />
    </p:column>

    <f:facet name="footer">
        Total:
        <h:outputText id="outputTotal" value="#{myBean.total}" />
    </f:facet>

</p:dataTable>

The myBean.someList is an ArrayList<SomeOtherBean> with one String and two Integers, with just getters and setters.  The myBean.changeListener calculates the second Integer from the first for the given row, and also the total for all rows.
So, when I type in one of the inputs then focus out, the listener is called and the calculation done, but on screen, the value in the third column changes, but the total stubbornly remains zero.  I'm fairly sure this has something to do with PrimeFaces appending the row index to the generated id's of each input and output, but I can't figure out how to get to the output in the footer (whose generated id is mainForm:myTable:0:outputTotal).
Now, I could just update the parent table. However whenever the input to receive focus is part of the update target, the focus is lost, and I am under extremely strict accessibility rules that this table must be keyboard friendly (type a number, tab, type a number, tab, etc...)
I have tried:

*

*update=":outputTotal" (gave exception Cannot find component with identifier...)

*update="myTable:0:outputTota (same exception)

*update="myTable:outputTotal" (no update, total stays zero)

*wrap the text in a panelGroup and update that (no update)

(PrimeFaces 3.5.0 with MyFaces unknown version)

A: You can't really update the values of the table from within the table. However, you can use p:remoteCommand to achieve this. Also, I would probably use the cellEdit event on the whole table (instead of a single p:ajax on your pe:inputNumber). The overall result would be:
<p:remoteCommand name="refreshFooter" update=":formName:outputTotal"/>
...
<p:dataTable id="myTable" value="#{myBean.someList}" var="currentItem">

    <p:column headerText="Header1">
        <h:outputText value="#{currentItem.name}" />
    </p:column>

    <p:column headerText="Header2">
        <pe:inputNumber value="#{currentItem.inputVal}">
            <p:ajax event="change" listener="#{myBean.changeListener}" process="@this"
                oncomplete="refreshFooter();" update="outputVal"/>
        </pe:inputNumber>
    </p:column>

    <p:column headerText="Header3">
        <h:outputText id="outputVal" value="#{currentItem.outputVal}" />
    </p:column>

    <f:facet name="footer">
        Total:
        <h:outputText id="outputTotal" value="#{myBean.total}" />
    </f:facet>

</p:dataTable>

Please note that you might need to add partialSubmit="true" to the p:ajax, this way you only submit the component's data. If you like the cellEdit event idea, you need to make the dataTable editable, and add the following in your p:dataTable, and get rid of the p:ajax inside your pe:inputNumber
<p:ajax event="cellEdit" partialSubmit="true" listener="#{myBean.onCellEdit}"
    process="@this" oncomplete="refreshFooter();"/>

Good luck!

A: Update PrimeFaces
This issue was finally fixed in PrimeFaces 11, or PrimeFaces Elite 8.0.8 / 10.0.1. With PrimeFaces 11+ you can use partialUpdate="false" on the data table. Downside of this fix is that it will also update the headers (and filters), so it might update the filter input for you while you are typing. You could set a delay on the filter event to improve on this, but the effect won't be gone, only less noticeable.
See:

*

*https://github.com/primefaces/primefaces/issues/1178

*https://github.com/primefaces/primefaces/issues/7165

*https://github.com/primefaces/primefaces/pull/7157
PrimeFaces.ab instead of p:remoteCommand
If you don't want to create p:remoteCommands to update components on a data table filter event (well, I don't), you could use:
<p:ajax event="filter"
        oncomplete="PrimeFaces.ab({source:'#{component.clientId}',process:'@none',update:'componentToUpdate'})"/>

True, this looks a bit messy, but you can create a custom EL function to reduce this to:
<p:ajax event="filter"
        oncomplete="#{my:ajaxUpdate('componentToUpdate')}"/>


text:
Q: How to get custom header from response (retrofit & rxjava) I am trying to get some custom HTTP headers from all the REST API responses in my code.
Here is how I initiate the client:
private fun initializeClient(): OkHttpClient {
        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        val httpClient = OkHttpClient.Builder()
                .addInterceptor(object : Interceptor {
                    override fun intercept(chain: Interceptor.Chain): Response {
                        val original = chain.request()

                        val request = original.newBuilder()
                                .header("Content-Type", "application/json")
                                .method(original.method, original.body)
                                .build()

                        return chain.proceed(request)
                    }

                })
                .addInterceptor(interceptor)
                .build()
        return httpClient
    }

private fun initializeApi() {
        api = Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(initializeClient())
                .build()
                .create(RestApi::class.java)
    }

Here is a sample of the retrofit implementation:
@POST("/register")
    fun registerUser(@Body registerPostData: RegistrationForm): Single<RegistrationResponse>

and the ViewModel part:
disposable.add(
                api.registerUser(form)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeWith(object : DisposableSingleObserver<Member>() {
                            override fun onSuccess(value: RegistrationResponse?) {
// no headers in here
                                response.value = value
                            }

                            override fun onError(e: Throwable?) {

                            }

                        })
        )

The server returns some x-custom-header in all API responses, which I need to capture in all calls.
Thank you!

A: Change your retrofit class to return a Response:
@POST("/register")
fun registerUser(@Body registerPostData: RegistrationForm): Single<Response<RegistrationResponse>>

then:
override fun onSuccess(result: Response<RegistrationResponse>?) {
    // get header from response.headers()
}


text:
Q: Query users and count totals based on meta values Users can choose a value from a multiple choice checkbox on sign up. In this example the choices are Cat or Dog.
I have a WP User Query and want to count the amount of users that have each meta value, and display something like '45 Cat People, 15 Dog People'.
Below are two separate queries but I'd like to loop through the values and display using one foreach query but not sure how to access the meta value to do this. Also the ability to output the value name rather than hard coding it would be useful...
    <?php

    // Meta value 'Cats'

    $user_query = new WP_User_Query(array(
        'role' => 'Subscriber',
        'meta_query' => array(
        array(
            'key' => 'favourite_animal',
            'value' => 'Cat',
        ),
      )
    ));

    $users = $user_query->get_results();
    $total = $user_query->get_total();

    echo $total . 'Cat people';

    // Meta value 'Dogs'

    $user_query = new WP_User_Query(array(
        'role' => 'Subscriber',
        'meta_query' => array(
        array(
            'key' => 'favourite_animal',
            'value' => 'Dog',
        ),
      )
    ));

    $users = $user_query->get_results();
    $total = $user_query->get_total();

    echo $total . 'Dog people';

    ?>


text:
Q: Spring Java config specified Beans won't initialize I've read Spring In Action, and prefer Java config over XML config. So I used Java config to write my app, but our deployment environment requires me to use XML config. So I wrote an XML config, and it's only function is to import the root Java config.
The Java config code looks like this:
package com.somegroup.app;
@Configuration
@ComponentScan(basePackages = "com.tianchengsys.crawlers.cqs")
public class AppCtxConfig {

    @Bean
    public SomeType aSomeType() {
           return new SomeType()
    }

}

and the XML config looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"

    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://code.alibabatech.com/schema/dubbo
    http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <context:annotation-config />

    <bean class="com.somegroup.app.AppCtxConfig" lazy-init="false" />

</beans>

When I created a ClasspathXmlContext("classpath:spring-context.xml") in Eclipse, the SomeType bean defined in Java config is initialized, and registered to springs ApplicationContext. But when I deployed this app (all dependencies are in a lib directory), the AppCtxConfig bean defined in the XML config was just treated an ordinary bean (not configuration).
It was created, but the beans defined in it were not initialized. Spring some times warned the someType method in the Java config should be static. I did changed it to static, it also didn't work.

A: This is because you are creating AppCtxConfig as a regular bean, which it isn't.
As the commentor suggested, add the component-scan on and set base-package to the package where your config class is located in:
<!-- Scan the JavaConfig -->
<context:component-scan base-package="com.somegroup.app" />

If your app package is the root package, with all subpackages inside, add a new config package and move the AppCtxConfig inside it.
So add:
<!-- Scan the config package with AppCtxConfig inside it -->
<context:component-scan base-package="com.somegroup.app.config" />


text:
Q: How to display a sentence with VHDL on a FPGA board I am just wondering if it is possible to display a sentence, for example "SOLD OUT", on the 7-segment display of the FPGA board where I can only show four letters.
I want it to display SOLD then OUT.
If it is possible to implement that, how can I do it? Clock divider?

A: You start by researching what the board does.  How does it connect to the LCD display?  What are the waveforms required to drive a value to the display.  It will be different for different boards.  The Digilent boards tend to be common Anode.  Some Altera boards connect all four 7-segment displays directly to FPGA IO (wastes IO, but who cares when you have plenty).
Next you determine, how do I display a character on the display.  What holds the value?  What translates the value from an internal representation, such as ASCII to the value on the display.
WRT clocks, my preference is to use a common FPGA clock and use load enables that provide periodic indication it is time to load the other image.
Think about how fast you should be switching the display?  My recommendation is to make sure you display each value for 1 sec before switching and adjust after you see it working.  If you decrease the display time too much, your display will blur because neither value is displayed long enough.
Next how do I display 4 characters?
Next how do I make the characters shift or alternate between different values.  This could be a character wide shift register, it could be two different display registers.
In each of these steps you should be drawing a picture of the hardware before writing any code.


text:
Q: Counting $\mathrm{mod}\:p$ solutions of Diophantine equation in two variables taking $O(p^2)$ time Are there Diophantine equations in two variables such that counting solutions $\mathrm{mod}\:p$ requires $O(p^2)$ time?
Geometrically this means we have to sort through a positive proportion of the affine plane before being sure we have counted all solutions (modulo the complexity of addition and multiplication).
Non-example: it takes $O(\log p)$ time to count (and output) the $\mathrm{mod}\:p$ solutions of $x+y=0$ as there are $p$ solutions.

A: At least for fixed degree, the answer appears to be 'no' — it seems to be well-established that the number of roots of a univariate polynomial $g(x)$ of degree $d$ modulo a prime $p$ can be determined in $O\left((d+\log p)^{O(1)}\right)$ time, which gives a quasilinear time algorithm for a polynomial $f(x,y)$ by just evaluating $f()$ at each value of $y$ to find $p$ univariate polynomials (which can be done in basically $O(dp)$ time) and count the number of roots for each in turn. This means that for any fixed polynomial, it can be done in $O(p(\log p)^{O(1)})$ time as $p$ increases. I don't know whether you can get time sub-linear in $p$, though I wouldn't be surprised if it was an open question. Note that 'linear in $p$' here is still exponential in the size of the input (giving $p$ in binary) and that's the usual metric for this sort of problem for large $p$, so the usual target here is really something in $p^{o(1)}$.
If we allow for an arbitrary polynomial of degree $\lt p$ then this no longer works, but note that then the input naively has size $\Theta(p^2)$ so we can't even read all the data in less time then that. The one case I can't account for is the case of sparse bivariate polynomials of arbitrarily high degree mod $p$, where it seems from at least a bit of digging like not much is specifically known.


text:
Q: make Kile default for tex files I re-installed Ubuntu due to some issues but before the re-install, I was able to make my default tex editor by going into properties, other apps, and selecting Kile.
Now Kile isn't an option to select.  What can I do?


text:
Q: Отложить выполнение функции (фоновая функция) Пытаюсь на питоне реализовать выполнение отложенной функции (фоновую функцию), которая бы не прерывала выполнение других функций.
Суть функции - через 1 час/день изменить значение в строке коллекции MongoDB.
Я стал изучать asyncio, но и в нем не нашел решения. Видите ли, выполнение таких функций блокируют мой синхронный код. Пока что я понял, как запустить N функций одновременно, но весь код, который идет после запуска, не продолжит выполняться, пока не завершатся все N функций. Расскажите, пожалуйста, как не блокировать код?
import asyncio

def rocket(value):
    rocketName = value
    print(rocketName)

async def print_nums():
    num = 1
    while num < 10:
        print(num)
        num += 1
        await asyncio.sleep(0.1)

async def main():

    tasks = []
    for i in range(10): # запускаю 10 функций за раз
        tasks.append( asyncio.create_task(print_nums()) )

    await asyncio.gather(*tasks)

    print("i = " + str(i))

if __name__ == '__main__':
    asyncio.run(main())
    rocket("myFirstRocket") # не выполнится, пока работат строка выше

A: Для этого вам не нужен asyncio, используйте потоки, или запускайте
скрипт по крону. После завершения работы функции, вызванной из
asyncio.run, цикл событий тоже завершается.
@extrn


text:
Q: Phaser doesn't load audio function in json file Phaser loads all the files except it is failing to load audio file.
JSON file with assets to load (image and audio file):
 "assets": {
    "background_image": {
      "type": "image",
      "source": "assets/images/background.png"
    },
    "background_audio":{
      "type": "audio",
      "source":"assets/sound/intro_screen_sound.wav"
    }

Code used to load JSON file:
 RPG.LoadingState.prototype.preload = function () {
     "use strict";
     var assets, asset_key, asset;
     assets = this.level_data.assets;
     for (asset_key in assets) { // load assets according to asset key
         asset = assets[asset_key];
         switch (asset.type) {
             case "image":
                 this.game.load.image(asset_key, asset.source);
                 break;
             case "audio":
                 this.game.load.audio(asset_key, asset.source);
                 break;
             case "spritesheet":
                 this.load.spritesheet(asset_key, asset.source, asset.frame_width, asset.frame_height, asset.frames, asset.margin,
asset.spacing);
                 break;
             case "tilemap":
                 this.load.tilemap(asset_key,asset.source,null,Phaser.Tilemap.TILED_JSON);
                 break;
         }
         this.load.text("user_input", this.level_data.user_input);
     }


text:
Q: Operator '>' cannot be applied to 'android.widget.EditText','int' I'm doing an app for Android that will generate a random number between 1 and 10,000 and compare it to an EditText inputType:number and then in a TextView tell if it is bigger or smaller.
But when I try to make it, android studio returns an error

Operator '>' cannot be applied to 'android.widget.EditText','int'

Here's the code:
package com.boodle.guessthenumber;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_main);
   }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

        public void guess (View view){

        EditText textguess = (EditText) findViewById ( R.id.textguess );

        TextView result = (TextView) findViewById(R.id.resulto);

        int rand = (int) (Math.random()*10000+1);

        if (textguess > rand) {
            result.setText(textguess.getText() + "is too big" );
            }

        if (textguess < rand) {
            result.setText(textguess.getText() + "is too small" );
            }

        }

A: You can't use a comparison operator to (reasonably) compare an integer and an instance of the EditText class.
Here, you want to get the number that your EditText contains:
String guessStr = textguess.getText().toString();
Then, to get the actual integer value to compare with,
int theGuess = Integer.parseInt(guessStr);
EditText is a complex object with lots of fields, while int rand is just an integer. It doesn't make sense to compare the entirety of an EditText object, with all of its various fields, with just a number.
In this case, you have to pick out the text that your user entered into your EditText field -- which will always be a String even if you've specified that it's a number-only field -- then use the Integer class' parseInt method to convert the String into something you can compare with an int.
Another problem with your code, if your aim is the archetypal 'guess the number' game:
Every time your user will try to guess, they'll be checking their guess against a new random number every single time, since you generate the number they're trying to guess every single time in the guess() function.

A: 1) you can not assign views out of the onCreate. What you can do is declare class-wide view objects and then assign them with findviewbyid() in the onCreate so you can use them class-wide.
2) to get the number to compare you first need to do input = (EditText object).gettext.toString() and then entery  = Integer.parseInt(input). After that you can compare the numbers.
Sorry about the formating, I am using the app.


text:
Q: Irreducible polynomial $p(x)=x^3+2x+1$ Consider an irreducible polynomial $p(x)=x^3+2x+1$ in the ring $\mathbb Z_3 [x]$. I beg help on  how to solve the following two cases basing the polynomial above?.
(i) Find a representative polynomial of degree less than $3$ in $\mathbb Z_3[x]/{\langle p(x)\rangle}$ to the polynomial $x^4+x\in\mathbb Z_3[x]$.
(ii) Let $\alpha=x+\langle p(x)\rangle$ in   $E=\mathbb Z_3[x]/{\langle p(x)\rangle}$. Show that $p(\alpha)=0$ in $E$.
Thanks.

A: (i) In $E=\mathbb Z_3/\langle p(x)\rangle$, $x^3+2x+1=0$, thus $x^3=-(2x+1)$, and $x^4=-x(2x+1)=-2x^2-x$. Thus $x^4+x=-2x^2=x^2$ since $-2=1$ in $\mathbb Z_3$.
(ii) What is $p(\alpha)$? You can compute a representative of it:
$$p(\alpha)=p(x+\langle p(x)\rangle)=\langle (x+p(x))^3+2(x+p(x))+1\rangle=\dotsb$$
Then you just have to simplify as in (i). (Don't forget that $\langle p(x)\rangle=0$ in $E$.)


text:
Q: Cannot increase "Max open files" for Wildfly while ulimit already changed to unlimit I'm working on Ubuntu 16.04 with wildfly. I got an error "Caused by: java.net.SocketException: Too many open files". So I changed the ulimit to ulimited for all users.
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 128429
max locked memory       (kbytes, -l) 16384
max memory size         (kbytes, -m) unlimited
open files                      (-n) 65535
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 65535
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

in /etc/security/limits.conf
* soft     nproc          65535
* hard     nproc          65535
* soft     nofile         65535
* hard     nofile         65535
root soft     nproc          65535
root hard     nproc          65535
root soft     nofile         65535
root hard     nofile         65535

The problem is that another java process are got a new open files value(65535) except wildfly
 cat /proc/1717/limits
Limit                     Soft Limit           Hard Limit           Units
Max cpu time              unlimited            unlimited            seconds
Max file size             unlimited            unlimited            bytes
Max data size             unlimited            unlimited            bytes
Max stack size            8388608              unlimited            bytes
Max core file size        0                    unlimited            bytes
Max resident set          unlimited            unlimited            bytes
Max processes             128429               128429               processes
Max open files            4096                 4096                 files
Max locked memory         16777216             16777216             bytes
Max address space         unlimited            unlimited            bytes
Max file locks            unlimited            unlimited            locks
Max pending signals       128429               128429               signals
Max msgqueue size         819200               819200               bytes
Max nice priority         0                    0
Max realtime priority     0                    0
Max realtime timeout      unlimited            unlimited            us

I already restart the server. Please advise me how to fix this issue

A: Max process for JBoss ulimit can be set according to the daily load received in server, but standard size is 65536, and openfiles also can be set more than 65536. We performed loadtest with concurrent users and max hits per sec to conclude on numbers.
Check JBoss ulimit:
jboss@user1>ulimit -aS ---> soft limit
jboss@user1>ulimit -aH ---> hard limit


text:
Q: Culbera: Selecting things from dropdown list in an Android app I am trying to test a drop down list with Culbera. My menu structure is as follows
Main Page
   -- Program  - Setup - Arm
                       - Torque
   -- Test

Now Arm  displays (makes visible) a drop down list that shows the list of ARM types.
I want to pick one from the dropdown list and then press Program Arm Type. For some reason this is not working as expected.
When I used
python culebra -Gu -o command_trace.txt --scale=01.0

the trace I got is
vc.findViewWithTextOrRaise(u'Arm').touch()
vc.sleep(_s)
vc.dump(window=-1)
vc.findViewByIdOrRaise("id/no_id/21").setText(u"xxx")
vc.sleep(_s)
vc.dump(window=-1)
vc.findViewWithTextOrRaise(u'OK').touch()
vc.sleep(_s)
vc.dump(window=-1)
vc.findViewWithTextOrRaise(u'Program ArmType').touch()
vc.sleep(_s)
vc.dump(window=-1)

It popped up a text box. (I have no idea where it is coming from)? Can someone explain how to select things from a dropdown list in Culbera
import re
import sys
import os
import time

from com.dtmilano.android.viewclient import ViewClient
from com.dtmilano.android.adb.adbclient import DOWN_AND_UP

kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': False}
device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1)
kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': True}

_s = 3
_v = '--verbose' in sys.argv

vc = ViewClient(device, serialno, **kwargs2)

# Installs the Android package. Notice that this method returns a boolean, so you can test
# to see if the installation worked.
#vc.installPackage('AbcApp.Android.AbcApp.Android-Signed.apk')

# sets a variable with the package's internal name
package = 'AbcApp.Android.AbcApp.Android'

# sets a variable with the name of an Activity in the packag
activity = 'md591ecfcc0189ae8714.MainActivity'

# sets the name of the component to start
runComponent = package + '/' + activity

# Runs the component
device.startActivity(component=runComponent)

vc.sleep(5)

def GoToView(s):
    vc.findViewWithTextOrRaise(unicode(s)).touch()
    vc.sleep(_s)
    vc.dump(window=-1)

vc.dump(window=-1)

GoToView('Program')

GoToView('Setup')
vc.findViewWithTextOrRaise(u'Arm').touch()
vc.sleep(_s)
vc.dump(window=-1)

vc.findViewWithTextOrRaise(u'OK').touch()
vc.sleep(_s)
vc.dump(window=-1)
vc.findViewWithTextOrRaise(u'Program ArmType').touch()
vc.sleep(_s)
vc.dump(window=-1)

GoToView('Main')

A: Picker
A Picker is a widget composed of other widgets such as Button and EditText.
This simple example shows a TimePicker

then, if you run
dump

this is part of the output
  android.widget.TimePicker com.dtmilano.android.demoapplication:id/timePicker
     android.widget.NumberPicker
        android.widget.Button  2
        android.widget.EditText android:id/numberpicker_input 3
        android.widget.Button  4
     android.widget.NumberPicker
        android.widget.Button  33
        android.widget.EditText android:id/numberpicker_input 34
        android.widget.Button  35
     android.widget.NumberPicker
        android.widget.EditText android:id/numberpicker_input AM
        android.widget.Button  PM

where you can see what I mean by composed.
Then, when you click on some of the EditTexts, culebra understands that your intention is to enter some text and thus it shows the entry dialog

If you click on any of the Buttons, culebra will also understand your intention is to increase or decrease the Picker value and generates the corresponding touches.
I'm not really sure what are the drop downs you mentioned. Are they Spinners?
The output of dump will help understand.
Spinner
The case for the Spinner is a bit different as it's composed of the entry and the drop down menu.
However, if you take a look at touch zones (CTRL+Z) you will see the entry and the drop down arrow are part of the same zone

I'm using ApiDemos here so if you want to test it or ask new questions we will have something to compare.
Then, you click on the Spinner it opens the drop down

and you will get this code generated
vc.dump(window=-1)
vc.findViewWithTextOrRaise(u'green', root=vc.findViewByIdOrRaise('id/no_id/4')).touch()
vc.sleep(_s)
vc.dump(window=-1)
vc.findViewWithTextOrRaise(u'violet').touch()

The first touch() might be a little trickier if you don't know the current value then you can use either the View Id or a regular expression to match all the options.


text:
Q: how to design layout button to be half one color, half other I need to design button for android app to be rectangle, and to be half one color, half other. In XML of course.
I have tried this:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<padding
    android:left="7dp"
    android:top="15dp"
    android:right="7dp"
    android:bottom="15dp" />
<gradient
    android:startColor="#a241cb"
    android:endColor="#a241cb"
    android:type="linear"
    android:angle="90"/>
<stroke>
    android:width="1dip"
    android:color="#a241cb" />
<corners android:radius="0dp" />
</shape>

Any help is appreciated

A: Try this:

frist create background.xml in drwable folder
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient android:startColor="#4A225E"
        android:endColor="#4C4064"
        android:centerColor="#B4AFC5"/>
</shape>

and then set button backgrond its work for me

A: you can achieve this by using gradients as background. use this
create a new XML file under res/drawable folder and name it as button_bg.xml.
button_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#D5DDE0"
      android:centerColor="#e7e7e8"
      android:endColor="#CFCFCF"
      android:angle="270" />
</shape>

now use it for your Button like this:
android:background="@drawable/button_bg"

Hope it helps. :)

A: Using a 9 patch like this (save it in your drawable folder as bw_bg.9.png):

You can get a result like this:

Example layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f00f"
    >
    <Button
        android:layout_width="120dp"
        android:layout_height="60dp"
        android:layout_centerInParent="true"
        android:background="@drawable/bw_bg"
    />
</RelativeLayout>

Don't mind the size (it's running on a Froyo 2.8 inch screen).
Also don't mind the notification (it's from another running app).


text:
Q: Abstract methods not-implemented error is not being thrown So i was just trying to learn java coming from a C++ background, as part of a quick ramup I just implemented a base class from a abstract class as below
abstract class my_abstract_class
{
    abstract void my_abstract_function();
}

class my_concrete_class extends my_abstract_class
{

}

public class ConcreteClasses {

    public static void main(String args[])
    {
        my_concrete_class my_concrete_class = new my_concrete_class();

    }

This passes even though my concrete class is not implementing the abstract method nor is it a abstract class. Shouldn't a compilation error be thrown? Or am i missing something very basic here
PS: The error is shown by eclipse as part of the static analysis but I still wonder how this program compiles and runs without any issues

A: The Eclipse compiler is a bit special. If the code doesn't compile, it generates error messages, but still compiles the classes by generating dummy methods throwing exceptions.
If you run a project which has compilation errors, it warns you that you shouldn't do that, but you can still proceed.
Just don't do that, and don't ignore error messages from the compiler.


text:
Q: Button On Click Change Rotation of an Image I have an image that I want to transform in terms of rotation when click on a button.
How do I achieve this in Jquery?
JS Fiddle Link: http://jsfiddle.net/DJ8p7/
$("spin").click(function(){
  $("myImage").css("transform", "rotate(45deg)");
  $("myImage").css("-webkit-transform", "rotate(45deg)");
  $("myImage").css("-ms-transform", "rotate(45deg)");
});

A: Consider the following example: https://jsfiddle.net/Twisty/d43tfp2c/11/
JavaScript
$(function() {
  var cDeg = 0;

  function animateRotate(elem, angle) {
    var $elem = $(elem);
    $elem.animate({
      deg: angle
    }, {
      duration: 2000,
      step: function(now) {
        $elem.css({
          transform: 'rotate(' + now + 'deg)'
        });
      }
    });
  }

  $("img").click(function() {
    cDeg += 45;
    /*
    if (cDeg >= 360) {
      cDeg = 0;
    }
    */
    console.log(cDeg);
    animateRotate(this, cDeg);
  });
});

Found under: CSS rotation cross browser with jquery.animate()

A: It's better to use css transition and simply toggleClass on button click:

$(".rotate").on("click", function(e) {
  $(".image").toggleClass("rotate");
})
$(".rotateX").on("click", function(e) {
  $(".image").toggleClass("rotateX");
})
img {
  display: block;
  margin: 20px;
  transition: transform 1s ease;
}

img.rotate {
  transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
}

img.rotateX {
  transform: rotateX(180deg) scaleX(-1);
  -webkit-transform: rotateX(180deg) scaleX(-1);
  -ms-transform: rotateX(180deg) scaleX(-1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="rotate">
Rotate
</button>
<button class="rotateX">
RotateX
</button>
<img class="image" src="http://lorempixel.com/400/200/" alt="" />


text:
Q: Twilio Opt-in/Opt-out tracking How do I get all the phone numbers which have Opted-in or Opted-out via text to the short code? IS there any Twilio API which I can use? I need to import those numbers into SQL database.
Customers can text "Join" to short code and get opted-in and I need a list of all the phone numbers which are Opted-in and similarly customers can text STOP to opt-out. I am looking for a way to get all the numbers which have opted-in and opted-out. I am new to Twilio. Please help.
Thanks

A: You can track these events using your code. Twilio forwards all opt-in/opt-out to you backend application, the destination you have the Webhook configured for. You can do this with standard opt-outs or advanced opt-out. Currently, there is no API to view the Twilio maintained opt-in/opt-out list.
Twilio support for opt-out keywords (SMS STOP filtering)
Customize opt-in and opt-out flows with Advanced Opt-Out


text:
Q: Figure out if Carat is in TextBox Is there any way to tell if the Mouse Carat is in a TextBox? Basically, if the carat is in the TextBox, you can start typing and the text will appear in the TextBox but if the Carat is not in the TextBox, when you start typing, nothing will happen, Is it possible to tell if it is or isn't in the TextBox?
Sort of like what the TextBox where you put your password in when you log in to your computer.
Sorry if this sounds confusing, it is sort of confusing to me.

A: You can check if the Textbox has focus by using the Control.ContainsFocus property.


text:
Q: Customizing Glass I need to customize Glass such that only the kernel and the window manager are present. In addition, when Glass boots, it needs to simply bring up our Android application.
Fortunately, Google team has graciously provided basic instructions for rooting Glass at https://developers.google.com/glass/tools-downloads/system. Understandably, rooting Glass will void your warranty. This is okay for us.
There are also instructions on how to build the kernel for Glass.
However, for our needs, I am thinking I don't even need to worry about rebuilding the kernel. I think all I need is to just modify init.rc, comment out the loading of unneeded application and add my application to the list. I am assuming there is an init.rc file as Android is based on Linux.
I would appreciate it if someone can point me in the right direction. Is modifying init.rc good enough or something else is required? Or, do I really have to build a custom kernel? Regards.

A: One good way to start around would be to check the tutorials about how to extract and repack system.img file.
https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&es_th=1&ie=UTF-8#q=android%20extract%20system.img
Options in this search would point out to a certain direction.
This will let you customize your own Glass image, remove/add system APKs, etc.
Doing this, you should also be able to remove the GlassHome.apk to remove the default launcher.
And because you want specific features when the Glass boots you can try to add your own launcher, you can follow this guide in order to achieve this:
Hope this would Help!!


text:
Q: IndexError: index 1 is out of bounds for axis 0 with size 1 while storing the result as a tuple in python I want to store the result in a data-frame in form of a tuple with (predictions, probabilities) in each tags. I can print fine the result at the line:
print(eachPrediction , " : " , eachProbability)
I'm getting the error for the line :
    Error message:
        temprow[i+1] = (predictions[i],probabilities[i])
    IndexError: index 1 is out of bounds for axis 0 with size 1
from imageai.Prediction import ImagePrediction
import os
import pandas as pd
import numpy as np
from PIL import Image

execution_path = os.getcwd()
pred_array = np.empty((0,6),dtype=object)

TEST_PATH = '/home/guest/Documents/Aikomi'
for img in os.listdir(TEST_PATH):
    if img.endswith('.jpg'):
        image = Image.open(os.path.join(TEST_PATH, img))
        image = image.convert("RGB")
        image = np.array(image, dtype=np.uint8)
        prediction = ImagePrediction()
        prediction.setModelTypeAsDenseNet()
        prediction.setModelPath(os.path.join(execution_path, "DenseNet.h5"))
        prediction.loadModel()
        predictions, probabilities = prediction.predictImage(os.path.join(TEST_PATH, img), result_count=5 )
        temprow = np.zeros((1,pred_array.shape[1]),dtype=object)
        temprow[0] = img
        for i in range(len(predictions)):
            temprow[i+1] = (predictions[i],probabilities[i])
        for eachPrediction, eachProbability in zip(predictions, probabilities):
            #print(eachPrediction , " : " , eachProbability)
            pred_array = np.append(pred_array,temprow,axis=0)
df = pd.DataFrame(data=pred_array,columns=['File_name','Tag_1','Tag_2','Tag_3','Tag_4','Tag_5'])
print(df)
df.to_csv('Image_tags.csv')

A: I have got a fix with the dimension mismatch.
pred_array = np.empty((0,6),dtype=object)
for img in os.listdir(TEST_PATH):
    if img.endswith('.jpg'):
        image = Image.open(os.path.join(TEST_PATH, img))
        image = image.convert("RGB")
        image = np.array(image, dtype=np.uint8)
        predictions, probabilities = prediction.predictImage(os.path.join(TEST_PATH, img), result_count=5)
        temprow = np.zeros((1,pred_array.shape[1]),dtype=object)
        temprow[0,0] = img
        for i in range(len(predictions)):
            temprow[0,i+1] = predictions[i]
        pred_array = np.append(pred_array,temprow,axis=0)

A: you have defined:
pred_array = np.empty((0,6),dtype=object)

it should be:
pred_array = np.empty((1,6),dtype=object)

zero means no axis, but it show as (0, 6) if you get pred_array.shape, which maybe misleading a bit.
and :
temprow = np.zeros((1,pred_array.shape[1]),dtype=object)

later you are indexing:
 for i in range(len(predictions)):
        temprow[i+1] = (predictions[i],probabilities[i])

temprow only has one index room to access for it's first axis since you have defined it's shape as (1, pred_array,shape[1]). numpy arrays do not have dynamic size allocation property to index at out range and it be made for you.


text:
Q: How does neural network learn feature functions? I was wondering if there is some intuitive way of thinking about the fact that neural networks learn the feature function $\phi(x_i)$ along with the feature weights $\theta$. Because this is really the point of using a net: they will find the relevant feature functions and tune their weights to obtain decent results. But when you're training a net you're only updating the weights matrices $W^{(l)}$ of the net.
I was thus wondering what exactly is referred (in terms of maths) when we say that the neural net is learning the feature function? The goal would be to somehow compare this intuition with the standard regression $ \hat{y}_i = \theta^T \phi(x_i)$. Where we have to define ourselves the feature function and regression techniques take care of finding the appropriate weights $\theta$.

A:
what exactly is referred (in terms of maths) when we say that the neural net is learning the feature function?

This is about representation learning. Deeper layers act as learning  entities for new unknown representations:

A central idea, referred to as greedy layerwise unsupervised
pre-training, was to learn a hierarchy of features one level at a
time, using unsupervised feature learning to learn a new
transformation at each level to be composed with the previously
learned transformations; essentially, each iteration of unsupervised
feature learning adds one layer of weights to a deep neural network.[*]

[*] Representation Learning: A Review and New Perspectives, Bengio et. al 2014, pdf.


text:
Q: Difference between SQL Server Login Account & Database Users? What is the difference between SQL Server logins and database users, and how can I use the    users inside my code for the privileges given to each user since the connection string uses the login only ?

A: A SQL Server login stores the informations to authenticate a user at server level.
After a user is authenticated, you might want to authorize him to use some of the databases the server hosts. You do that by mapping the login to a database user or in other word grant that login access to one or more databases.
What privileges do you want to set by code?
For example you can use SMO to administer your server or you can use Sql Statements like GRANT to change permissions.

A: I think this is a very useful question. Just to add my two cents: from msdn:
A login is a security principal, or an entity that can be authenticated by a secure system. Users need a login to connect to SQL Server. You can create a login based on a Windows principal (such as a domain user or a Windows domain group) or you can create a login that is not based on a Windows principal (such as an SQL Server login).
Note Note
To use SQL Server Authentication, the Database Engine must use mixed mode authentication. For more information, see Choose an Authentication Mode.
As a security principal, permissions can be granted to logins. The scope of a login is the whole Database Engine. To connect to a specific database on the instance of SQL Server, a login must be mapped to a database user. Permissions inside the database are granted and denied to the database user, not the login. Permissions that have the scope of the whole instance of SQL Server (for example, the CREATE ENDPOINT permission) can be granted to a login.
http://msdn.microsoft.com/en-us/library/aa337562.aspx#Background


text:
Q: Relationship between correlation of x vs. x+y and y vs. x+y I am working with some data in which two component scores X and Y are added together to make a total score X + Y. Is there any known relationship between the correlation R for X vs. X + Y and the R for Y vs. X + Y?
I've played around a little bit, but I am not seeing anything except in the case where X and Y themselves are uncorrelated. (In that case, the R2 values sum to 1.)
ETA: With all due respect, this question is NOT a duplicate of the one already cited. I made abundantly clear that I am not talking about cases in which the variables have no correlation, which is a key feature of the other question. I am asking a much broader question.


text:
Q: jquery mobile,cordova not working on iphone simulator I am new to ios phonegap . I started to cordova based application.My code does not show header and footer in emulator but works fine in browser. My index.html code is something like this.
<!doctype html>

    <title>JQM Sample</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta charset="utf-8">

    <link href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" rel="stylesheet" type="text/css" />

Header

Welcome

...

Footer

Am i missing something?
My ios version is 5.1.I have also added URL in Cordova.plist,still not working.

A: You need to add the remote URL code.jquery.com to the whitelist. If you expect your app to be used offline it is best to include the JS files as part of your app and use the local copy.
To add the URL to the whitelist edit the Cordova.plist file in your project and add code.jquery.com under ExternalHosts.

A: What's the version of IOS did you try on?
It's well known and documented by JQM team, that old platforms like IOS 4.3 do not support fixed toolbars positioning out of the box. You'll need to polyfill.
Just look at their docs: http://jquerymobile.com/demos/1.1.0/docs/toolbars/bars-fixed.html
Also don't forget to update *.plist as already mentioned in this topic.


text:
Q: How do you debug a request How do you debug a request?
Like the code below.
This is javascript.  And I am running through firebug.
But I never get anything on
 if (status == google.maps.GeocoderStatus.OK)

To check the status.
So the call goes out.  And nothing back.
How can someone debug this?  Is there some other way to get an error code?
thank you
function codeAddress() {
  geocoder = new google.maps.Geocoder();
  service = new google.maps.DistanceMatrixService();
    var address = document.getElementById("storeAddress").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        storeGeo = results[0].geometry.location;

      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

A: You can check with wireshark if the request is send to the interface or you can append the GET-URL string XESSION_XDEBUG_START to the url.


text:
Q: How to get the viewport size excluding scrollbars in pure JavaScript? I am now rewriting some old codes to work with modern browsers. One problem is persistent to me: the viewport size. I wish to put a DIV element in the center but with the scrollbar, it won't be right. Also, I wish to put a button near the right border but the scrollbar is rendered over my button.
I am using plain simple...
window.innerWidth

... to get the width, but won't consider vertical scrollbar, if there is. I have looked inside MDN documentation for something to give me the right number...
document.body.clientWidth (give a smaller number, about twice width of scrollbar)

Also this property has a special behavior for body, but to me is just wrong.
I did't find a way to get the size of each scrollbar, so I am now out of ideas.
I know this is asked a lot, as here, but I wish to go to the bottom of this subject thinking in new browsers and latest ECMAScript definitions, with some retro compatibility.

A: I did a webpage to play with those properties and it's values. It seems the only way to get what is needed in this case, the right green box positioning, is thought empiricism. So this is the code:
<!DOCTYPE html>

<meta charset="UTF-8">

<title>Window Size Test</title>

Window Size Test

This is the result:

Note that I did the green box with half size to not cover the other boxes. Also, might be a good idea to have an invisible box fixed at the corner to get the actual window size when needed, thought is what I will do.
Please test and share comments, I am still worry if this will work with any browsers and have some retro compatibility.


text:
Q: How is best practise using AMD and RequireJS, when namespacing an entire file I am new to AMD, and I've been wondering about how one can have a file like this, mixed functions and logic:
function abc() {
    ....
}

function def() {
    ....
}

function ghi() {
    ....
}

var something = { ... }

if (abc === something) {
    for(var i = 1; i < 10000000; i++) {
       ...
    }
}

... And so it goes on for 1200 lines or so.

So not everything in this file is inside functions, there is also just logic being executed outside functions.
How can I include a file like this in another module, and make sure all these functions and what not are NOT in the global namespace/scoped in AMD style?

A: You have to wrap entire file contents into a module definition:
define(function () {
function abc() {
    // ....
}

function def() {
    // ....
}

function ghi() {
    // ....
}

var something = { /* ... */ }

if (abc === something) {
    for(var i = 1; i < 10000000; i++) {
       // ...
    }
}

// ... And so it goes on for 1200 lines or so.
});

Then in the other module just require the thing from the above :) But none of those functions will be available to the module which needs the wrapped code. But that can also be sorted, just return them in the object literal at the end of the wrapped file


text:
Q: Send() using TCP is not sending the whole array I am trying to send a char array to a server and I am not able to send the whole thing. I discovered that I am not receiving  that it is sending only the first four packets.
This is the data I want to send in one go.
char msg1[]={0xff,0xfd,0x03,0xff,0xfb,0x18,0xff,0xfb,0x1f,0xff,0xfb,0x20,0xff,0xfb,0x21,0xff,0xfb,0x22,0xff,0xfb,0x27,0xff,0xfd,0x05,0xff,0xfb,0x23};

This is the function I am using to check whether all the bytes have been send or not. and if not. send the rest.
int send_all(int s,char *buf,int *len)
{
    int total=0; //total bytes sent
    int byteslft= *len; //bytes left to be sent
    int n; //value returned by send()

    while(total<*len)
    {
        n=send(s,(buf+total),byteslft,0);
        if(n== -1)
            break;

        total +=n; //total bytes sent will be in total
        byteslft -=n; //total bytes left to be sent is stored here
    }

    *len= total;
    return (n==-1)?-1:0;
}

And this how I am trying to send it
len=sizeof (*(arr+i)) ;
    if((numbytes=send_all(sockfd,(*(arr+i)),&len))==-1)
    {
        perror("send");
        continue;
    }

I have done the connect(),socket(), etc. steps before this just to be clear.
And this is how I've initialized the array of the pointers to the msg array.
char *arr[]={msg1,msg2,msg3,msg4....};

When I debug my program, I see that it is only sending
ff fd 03 ff //message stops sending here

And that's why I'm not getting the required response from the server.

A: The expression *(arr + i) is not an actual array, but a pointer to an array. This means that the sizeof operation will return the size of the pointer (which is 32 bits, i.e. four bytes on a 32-bit operating system) and not what it points to.
You can only use sizeof to get the size of an array if you have the actual array, not on pointers.


text:
Q: Why won't my function tally up a score properly? My question is simple, I have a few lines of code that should be tallying up my total score when the right input is selected. However, I can't seem to get the score to be anything but 0. Here's the code:

$(document).ready(main);

function main(){
    $("input").hide();
    $("h1").on('click', function(){
        $('h1').css("background-color", "red")

    });

    var questions = [
        {
            question: "What is the capital of Washington?", choices: ["Salem", "Seattle",
            "Helena", "Olympia"], correctanswer: "Olympia"
        },
        {
            question: "How many countries are in Europe?", choices: ["15", "46", "27",
            "51"], correctanswer: "51"
        },

        {
            question: "What is the population of Mexico City?", choices: ["3.3 Million", "800 Thousand", "15.1 Million",
            "8.9 Million"], correctanswer: "8.9 Million"
        },

        {
            question: "Who is the current leader of Russia?", choices: ["Boris Yelstin", "Dmitry Medvedev",
            "Nikolai Bulganin", "Vladimir Putin"], correctanswer: "Vladimir Putin"
        },

        {
            question: "How large is the state of California?", choices: ["85,115 square miles", "130,919 square miles",
            "215,355 sqaure miles", "163,696 square miles"], correctanswer: "163,696 square miles"
        }
    ];

    $("#start").on('click', function() {
        $("#start").hide();
        $("input").show();
        quiz();

    } );

    total=0;
    number=0;

    function quiz(){
        $("#question").text(questions[number].question);
        $("#answer1").text(questions[number].choices[0]);
        $("#answer2").text(questions[number].choices[1]);
        $("#answer3").text(questions[number].choices[2]);
        $("#answer4").text(questions[number].choices[3]);
    }

 $("#submit").on('click', function(){
     var chosen;
     chosen = ($("input[name='choice']:checked").val());
     if (chosen == questions[number].correctanswer) {
         total++;
         $("#score").text("Score: " + total);
     } else {
         $("#score").text("Score: " + total);
     }
     number++;
     quiz();

 });

}
.btns{height:50px; width:80px; background-color:blue;
}

#answers{
    display: inline-block;
}

Simple Quiz

    <input type="radio"  name="choice" value="1">

    <input type="radio"  name="choice" value="2">

    <input type="radio"  name="choice" value="3">

    <input type="radio"  name="choice" value="4">

    <button id="start">Start</button>
    <button id="submit">Submit</button>

So it's pretty simple as far as code goes and to me it looks like it should work, but clearly not so any help is appreciated. Thanks! Here's the git repository.

A: The quiz() function updates the text of each radio button, but not its value. So chosen will just be a number from 1 to 4, and won't match the .correctanswer property. Use the value as an index into the choices array and compare with that. I've changed the values of the radio buttons to start at 0, to match array indexing.
Another way to fix it would be to change the correctanswer property to just contain the index of the correct answer, rather than its text.

$(document).ready(main);

function main() {
  $("input").hide();
  $("h1").on('click', function() {
    $('h1').css("background-color", "red")

  });

  var questions = [{
      question: "What is the capital of Washington?",
      choices: ["Salem", "Seattle", "Helena", "Olympia"],
      correctanswer: "Olympia"
    }, {
      question: "How many countries are in Europe?",
      choices: ["15", "46", "27", "51"],
      correctanswer: "51"
    },

    {
      question: "What is the population of Mexico City?",
      choices: ["3.3 Million", "800 Thousand", "15.1 Million", "8.9 Million"],
      correctanswer: "8.9 Million"
    },

    {
      question: "Who is the current leader of Russia?",
      choices: ["Boris Yelstin", "Dmitry Medvedev", "Nikolai Bulganin", "Vladimir Putin"],
      correctanswer: "Vladimir Putin"
    },

    {
      question: "How large is the state of California?",
      choices: ["85,115 square miles", "130,919 square miles", "215,355 sqaure miles", "163,696 square miles"],
      correctanswer: "163,696 square miles"
    }
  ];

  $("#start").on('click', function() {
    $("#start").hide();
    $("input").show();
    quiz();
  });

  total = 0;
  number = 0;

  function quiz() {
    $("#question").text(questions[number].question);
    $("#answer1").text(questions[number].choices[0]);
    $("#answer2").text(questions[number].choices[1]);
    $("#answer3").text(questions[number].choices[2]);
    $("#answer4").text(questions[number].choices[3]);
    $("input[name='choice']:checked").prop("checked", false); // Clear the previous selection
  }

  $("#submit").on('click', function() {
    var chosen;
    chosen = questions[number].choices[$("input[name='choice']:checked").val()];
    if (chosen == questions[number].correctanswer) {
      total++;
      $("#score").text("Score: " + total);
    } else {
      $("#score").text("Score: " + total);
    }
    number++;
    quiz();
  });
}
#btns {
  height: 50px;
  width: 80px;
  background-color: blue;
}
#answers {
  display: inline-block;
}

Simple Quiz

  <input type="radio" name="choice" value="0">

  <input type="radio" name="choice" value="1">

  <input type="radio" name="choice" value="2">

  <input type="radio" name="choice" value="3">

  <button id="start">Start</button>
  <button id="submit">Submit</button>

A: The value attributes of your radio buttons are 1..4, and so this line evaluates to 1..4:
chosen = ($("input[name='choice']:checked").val());

You are then comparing 1..4 to a string value, such as Olympia, from your array:
if (chosen == questions[number].correctanswer) {

The integer is never equal to the string and so this condition never evaluates to true to increment your counter:
if (chosen == questions[number].correctanswer) {
total++;

To compare the string value to the string value (instead of its index) you want this:
chosen = ($("input[name='choice']:checked").val());
chosen = chosen - 1;
chosen = questions[number].choices[chosen];

Here is a jsfiddle that shows it working this way:
https://jsfiddle.net/79rfjz04/


text:
Q: Why does my CalcOddIntegers method always return zero? This method is supposed to take user input for the length of the array, and then the integers that are part of the array, and return the amount of odd numbers in the array. However, it always returns zero for the count of odd integers and I am unsure as to why. The scanner is declared outside of this method.

        System.out.print("Enter length of sequence\n");
        int length = console.nextInt();
        int[] array = new int[length];
        System.out.print("Enter the sequence: \n");
        int count = 0;
        int i = 0;
        for (i = 0; i < length; i++) {
            array[i] = console.nextInt();
        }
        for (i = 0; i < length -1; i++); {
            if (array[i] % 2 != 0) {
                count++;
            }
        }
        System.out.printf("The count of odd integers in the sequence is %d\n", count);
    }

Example of console:
2. Calculate the factorial of a given number
3. Calculate the amount of odd integers in a given sequence
4. Display the leftmost digit of a given number
5. Calculate the greatest common divisor of two given integers
6. Quit

3
Enter length of sequence
4
Enter the sequence:
1
2
3
4
The count of odd integers in the sequence is 0

I have tried experimenting with the for statements with different variables to see if something was conflicting but nothing has worked.

A: After the second for there is a semicolon that shouldn't be there. The syntax is technically correct however, there is nothing to execute so the block that checks for odd numbers is going to be executed only once. I suggest using a debugger that will help you troubleshoot issues easier.

A: Remove the semi-colon (;) in the line

for (i = 0; i < length -1; i++);
the semi-colon terminates the loop hence an assumption that your line does nothing.


text:
Q: conditional string with ternary operator not working on multi language string - javascript nodejs Desired result:
if variable cityName present -------------> " :أوقات الصلاة في كراتشي"
if variable cityName is not present -----> " :أوقات الصلاة"

what I am getting:
${(cityName) ? " :" + cityName + "في "  : ":"}وقت الصلاة\n

" :karachiفي وقت الصلاة↵"

وقت الصلاة${(cityName) ? (" :" +cityName+" في ") : (":")}\n;

"وقت الصلاة :karachi في ↵"

may be this is the problem with arabic language because even I remove the english latters just for testing it doesnt work:
وقت الصلاة${(cityName) ? (" :في كراتشي") : (":")}\n;

"وقت الصلاة :في كراتشي↵"

${(cityName) ? (" :في كراتشي") : (":")} وقت الصلاة\n;

" :في كراتشي وقت الصلاة↵"

no matter What I do I never get correct result, what I am looking for is how do I get correct result according to my need, in addition if anyone can tell me what is the science of multilanguage (of different starting sides such as english from left and arabic from right) in string  would be thankful .
I am using this approach in english from years it works fine but with arabic it is not working

A: The best fix for this when displaying Arabic text that has a non-Arabic character at the end is to include the Unicode RTL code after the non-Arabic character.
This happens when placing Neutral Characters such as punctuation between different directional text runs. For example, the Arabic Unicode Table does not have the equivalent codes for the characters ! @ # $ % * : &
When you add any of these Latin characters to the end of Arabic text, that character positions itself correctly to the right of the Arabic text (i.e. before the Arabic text reading from right to left); this is incorrect according to the direction of the Arabic text.
By adding the Unicode for RTL "\u200F" after the Neutral Latin Char; you instruct that the Latin char maintains RTL as the remaining text; this will fix the problem. This works irrespective of the original direction of the sentence be it RTL or LTR because the Arabic characters always take the RTL direction.
This also allows combining RTL and LTR text in the same sentence.
Here is an example to (I hope) will fix this for you:
Of course, this only to give you an idea. Forget about how I am concatenating the strings; it is only for explanation.
You can adapt it for the ternary operator easily.

function showPrayerTime(city,Time) {
  let RTL = "\u200F";
  let prefix = "أوقات الصلاة";
  let prefix2 = prefix + " " + "في" + " ";

  switch (city) {

    case "KHI" :
      result = prefix2 + "كراتشي" + ":" + RTL;
      break;
      //---------------------
      case "DOH" :
      result = prefix2 + "الدوحة" + ":" + RTL;
      break;
      //---------------------
    default:
     result = prefix + ":" + RTL;

  }

  return result

}

console.log(showPrayerTime("KHI"));
console.log(showPrayerTime("DOH"));
console.log(showPrayerTime(""));

You can read more about it the RTL Unicode here: https://www.w3.org/TR/WCAG20-TECHS/H34.html
And using the Ternary Operator example:

let cityName = "كراتشي";
let prefix = "وقت الصلاة";
let suffix = ":" + "\u200F";

//==== example 1
let result = cityName ? prefix+" في "+cityName+suffix : prefix+suffix;
console.log(result)

//==== example 2
cityName = "";
result = cityName ? prefix+" في "+cityName+suffix : prefix+suffix;
console.log(result)

A: Your first line says ${(cityName) ? " :" + cityName + "في " : ":"}وقت الصلاة\n this is saying that if cityName, then return everything between ? And : (without the quotes), not sure why you're adding ":" plus the city name again.
This is not an issue with Unicode letters, it's just the format.
Let's take an example with English letters. If cityname, return "new York", if not, return "nothing", so
${cityName ? "new York" : "nothing"}
But I'm guessing you want to return the actual value of city name somehow, but I can't read Arabic nor do I know where the original cityName variable was defined, do I can't help you there, but the format of the inline if statements is the condition, followed by a ?, Followed by the resulting expression that is returned if condition is met, followed by :, followed by expression that is returned if not


text:
Q: MALFORMED_ID- unable to resolve Image2

Image1

I am trying to create a Lead record and when I click submit I am getting this error. Dealer_locator_selection__c is account field lookup on lead. any inputs please?
you can find the code below link
wire function not working in LWC.
I tired doing this, still it did not resolve the issue
  @AuraEnabled(cacheable=true)
    public static String getDealerAccount(){
       Account dAcc =  [SELECT id FROM Account WHERE name='newAcc'];
        return String.valueOf(dAcc.id).subString(0, 15);
    }

A: As per my understanding,instead of fields.Dealer_Locator_Selection__c = JSON.stringify(this.dealerAcc.data)
Use
fields.Dealer_Locator_Selection__c = this.dealerAcc.data;

Because this is already string and once your are again stringify it. It will add quotes as well.


text:
Q: Base64 input check for Yara rules so I started using Yara rules,
I have a mysql database with files and their base64 encodes saved in a column.
Is there any way to input in Yara a base64 string without storing it in a file? if so, what is the command? If not, is there a way in Python?
This is what I tried to do:
rule string_exist{
    strings:
        $a = "just for use in the Virtual Mechanics tutorials. More text. And more" base64
    condition:
        $a
}

and then in cmd: yara64.exe -r manual_code.yar ..........long base64 string``
but recieved an error: could not open file
Thanks in advance.


text:
Q: Program prints -ve integers after 2147483647 I've recently started learning C. I have read that integer range of gcc is -214783648 to +2147483647.
Using GCC on CentOS.
I understood that it is 2^32 is splitted into two parts and 0.

*

*Is this a imposed restriction on the Compiler ? Any Advantages with this ? or my compiler is 32 Bit ? (As far as I know my computer is 64-Bit).

*If one one go above this limit, what should one do ?
Thanks in Advance

A: Sizing of integers is platform-specific. C standard does not say exactly how many bits an int must have, all it says is that an int must be at least 16-bit long. This is not a restriction on the compiler - rather, it is one of many compiler's property that define your platform.
The bit-ness of your platform does not have a direct impact on the size of the int on your platform. You can often use the same compiler to generate 32-bit and 64-bit code (with gcc, you can use flags -m32 or -m64), but the sizes of built-in types will not necessarily change.
If you need bigger range for your integers, you can use long long, which is guaranteed to have at least 64 bits. In addition, gcc supports 128-bit integer type __int128. If you need even more range, you can use an arbitrary precision math package.

A: It has to do with binary numbers and how many bits an integer data type has. Typically an integer is composed of 4 bytes = 32 bits and therefore an integer can store 2^32 values [0, 232 - 1] or [-214783648, 2147483647] for signed integers.
As far as I know the behavior if one goes out of the range is undefined. This is known as Integer overflow.
And here is a must read:  http://en.wikipedia.org/wiki/Binary_number


text:
Q: Select first input, but don't select type=hidden I want to focus the first input element that is not type=hidden. I've got this far but it will still attempt to focus hidden elements.
$('#content input:first').focus();

A: $('#content input:first').not(":hidden").focus();

A: Use the :visible selector:
$('#content input:visible:first').focus();

:visible docs:

Description: Selects all elements that are visible. Elements can be
  considered hidden for several reasons:

*

*They have a CSS display value of none.

*They are form elements with  type="hidden".

*Their width and height are explicitly set to 0.

*An ancestor element is hidden, so the element is not shown on the page.

If it's too much for you, use Attribute Not Equal Selector:
$('#content input[type!="hidden"]:first').focus();

Attribute Not Equal Selector docs:

Description: Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.

A: You will need to select the element filtering with its attribute and appearing first.
$("#content input[type!='hidden']:first").focus();


text:
Q: velocity templates files for localization I am adjusting messageSource to support multi language. I have some velocity templates files (.vm). I wonder how can I adjust message codes for these files.
Now I add message code for localization like this.
<spring:message code="user.name"/>

But I cannot try this for .vm files. How can I use this code for .vm files?
If possible, please let me know.
Thanks.


text:
Q: Can you avoid loading reusable components that another page already loaded them So I have a page (let's call it Page1) that use is loaded dynamically via React.lazy that uses several reusable components and another page (Page2) that uses some of those reusable components, this page being as well loaded dynamically.
My question would be, is there a way to prevent Page2 to load those reusable components again?
When I analyze the generated final bundle I see that both pages load the reusable components individually and I think ideally would be to just load them once and each new dynamically loaded page that uses those reusable components shouldn't fetch them again.

A: Reusable components as like simple components act as individual distinctive when used in different code files. so they will surely re-render again when used in other files.


text:
Q: Devexpress Winforms tileview substring text forecolor Is it possible to change the forecolor of substring in element text in GridControls's Tileview in devexpress winforms?
What's going to happen is I have a textbox and tileview
In event while textbox textchanged fire, the text matched in tileview's element text will be highlighted
The initial color of tileview's text will be blue and if its match with textbox's text it will be highlighted as gray.
See picture to check the illustration:
Is it possible? or will i need another component to attain this output?

A: As far I can see there is property group called Appearance (TileView.Appearance) and there you have property called ForeColor. Moreover, you can acces via code by calling
titleViewName.Appearance.ForeColor = <RGB value goes here>
Finally, there is possibility for dynamic customization via event ItemCustomize.
For further information please check official documentation and DevExpress forum. There already existis questions similiar to yours.

A: You can try to use HTML Text formating for displayed string:
Text = "This is some <color=red>red or <color=black><b>bold</b> text!"


text:
Q: Can't install programs from terminal - error "403 forbidden" I'm running Ubuntu 16.04. I can't install anything, not even update the basics. For example, if I run sudo apt install mysql-server, the output says:
Err:1 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 mysql-server-core-5.7 amd64 5.7.12-0ubuntu1.1
  403  Forbidden
E: Fail to obtain http://archive.ubuntu.com/ubuntu/pool/main/m/mysql-5.7/mysql-server-core-5.7_5.7.12-0ubuntu1.1_amd64.deb  403  Forbidden
Err:1 http//archive.ubuntu.com/ubuntu xenial-updates/main amd64 mysql-server-core-5.7 amd64 5.7.12-0ubuntu1.1
  403  Forbidden
Err:2 http//archive.ubuntu.com/ubuntu xenial-updates/main amd64 mysql-server-5.7 amd64 5.7.12-0ubuntu1.1
  403  Forbidden

Any ideas or help, please!!

A: I found the problem: it seems that permissions were misconfigured on my session, all I had to do was to open the terminal (Ctrl+Alt+F2) and change permissions with a chmod 0766 -R *.

A: I have this problem too, I can do without any problem with some ISPs, but some of them still have the problem.
A VPN connection solved my problem, you can use a proxy app to ride this problem.