text:
Q: Highlight only a few columns and cells within a row How could I edit my code to only highlight the row from column G:K instead of wasting memory and time highlighting the entire row?
With ActiveSheet    'set this worksheet properly!
    'lastrow = .cells(Rows.Count, 1).End(xlUp).Row
    lastrow = Range("K6500").End(xlUp).Row - 2
    For Each cell In .Range("K3:K" & lastrow)
        If cell = "Wrong Date" Then
          'With cell.EntireRow.Interior
           With cell.Range("G:K").Value.Interior.ColorIndex = 3

                Rows().Select
                .Pattern = xlSolid
                .PatternColorIndex = xlAutomatic
                .Color = 3937500
                .TintAndShade = 0
                .PatternTintAndShade = 0
            End With

My current code does not work as I've tried replacing With cell.EntireRow.Interior with With cell.Range("G:K").Value.Interior.ColorIndex = 3
Excuse me this is what I mean I am trying to do
Sub highlight_wrong_Date()

Dim Rng As Range, lCount As Long, lastrow As Long
Dim cell As Object

With ActiveSheet    'set this worksheet properly!

    lastrow = Range("K6500").End(xlUp).Row - 2
    For Each cell In .Range("K3:K" & lastrow)
        If cell = "Wrong Date" Then

            With cell.Range(.cells(cell.Row, "G"), .cells(cell.Row, "K"))
                Rows().Select
                .Pattern = xlSolid
                .PatternColorIndex = xlAutomatic
                .Color = 3937500
                .TintAndShade = 0
                .PatternTintAndShade = 0
            End With

        ElseIf cell = "Pass" Then
             With cell.Range(.cells(cell.Row, "G"), .cells(cell.Row, "K"))
                Rows().Select
                .Pattern = xlSolid
                .PatternColorIndex = xlAutomatic
                .Color = 61046
                .TintAndShade = 0
                .PatternTintAndShade = 0
            End With

        Else
            With cell.EntireRow.Interior
                Rows().Select
                .Pattern = xlNone
                .TintAndShade = 0
                .PatternTintAndShade = 0
            End With

        End If

     Next cell
End With

End Sub

But I receive an error saying the cell object does not support this. If a cell has either a value of "Wrong Date" or "Pass" within column O I want to highlight red or green respectively.
3rd Edit
Sub highlight_wrong_Date()

Dim Rng As Range, lCount As Long, lastrow As Long
Dim cell_value As Object

With ActiveSheet    'set this worksheet properly!

    lastrow = Range("K6500").End(xlUp).Row - 2
    For Each cell_value In .Range("K3:K" & lastrow)
        If cell_value = "Wrong Date" Then

            With .Range(.cells(cell.Row, "G"), .cells(cell.Row, "K"))
                'Rows().Select
                .Pattern = xlSolid
                .PatternColorIndex = xlAutomatic
                .Color = 3937500
                .TintAndShade = 0
                .PatternTintAndShade = 0
            End With

        ElseIf cell_value = "Pass" Then
             With .Range(.cells(cell.Row, "G"), .cells(cell.Row, "K"))
                'Rows().Select
                .Pattern = xlSolid
                .PatternColorIndex = xlAutomatic
                .Color = 61046
                .TintAndShade = 0
                .PatternTintAndShade = 0
            End With

        Else
            With cell.EntireRow.Interior
                Rows().Select
                .Pattern = xlNone
                .TintAndShade = 0
                .PatternTintAndShade = 0
            End With

        End If

     Next cell_value
End With

End Sub

A: Your references should be
With .Range("G" & cell.Row & ":K" & cell.Row)


text:
Q: Ansible playbook works from CLI but does not when executed from cron The title really says it all.  I have a small playbook that works just great from the command line. But from cron, I get a "Permission denied" error.
The target machine is set up as passwordless (i.e. I did a ssh-copy-id to it). My key does have a passphrase.  I am running the ssh-agent.
Here is the script called by cron:
#!/bin/bash
cd "${HOME}/raspberry-pi-iot-monitor/ansible"
ansible-playbook gather-telemetry.yaml -vvvv

Here is the cron entry:
╰─➤  crontab -l
*/2 * * * * ~/raspberry-pi-iot-monitor/shell/gather.sh > /tmp/gather.log 2>&1

And here is the error:

"Failed to connect to the host via ssh: OpenSSH_8.9p1 Ubuntu-3, OpenSSL 3.0.2 15 Mar 2022\r\ndebug1: Reading configuration data /home/tennis/.ssh/config\r\ndebug1: /home/tennis/.ssh/config line 1: Applying options for \r\ndebug1: /home/tennis/.ssh/config line 10: Ignored unknown option "usekeychain"\r\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: /etc/ssh/ssh_config line 19: include /etc/ssh/ssh_config.d/.conf matched no files\r\ndebug1: /etc/ssh/ssh_config line 21: Applying options for \r\ndebug1: auto-mux: Trying existing master\r\ndebug1: Control socket "/home/tennis/.ansible/cp/7dac895013" does not exist\r\ndebug2: resolving "cat-doorbell.local" port 22\r\ndebug3: resolve_host: lookup cat-doorbell.local:22\r\ndebug3: ssh_connect_direct: entering\r\ndebug1: Connecting to cat-doorbell.local [192.168.0.179] port 22.\r\ndebug3: set_sock_tos: set socket 3 IP_TOS 0x10\r\ndebug2: fd 3 setting O_NONBLOCK\r\ndebug1: fd 3 clearing O_NONBLOCK\r\ndebug1: Connection established.\r\ndebug3: timeout: 9995 ms remain after connect\r\ndebug1: identity file /home/tennis/.ssh/id_rsa type 0\r\ndebug1: identity file /home/tennis/.ssh/id_rsa-cert type -1\r\ndebug1: Local version string SSH-2.0-OpenSSH_8.9p1 Ubuntu-3\r\ndebug1: Remote protocol version 2.0, remote software version OpenSSH_8.4p1 Debian-5+deb11u1\r\ndebug1: compat_banner: match: OpenSSH_8.4p1 Debian-5+deb11u1 pat OpenSSH compat 0x04000000\r\ndebug2: fd 3 setting O_NONBLOCK\r\ndebug1: Authenticating to cat-doorbell.local:22 as 'tennis'\r\ndebug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts: No such file or directory\r\ndebug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts2: No such file or directory\r\ndebug3: order_hostkeyalgs: no algorithms matched; accept original\r\ndebug3: send packet: type 20\r\ndebug1: SSH2_MSG_KEXINIT sent\r\ndebug3: receive packet: type 20\r\ndebug1: SSH2_MSG_KEXINIT received\r\ndebug2: local client KEXINIT proposal\r\ndebug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,sntrup761x25519-sha512@openssh.com,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,ext-info-c\r\ndebug2: host key algorithms: ssh-ed25519-cert-v01@openssh.com,ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,sk-ecdsa-sha2-nistp256-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,ssh-ed25519,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,sk-ssh-ed25519@openssh.com,sk-ecdsa-sha2-nistp256@openssh.com,rsa-sha2-512,rsa-sha2-256\r\ndebug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com\r\ndebug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com\r\ndebug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1\r\ndebug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1\r\ndebug2: compression ctos: zlib@openssh.com,zlib,none\r\ndebug2: compression stoc: zlib@openssh.com,zlib,none\r\ndebug2: languages ctos: \r\ndebug2: languages stoc: \r\ndebug2: first_kex_follows 0 \r\ndebug2: reserved 0 \r\ndebug2: peer server KEXINIT proposal\r\ndebug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256\r\ndebug2: host key algorithms: rsa-sha2-512,rsa-sha2-256,ssh-rsa,ecdsa-sha2-nistp256,ssh-ed25519\r\ndebug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com\r\ndebug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com\r\ndebug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1\r\ndebug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1\r\ndebug2: compression ctos: none,zlib@openssh.com\r\ndebug2: compression stoc: none,zlib@openssh.com\r\ndebug2: languages ctos: \r\ndebug2: languages stoc: \r\ndebug2: first_kex_follows 0 \r\ndebug2: reserved 0 \r\ndebug1: kex: algorithm: curve25519-sha256\r\ndebug1: kex: host key algorithm: ssh-ed25519\r\ndebug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC:  compression: zlib@openssh.com\r\ndebug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC:  compression: zlib@openssh.com\r\ndebug3: send packet: type 30\r\ndebug1: expecting SSH2_MSG_KEX_ECDH_REPLY\r\ndebug3: receive packet: type 31\r\ndebug1: SSH2_MSG_KEX_ECDH_REPLY received\r\ndebug1: Server host key: ssh-ed25519 SHA256:b3o1At5wRZ9muqjPIQ/O/bmuYYDUl/1yzaogibfGmUU\r\ndebug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts: No such file or directory\r\ndebug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts2: No such file or directory\r\nWarning: Permanently added 'cat-doorbell.local' (ED25519) to the list of known hosts.\r\ndebug3: send packet: type 21\r\ndebug2: ssh_set_newkeys: mode 1\r\ndebug1: rekey out after 134217728 blocks\r\ndebug1: SSH2_MSG_NEWKEYS sent\r\ndebug1: expecting SSH2_MSG_NEWKEYS\r\ndebug3: receive packet: type 21\r\ndebug1: SSH2_MSG_NEWKEYS received\r\ndebug2: ssh_set_newkeys: mode 0\r\ndebug1: rekey in after 134217728 blocks\r\ndebug1: Will attempt key: /home/tennis/.ssh/id_rsa RSA SHA256:xtX0cUMBg1J1E7AVt+6wbRRVITwmM3eqmniYfqtqhO4 explicit\r\ndebug2: pubkey_prepare: done\r\ndebug3: send packet: type 5\r\ndebug3: receive packet: type 7\r\ndebug1: SSH2_MSG_EXT_INFO received\r\ndebug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,sk-ssh-ed25519@openssh.com,ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,sk-ecdsa-sha2-nistp256@openssh.com,webauthn-sk-ecdsa-sha2-nistp256@openssh.com>\r\ndebug3: receive packet: type 6\r\ndebug2: service_accept: ssh-userauth\r\ndebug1: SSH2_MSG_SERVICE_ACCEPT received\r\ndebug3: send packet: type 50\r\ndebug3: receive packet: type 51\r\ndebug1: Authentications that can continue: publickey,password\r\ndebug3: start over, passed a different list publickey,password\r\ndebug3: preferred gssapi-with-mic,gssapi-keyex,hostbased,publickey\r\ndebug3: authmethod_lookup publickey\r\ndebug3: remaining preferred: ,gssapi-keyex,hostbased,publickey\r\ndebug3: authmethod_is_enabled publickey\r\ndebug1: Next authentication method: publickey\r\ndebug1: Offering public key: /home/tennis/.ssh/id_rsa RSA SHA256:xtX0cUMBg1J1E7AVt+6wbRRVITwmM3eqmniYfqtqhO4 explicit\r\ndebug3: send packet: type 50\r\ndebug2: we sent a publickey packet, wait for reply\r\ndebug3: receive packet: type 60\r\ndebug1: Server accepts key: /home/tennis/.ssh/id_rsa RSA SHA256:xtX0cUMBg1J1E7AVt+6wbRRVITwmM3eqmniYfqtqhO4 explicit\r\ndebug3: sign_and_send_pubkey: using publickey with RSA SHA256:xtX0cUMBg1J1E7AVt+6wbRRVITwmM3eqmniYfqtqhO4\r\ndebug3: sign_and_send_pubkey: signing using rsa-sha2-512 SHA256:xtX0cUMBg1J1E7AVt+6wbRRVITwmM3eqmniYfqtqhO4\r\ndebug1: read_passphrase: can't open /dev/tty: No such device or address\r\ndebug2: no passphrase given, try next key\r\ndebug2: we did not send a packet, disable method\r\ndebug1: No more authentication methods to try.\r\ntennis@cat-doorbell.local: Permission denied (publickey,password)."

Does anyone have any ideas?
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to search any word and highlight it without using button? I have a search function that searches for all the words entered. the function will run if the search button is clicked, I have made a function for it in the code below. what I want is to do a search without using the button like live search.
any ideas for that? thanks

  <input type="text" id="search_text">
  <input type="button" value="search" id="search">

        @Html.ActionLink("Form User", "Index", "User", null, new { @class = "btn btn-primary" })
        @Html.ActionLink("Form Role", "Index", "Role", null, new { @class = "btn btn-primary" })
        @Html.ActionLink("Form Transaction", "Index", "Transaction", null, new { @class = "btn btn-primary" })

A: You can use onkeyup
It will look like
document.getElementById("search_text").onkeyup = function() {
  highlight_word(searchpara)
};

Working demo

document.addEventListener('DOMContentLoaded', function() {
  var searchpara = document.getElementById("inputText1").innerHTML;
  searchpara = searchpara.toString();
  document.getElementById("search_text").onkeyup = function() {
    highlight_word(searchpara)
  };
}, false);

function highlight_word(searchpara) {
  var text = document.getElementById("search_text").value;
  if (text) {
    var pattern = new RegExp("(" + text + ")", "gi");
    var new_text = searchpara.replace(pattern, "" + text + "");
    document.getElementById("inputText1").innerHTML = new_text;
  }
}
#search_para {
  color: grey;
}

.highlight {
  background-color: yellow;
}

  <input type="text" id="search_text">

    @Html.ActionLink("Form User", "Index", "User", null, new { @class = "btn btn-primary" }) @Html.ActionLink("Form Role", "Index", "Role", null, new { @class = "btn btn-primary" }) @Html.ActionLink("Form Transaction", "Index", "Transaction", null, new {
    @class = "btn btn-primary" })


text:
Q: How do I run UI tests on an Android App having a Flutter module integrated in it? I have an android app which, has a separate flutter module integrated within it.
So when my app launches, I initialise the flutter engine and load it in a Flutter fragment. So all my initial screens are rendered from the flutter module.
I have tried:
Appium's flutter driver-
APK installs and runs smoothly. But I am not able to access any flutter widgets. Not sure if this is happening because flutter is being run in a fragment as a module.
Flutter test driver-
Also, since the flutter module is integrated as a separate module, running flutter tests using the test driver doesn't work.
Is there any way to run the UI tests on the flutter code which is loaded into the android app as a module?
code structure is something like:
|- Android App
|-|-Flutter module
|-|-|- .Android module
|-|-|- .iOS module
|-|-Android modules

A: Ensure enableFlutterDriverExtension() is the first line in main.dart class
and add the key as Value key
Ex
                   InkWell(
                      child: Container(
                        key: ValueKey("click_container"),
                        margin: const EdgeInsets.only(top: 32.0, bottom: 30.0),
                        padding: const EdgeInsets.only(
                            top: 15.0, bottom: 15.0, left: 40.0, right: 40.0),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8.0),
                            color: Colors.white),
                        child: Text(
                         "Hello"
                        ),
                      )


text:
Q: Open a menu list from a button inside an iframe I have an asp:Button which I want to open a menu, I would like to load a custom menu depending on the pageID in a box to the left of the menu button. I have been testing this using a jQuery dialog so far which works for now but doesnt have the required functionality.
I want to create the menu dynamically so what would be useful is an iframe which loads the menu page in a box, to the left of the button.
This is what it should look like:

This is the code that I use to open the menu at the moment in a dialog, if it can be changed somehow to just load an iframe next to that button that would be great:
    var $dial2 = ""
    function openmenu(title, width, height, menuID) {
        $dial2 = $('

')
                       .html('')
                       .dialog({
                           autoOpen: false,
                           modal: true,
                           height: height,
                           width: width,
                           title: title
                       });
        $dial2.dialog('open');
    }

A: In the end I achieved this using the dialog shown above, but used the position property to join it to the edge of my button. I added a button inside the dialog to close it and also added a close event to any button that is shown within the menu.
function openmenu(width, height, menuID) {
    if ($dial2 == "") {
        $dial2 = $('

')
                       .html('')
                       .dialog({
                           autoOpen: false,
                           modal: false,
                           height: height,
                           width: width,
                           title: 'Menu',
                           draggable: false,
                           resizable: false,
                           position: {
                               my: 'top',
                               at: 'left-207',
                               of: $('#btnMenu')
                           },
                           dialogClass: "testdia"
                       });
        $dial2.dialog('open');

    }
    else {
        closemenu();
    }
    }


text:
Q: Is it possible to listen to a "style change" event? Is it possible to create an event listener in jQuery that can be bound to any style changes? For example, if I want to "do" something when an element changes dimensions, or any other changes in the style attribute I could do:
$('div').bind('style', function() {
    console.log($(this).css('height'));
});

$('div').height(100); // yields '100'

It would be really useful.
Any ideas?
UPDATE
Sorry for answering this myself, but I wrote a neat solution that might fit someone else:
(function() {
    var ev = new $.Event('style'),
        orig = $.fn.css;
    $.fn.css = function() {
        $(this).trigger(ev);
        return orig.apply(this, arguments);
    }
})();

This will temporary override the internal prototype.css method and the redefine it with a trigger at the end. So it works like this:
$('p').bind('style', function(e) {
    console.log( $(this).attr('style') );
});

$('p').width(100);
$('p').css('color','red');

A: As others have suggested, if you have control over whatever code is changing the style of the element you could fire a custom event when you change the element's height:
$('#blah').bind('height-changed',function(){...});
...
$('#blah').css({height:'100px'});
$('#blah').trigger('height-changed');

Otherwise, although pretty resource-intensive, you could set a timer to periodically check for changes to the element's height...

A: Things have moved on a bit since the question was asked - it is now possible to use a MutationObserver to detect changes in the 'style' attribute of an element, no jQuery required:
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutationRecord) {
        console.log('style changed!');
    });
});

var target = document.getElementById('myId');
observer.observe(target, { attributes : true, attributeFilter : ['style'] });

The argument that gets passed to the callback function is a MutationRecord object that lets you get hold of the old and new style values.
Support is good in modern browsers including IE 11+.

A: Since jQuery is open-source, I would guess that you could tweak the css function to call a function of your choice every time it is invoked (passing the jQuery object).  Of course, you'll want to scour the jQuery code to make sure there is nothing else it uses internally to set CSS properties.  Ideally, you'd want to write a separate plugin for jQuery so that it does not interfere with the jQuery library itself, but you'll have to decide whether or not that is feasible for your project.

A: The declaration of your event object has to be inside your new css function.  Otherwise the event can only be fired once.
(function() {
    orig = $.fn.css;
    $.fn.css = function() {
        var ev = new $.Event('style');
        orig.apply(this, arguments);
        $(this).trigger(ev);
    }
})();

A: Interesting question. The problem is that height() does not accept a callback, so you wouldn't be able to fire up a callback. Use either animate() or css() to set the height and then trigger the custom event in the callback. Here is an example using animate() , tested and works (demo), as a proof of concept :
$('#test').bind('style', function() {
    alert($(this).css('height'));
});

$('#test').animate({height: 100},function(){
$(this).trigger('style');
});

A: There is no inbuilt support for the style change event in jQuery or in java script. But jQuery supports to create custom event and listen to it but every time there is a change, you should have a way to trigger it on yourself. So it will not be a complete solution.

A: you can try Jquery plugin , it trigger events when css is change and its easy to use

http://meetselva.github.io/#gist-section-attrchangeExtension

 $([selector]).attrchange({
  trackValues: true,
  callback: function (e) {
    //console.log( '
Attribute ' + e.attributeName +' changed from ' + e.oldValue +' to ' + e.newValue +'
');
    //event.attributeName - Attribute Name
    //event.oldValue - Prev Value
    //event.newValue - New Value
  }
});

A: I think the best answer if from Mike in the case you can't launch your event because is not from your code. But I get some errors when I used it. So I write a new answer for show you the code that I use.
Extension
// Extends functionality of ".css()"
// This could be renamed if you'd like (i.e. "$.fn.cssWithListener = func ...")
(function() {
    orig = $.fn.css;
    $.fn.css = function() {
        var result = orig.apply(this, arguments);
        $(this).trigger('stylechanged');
        return result;
    }
})();

Usage
// Add listener
$('element').on('stylechanged', function () {
    console.log('css changed');
});

// Perform change
$('element').css('background', 'red');

I got error because var ev = new $.Event('style'); Something like style was not defined in HtmlDiv.. I removed it, and I launch now $(this).trigger("stylechanged"). Another problem was that Mike didn't return the resulto of $(css, ..) then It can make problems in some cases. So I get the result and return it. Now works ^^ In every css change include from some libs that I can't modify and trigger an event.

A: Just adding and formalizing @David 's solution from above:
Note that jQuery functions are chainable and return 'this' so that multiple invocations can be called one after the other (e.g $container.css("overflow", "hidden").css("outline", 0);).
So the improved code should be:
(function() {
    var ev = new $.Event('style'),
        orig = $.fn.css;
    $.fn.css = function() {
        var ret = orig.apply(this, arguments);
        $(this).trigger(ev);
        return ret; // must include this
    }
})();

A: How about jQuery cssHooks?
Maybe I do not understand the question, but what you are searching for is easily done with cssHooks, without changing css() function.
copy from documentation:
(function( $ ) {

// First, check to see if cssHooks are supported
if ( !$.cssHooks ) {
  // If not, output an error message
  throw( new Error( "jQuery 1.4.3 or above is required for this plugin to work" ) );
}

// Wrap in a document ready call, because jQuery writes
// cssHooks at this time and will blow away your functions
// if they exist.
$(function () {
  $.cssHooks[ "someCSSProp" ] = {
    get: function( elem, computed, extra ) {
      // Handle getting the CSS property
    },
    set: function( elem, value ) {
      // Handle setting the CSS value
    }
  };
});

})( jQuery );

https://api.jquery.com/jQuery.cssHooks/

A: I had the same problem, so I wrote this. It works rather well. Looks great if you mix it with some CSS transitions.
function toggle_visibility(id) {
   var e = document.getElementById("mjwelcome");
   if(e.style.height == '')
      e.style.height = '0px';
   else
      e.style.height = '';
}


text:
Q: "unrecognized selector sent to instance" with a class inheriting from NSAttributedString I have a class that inherits from NSAttributedString like this:
Text.h:
#import <Foundation/Foundation.h>

@interface Text : NSAttributedString

-(id) initWithString:(NSString*) text andFont:(NSFont*)font andLineHeight:(float) lineHeight andLetterSpacing:(float) letterSpacing;

@end

Text.m:
#import "Text.h"

#import <Cocoa/Cocoa.h>

@implementation Text

-(id) initWithString:(NSString*) text andFont:(NSFont*)font andLineHeight:(float) lineHeight andLetterSpacing:(float) letterSpacing
{
    NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setParagraphStyle: [NSParagraphStyle defaultParagraphStyle]];
    paragraphStyle.lineHeightMultiple = lineHeight;
    NSDictionary* attributes =
    @{
        NSFontAttributeName: font,
        NSKernAttributeName: @(letterSpacing),
        NSParagraphStyleAttributeName: paragraphStyle
    };
    self = [super initWithString:text attributes:attributes];
    return self;
}

@end

When I instantiate the class like this:
[[Text alloc] initWithString:@"Test" andFont:welcomeLabelFont andLineHeight:52 andLetterSpacing:0.0f]];

I get the following exception:
2017-07-17 17:21:15.771610+0300 Test[41403:10128169] -[Text initWithString:attributes:]: unrecognized selector sent to instance 0x600000000f70

The selector is available in the base class, event ctrl clicking it jumps to the NSAttributedText class. Can anyone point what am I doing wrong? The arguments are not nil pointers and the call seems legitimate. The only thing that seems weird is that the error has the class name Text not NSAttributedString.

A: Instad of a subclass, use an extension.  Like this
// in NSAttributedString+init.h
//
@interface NSAttributedString (Init)

-(instancetype) initWithString:(NSString*) text andFont:(NSFont*)font andLineHeight:(float) lineHeight andLetterSpacing:(float) letterSpacing;

@end

And then,  `
// in NSAttributedString+init.m
//
#import "NSAttributedString+init.h"

@implementation NSAttributedString (Init)

-(instancetype) initWithString:(NSString*) text andFont:(NSFont*)font andLineHeight:(float) lineHeight andLetterSpacing:(float) letterSpacing {
    // ...
}

Import that extension header wherever you want to use your convenience initializer.


text:
Q: Fetch xml with HttpWebRequest in Windows phone I'm using httpwebrequest to fetch some xml document, the code is as followed. When I call
HttpGetMethod http = new HttpGetMethod();
http.Request("http://sample.com/xml.php");

It works fine, then I use the
XDocument document = XDocument.Parse(xml);

                XElement element = document.Element("statuses");
                IEnumerable<XElement> statusesElements = element.Elements("status");

                foreach (var elx in statusesElements)
                {}

to parse the xml document. But sometimes there cause a exception, then I traced to find that the returned xml string contains the "e48"(I'm using the Fiddler to find the returned xml string), as shown in the pic. But I can't figure out the reason, it's so strange, what's the "e48"? Could anybody help?
Thanks.

public class HttpGetMethod
    {
        public WebCallBack CallBack;

        public void Request(string url)
        {
            var request = (HttpWebRequest)HttpWebRequest.Create(url);
            IAsyncResult result = null;

            result = (IAsyncResult)request.BeginGetResponse(ResponseCallback, request);
        }

        private void ResponseCallback(IAsyncResult result)
        {
            try
            {
                var request = (HttpWebRequest)result.AsyncState;
                var response = request.EndGetResponse(result);

                using (var stream = response.GetResponseStream())
                {
                    using (var reader = new StreamReader(stream))
                    {

                        if (CallBack != null)
                        {
                            var str = reader.ReadToEnd();
                            CallBack(str);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    CallBack(ex.ToString());
                });
            }
        }
    }

The debug output is:
A first chance exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
System.Xml.XmlException: '', hexadecimal value 0x0C, is an invalid character. Line 897, position 14.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.Throw(Int32 res, String resString, String[] args)
   at System.Xml.XmlTextReaderImpl.Throw(Int32 pos, Int32 res, String resString, String[] args)
   at System.Xml.XmlTextReaderImpl.ThrowInvalidChar(Char[] data, Int32 length, Int32 invCharPos)
   at System.Xml.XmlTextReaderImpl.ParseCDataOrComment(XmlNodeType type, Int32& outStartPos, Int32& outEndPos)
   at System.Xml.XmlTextReaderImpl.ParseCDataOrComment(XmlNodeType type)
   at System.Xml.XmlTextReaderImpl.ParseCData()
   at System.Xml.XmlTextReaderImpl.Parse

Here is the Raw response ih Fiddle:

A: IMO in this specific scenario use regex such as "^[^<]*" in
String result = Regex.Replace(htmlDocument, @"^[^<]*", System.String.Empty, RegexOptions.Singleline);

to remove the preceeding garbage chars


text:
Q: HTML/Ajax - Dynamically Displaying Data I'm working on creating an e-commerce site for a project, which requires reading data from a JSON file and then displaying it on screen, with the relevant information. I've been able to link the file to my HTML document and using the console, am able to list information such as the product name. My question is how would I go about putting this information onto the website and creating a new container per product?
I've created the layout for how these products should be displayed, with some dummy data included and created some CSS along with it. Could someone illustrate how I'd go about creating a new shopping-container for every product listed inside the JSON file, so every product that is inside the JSON file is produced as shown in the screenshot below?
Script  & Div Layout:

What We Offer.

Logitech G910 Orion Spectrum RGB Mechanical Gaming Keyboard - UK-Layout

Logitech 920-008017 G910 Orion Spectrum RGB Mechanical Gaming Keyboard - Black.

                £199.99

Layout of the JSON file
{
  "products" : [
    {
      "id" : "0",
      "name" : "Logitech G910 Orion Spectrum RGB Mechanical Gaming Keyboard - UK-Layout",
      "price" : "119.99",
      "category" : "0",
      "description" : "Logitech 920-008017 G910 Orion Spectrum RGB Mechanical Gaming Keyboard - Black.",
      "images" : [
        {
          "id" : "0",
          "src" : "images/00.jpg"
        },
        {
          "id" : "1",
          "src" : "images/01.jpg"
        },
        {
          "id" : "2",
          "src" : "images/02.jpg"
        }
      ]
    },

A: Try investigating tools such as Knockout, Angular or React. All offer great functionality to do as you desire and some more. All (if memory serves) offer the concept of components, which allows the replication of some HTML but with varying data appearing within it; i.e: what you want here.


text:
Q: How to connect flyback diodes on a h-bridge I'm using a SN754410NE h-bridge to drive two DC motors (4.5V each) with Arduino. After testing the circuit and the code, I made a standalone Arduino on a perma-proto breadboard.
My problem is that while the motors are running I see that led13 (the red led on the schematic) flashes periodically, while it's not supposed to (my code doesn't use that pin at all). After a while my atmel328 chip is kind of "erased" and in order to make my robot work again, I have to reprogram the chip.
So after looking around I found out that my h-bridge doesn't come with protection/flyback diodes (correct me if I'm wrong) and I need to add them myself. I have some 1N40001 diodes but am not sure how and where to connect them. Should I connect parallel to the motor leads? And if so, what the polarity should be given that the polarity can change (the motors run in both directions). Alternatively, should I connect the diodes serially to the wires connecting the Arduino digital pins to the driver input pins on the h-bridge?

A: From your breadboard diagram, one point stands out as missing: you have no bypass capacitors. The fast switching and inductive loads of the motor drivers will generate electromagnetic interference (EMI). Bypass capacitors are connected to between positive or negative rails and ground to stabilize the DC power rails and allow the currents causing EMI to be contained locally.
I would recommend using at least a 10uF-range electrolytic capacitor directly on the motor driver (H-bridge) power/ground pins, along with 0.1uF ceramic capacitors at the MCU and additionally at the motor driver. You don't want to put large capacitance on the motor driver output.
Additionally, you could put smaller ceramic capacitors (10nF to 0.1uF) directly on the motor, but these will slightly increase the power losses inside the motor driver. They are commonly connected as in this photo:

A: Add them in parallel to your motors, but in the reverse direction of the current flow. This allows the current still flowing through the motor (an inductor) to slowly dissipate back through the motor. This video gives a pretty good demonstration of the reasoning behind this.


text:
Q: Как преобразовать запись МФА в транскрипцию на русском языке? Товарищи, приветствую! Ищу информацию (или утилиту или кусок кода) преобразования записи в формате международного фонетического алфавита (IPA) перевести в русскую транскрипцию.
Пример: дано слово maɾɛ - надо получить марэ. Таблицу "МФА-русский" уже нагуглил, однако она не покрывает случаи, когда символ МФА отсутствует в русской фонетике (типа гортанного французского р). А также ещё один пример, даже не знаю как описать: если слово начинается с iẽ, побуквенная транскрипция даст иэ, хотя более правильно будет йе (то есть задача преобразования контекстно-зависимая, простым набором замен не обойдёшься).
ЗЫ. Метки (не могу создать сам): МФА, транскрипция, фонетика.
Язык кода не особо важен, но предпочтительно Python или C# =) Также если подскажете статью, в которой описаны правила подобной трансляции, я также буду благодарен.


text:
Q: How can I resolve or reject a promise based on a another promise? function process () {
 return new Promise((resolve, reject) => {

    //make sure module exists
    let module = modules[queueData.module];
    if (!module) reject('module not found: '+queueData.module);

    //make sure processor exists
    let processor = fileProcessors[module.type];
    if (!processor) reject('processor not found: '+module.type);

      return anotherPromiseFunction();
})
}

processFile().catch(e => console.error)

anotherPromiseFunction() returns a promise. normally inside a .then() I can return a promise to make the then() wait for that promise to finish, but how do I do it when creating a promise?
Am I supposed to do this:
    anotherPromiseFunction()
        .then(e=>resolve(e))
        .catch(e=>reject(e))

That seems wrong...

A: You likely do not need the new Promise. The cases for "module exists" and "processor exists" can be handled separately, and then you can just return the call to anotherPromiseFunction after them:
//make sure module exists
let module = modules[queueData.module];
if (!module) {
  return Promise.reject(new Error('module not found: '+queueData.module));
}

//make sure processor exists
let processor = fileProcessors[module.type];
if (!processor) {
  return Promise.reject(new Error('processor not found: '+module.type));
}

return anotherPromiseFunction();

If the enclosing function is an async function, you can just throw the errors instead:
async function run() {
  //make sure module exists
  let module = modules[queueData.module];
  if (!module) {
    throw new Error('module not found: '+queueData.module);
  }

  //make sure processor exists
  let processor = fileProcessors[module.type];
  if (!processor) {
    throw new Error('processor not found: '+module.type);
  }

  return anotherPromiseFunction();
}


text:
Q: How to detect mouse clicks inside nested buttons in pygame I'm trying to create a GUI that displays some buttons when you click a button. However, I cannot figure out how to detect if you click the nested button. Here's my code:
import pygame
from pygame.locals import *

import sys
import os
import time
from random import randrange, randint
import base64
from configparser import ConfigParser
import tkinter
from tkinter import Tk, messagebox, simpledialog

configure = ConfigParser()
configure.read('dooroperatingsystempassword.txt')
start_time = time.time()

WIDTH = 801
HEIGHT = 452
CENTER_X = WIDTH / 2
CENTER_Y = HEIGHT / 2

admin = False
complete = False
failed = False
loading = False
first_time_password = True
back_button_dofalsetotrue = 'none'
back_button_dotruetofalse = 'none'

start_screen = True
system_screen = False
privacy_screen = False
account_screen = False
time_button_screen = False
keyboard_screen = False
shutdown_screen = False

system = pygame.image.load(r'images\system_button.png')
privacy = pygame.image.load(r'images\security_button.png')
background = pygame.image.load(r'images\background.png')
shutdown = pygame.image.load(r'images\shutdown.png')
doors_icon = pygame.image.load(r'images\doors2_icon.png')

pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.mouse.set_visible(1)
pygame.display.set_caption('Doors Operating System (DOS)')
pygame.display.set_icon(doors_icon)

root = Tk()
root.withdraw()
shutdown_img_for_tkinter = tkinter.PhotoImage(file=r'images\shutdown.png')
root.iconphoto(False, shutdown_img_for_tkinter)

def letters_off():
    global loading
    if loading:
        loading = False

def decode(decode_message):
    base64_bytes = decode_message.encode('ascii').decode('UTF-8')
    message = base64.b64decode(base64_bytes).decode('UTF-8')
    return message

def check_mouse_pos(pos):
    global start_screen, loading_first_time_password
    global system_screen, privacy_screen, account_screen, time_button_screen, keyboard_screen, shutdown_screen
    print(pos)

    if start_screen and pos[0] >= 145 and pos[0] <= 233 and pos[1] >= 85 and pos[1] <= 167:
        password2 = simpledialog.askstring('Welcome to Systems', 'Password?')
        paswrd2 = configure.get('password section 2', 'password2')
        paswrd2 = paswrd2.rstrip()
        paswrd2 = decode(paswrd2)
        if password2 == paswrd2:
            start_screen = False
            system_screen = True
            print('sfdfsfsdfsfsdfsf')
            #while not start_screen and system_screen:
            #    if pos[0] >= 315 and pos[0] <= 403 and pos[1] >= 85 and pos[1] <= 167:
            #        print('es')

while not failed:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            position = pygame.mouse.get_pos()
            if start_screen:
                check_mouse_pos(position)
    screen.blit(background, (0, 0))
    if first_time_password:
        screen.blit(background, (0, 0))
        pygame.display.update()
        password1 = simpledialog.askstring('Welcome to Doors Operating System', 'Password?')
        paswrd1 = configure.get('password section 1', 'password1')
        paswrd1 = paswrd1.rstrip()
        paswrd1 = decode(paswrd1)
        if password1 == paswrd1:
            print('yay dun')
            first_time_password = False
            if not complete:
                if start_screen and not system_screen:
                    screen.blit(system, (145, 85))
                elif not start_screen and system_screen:
                    screen.blit(shutdown, (315, 85))
        else:
            messagebox.showinfo('Error 001', 'LOL NOOB YOU FAILED ROFL LOL NOOB HAHA LOOK AT YOUR FACE IT LOOKS LIKE DEATH ROFL LOL')
            pygame.quit()
            sys.exit()
    else:
        if not complete:
            if start_screen and not system_screen:
                screen.blit(system, (145, 85))
            elif not start_screen and system_screen:
                screen.blit(shutdown, (315, 85))

        pygame.display.flip()
        pygame.display.update()

First, I load my images, which work fine. Next, I defined a function decode that decodes my base 64 encoded passwords. Then, I define a function check_mouse_pos that actually checks if the mouse has clicked on the image. Finally, I made a while loop that detects if I clicked my mouse.
I'm pretty new in Pygame, so this question my seem trivial :(

A: To answer your question, it's not working because once start_screen becomes False, the function check_mouse_pos() doesn't do much.
Anytime you have a collection of things, like buttons, pause and think to yourself: "How can I handle all of these with one section of code?"
Your program has the concept of a set of buttons, some of which are shown at different phases of the system access.
So probably your button has some attributes:  Access-Level, Name, Image, Size, Location.  I'm assuming (guessing) that as the user progresses through the various logons, more buttons become available.  To keep it simple, let's make the access an integer, with 0 meaning "logged out", and increasing from there.
This leads to perhaps tuples of:
logon_butt = ( 0, "Logon",  "logon_button.png", pygame.Rect(   0,0,   128,128) )
exit_butt  = ( 0, "Exit",   "exit_button.png",  pygame.Rect( 160,0,   128,128) )
door1_butt = ( 1, "Door 1", "door.png",         pygame.Rect(   0,160, 128,128) )
door2_butt = ( 1, "Door 2", "door.png",         pygame.Rect( 160,160, 128,128) )
...

Or a class:
class Button:
    def __init__( self, access, name, image_filename, location, size )
        self.access = access
        self.name   = name
        self.image  = pygame.image.load( image_filename )
        self.image  = pygame.transform.smoothscale( image, size )
        self.rect   = self.image.get_rect()
        self.rect.x = location[0]
        self.rect.y = location[1]

logon_butt = Button( 0, "Logon", "logon_button.png", ( 0,0 ),     (128,128) )
exit_butt  = Button( 0, "Exit",  "exit_button.png",  ( 160,0 ),   (128,128) )
door1_butt = Button( 1, "Door1", "door.png",         ( 0,160 ),   (128,128) )
door2_butt = Button( 1, "Door2", "door.png",         ( 160,160 ), (128,128) )
...

Once you have a tuple or class to hold all the fields, your code can make a list of all buttons:
all_buttons = [ logon_butt, exit_butt, door1_butt, door2_butt ]  # etc.

When the user completes a password, the access-level number stored in user_access_level increases.  So at 0 they can only exit or login.
The list makes it very easy to check every button each time you get a mouse-click event:
while not failed:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            position = pygame.mouse.get_pos()
            # check which button was pressed
            for butt in all_buttons:
                if ( butt.rect.collidepoint( position ) ):     # click inside button
                    print( "Button [" + butt.name +"] pressed" )
                    if ( butt.access <= user_access_level ):   # is user allowed?
                        print( "User access OK" )

                    else:
                        print( "No ACCESS" )
                        # TODO - another login level?

The above code uses the Button class, but alternatively it could have used the tuple like butt[0] for access, and butt[1] for name, etc.
The button list also simplifies drawing all the buttons to the screen:
# repaint screen
screen.blit( background, (0, 0) )

# draw any buttons the user has access to
for butt in all_buttons:
    if ( butt.access <= user_access_level ):
        screen.blit( butt.image, butt.rect )

pygame.display.flip()

BTW: you only need to call pygame.display.flip()  (or .update()) once in the main loop.


text:
Q: Design Pattern for working with IF/ELSE in Node JS / Express / Mongoose I've quite a big application built, and constantly seeing this appearing across the application when working with mongoose:
Version.create({ version: req.body.version }, function (error, version) {
    if (error) {
        res.send(501, error)
    }
    else {
        res.send(201, version);
    }
});

The If/Else statement to send errors or content.
Is there a better way of doing this?

A: The common way to do it with JavaScript is to return early.
Version.create({ version: req.body.version }, function (error, version) {
    if (error) {
        return res.send(501, error)
    }
    res.send(201, version);
});


text:
Q: How to write a Jenkins Cron with multiple parameters I have an issue and can't seem to find results or information online.
Let's say I have a software for generating descriptions (and optional images) for dogs. The Jenkins pipeline has parameters such as name, type, a checkbox for generating an image, etc.
When I manually run the software on "build with parameters", I can fill in the boxes as so:
dog_type

Is the breed of dog.
dog_name

Name of the dog.
generate_image

is a checkbox that I click if I want an image for the dog to generate.
I want to set up a weekly run to generate a dog and picture. How would I write it to have multiple parameters?
I've tried this:
H 0 * * 1 dog_type=poodle dog_name=Molly generate_image=True

Which is supposed to run weekly, generating a picture of a poodle named Molly.
But that didn't work for me. Any help would be appreciated!

A: Take a look at this plugin. Example Pipeline below.
pipeline {
    agent any
    parameters {
      string(name: 'PLANET', defaultValue: 'Earth', description: 'Which planet are we on?')
      string(name: 'GREETING', defaultValue: 'Hello', description: 'How shall we greet?')
    }
    triggers {
        parameterizedCron('''
            # leave spaces where you want them around the parameters. They'll be trimmed.
            # we let the build run with the default name
            */2 * * * * %GREETING=Hola;PLANET=Pluto
            */3 * * * * %PLANET=Mars
        ''')
    }
    stages {
        stage('Example') {
            steps {
                echo "${params.GREETING} ${params.PLANET}"
                script { currentBuild.description = "${params.GREETING} ${params.PLANET}" }
            }
        }
    }
}


text:
Q: Bounded convolutions with binomial coefficients I need to figure out a nice family of decaying functions such that
$\sum_{d=2}^k {k \choose d} f_k(d) \leq 1/k$ and $f_k(d)\geq f_k(d+1)$
How can I figure out what good candidates could be?
Any leads or ideas?

A: I managed to find a few alternatives:
Binomial Theorem
$f_k(d) = x^d$ works for any $x$ such that $(1+x)^k \leq 1/k + 1 + kx$. The suggested $1/k^2$ from The Masked Avenger is one such $x$, but solving for each $k$ in turn one can see that we can do far better than $1/k^2$.
Vandermonde's Identity
From the identity ${m+n \choose r} = \sum_{d=0}^r{m\choose k}{n\choose r-k}$ we can extract the function families
$f_k^m(d) = \frac{{m\choose k-d}}{{k+m\choose k}\cdot k}$
that provide a viable family of functions for each $m\geq k$. These functions are not monotonic, but they are only really needed for an upper bound, so that still works. The $m$ forms a kind of a shape parameter -- higher $m$ means more mass is concentrated early on, while a lower value for $m$ means larger mass allowed in the middle of the sequence.
In particular, the Vandermonde-derived bounds allow for a much slower decay, while the exponential bounds allow for a large amount of mass used early in the sequence.


text:
Q: React Native - Button Styling Trouble I have a questions regarding React Native:
Can i transition background colour like I would do using CSS :active selector and transition?
If not, what would be the best alternative to achieve at least similar design?

A: You may do so by using the onPressIn and onPressOut callbacks on the TouchableHighlight and TouchableWithoutFeedback together with the Animation API to create such an animation. React Native also provides this behavior for TouchableHighlight, you may set an underlay color, which comes up as soon as it is clicked.


text:
Q: Is there any combination of numbers which upon division gives the exact number of P? In other words, there are (probably) infinite combination of numbers/operations which leads to irrational numbers. So I wonder, if there is one which gives exact number representation of P(π)? Do we need to measure the ratio of diameter/circumference or we can actually get infinitely accurate representation by just doing simple math? Thanks.

A: That depends on what you consider simple math. The most basic sequence you can get (i.e. looks simple) is $\pi/4 = 1 -\frac13+\frac15-\frac17+\frac19+...$.
However, as this one converges painfully slow, no one in their right mind uses it because more effective formulas have been known for ages (for example, I once used $4\arctan {\frac15} - \arctan {\frac1{239}}$). Currently rapidly converging series are used. Read the Wikipedia article on this, as suggested in the comments :)


text:
Q: Turning on multiple leds with arduino using transistor I want to be able to turn on 50 red LEDs with one pin of an Arduino. I don't want individual control, I just want to be able to turn them all on or all off.
I found this example. It uses a 2N3904 transistor. Is this the approach I want to take? I presume I would need a higher power transistor?
I am using an external power supply that is wired into a custom board with a 5v voltage regulator so I am powering the LEDs directly from this regulator.
The LEDs come in the form of this LED light bar array (or at least very similar)...
I had mentioned in a comment in an answer below that I was using a 330 ohm resistor with each LED. On another part of this project, I use the light bars as level meters, and each separate LED is controlled via a shift register, thus the separate resistor. I realise after thinking about it that I don't need to have a resistor in series with each LED for this now as they are either all on or all off (hmmm.... sorry for my rather haphazard comments!).
I did have a thought that I could have some sort of electronic switch that can disconnect ground or 5V. Is this viable?

A: A transistor is basically a switch that can disconnect ground or 5V. There are transistors of all sorts, and some can switch truly huge loads. 50 LEDs is no big deal.
So, the question then is this: Can a single 2N3904 switch 50 LEDs?
To answer that, we'd need to know first what kind of LEDs. But let's assume you are using the usual nothing-special variety. A reasonable estimate of the maximum current of these is \$20mA\$. If you have 50, then the maximum current is \$20mA \cdot 50 = 1000mA \$. Looking at the datasheet I see the maximum collector current for 2N3904 is \$ 200 mA \$. So the answer is no: you can not switch 50 LEDs with one 2N3904.
I suppose you have several options:

*

*use multiple 2N3904

*use fewer LEDs

*use the same LEDs, but drive them with less current

*use a bigger transistor (TIP121 is very easy to find)

*use some other switching device

Of these, I think reducing the LED current or using a larger transistor is probably the most likely solution. Other switching devices (like a relay) are probably more expensive and slower.

A: Considering the information given (50 Red Leds Noted at 1.95V, 5v Source, 2mA current, 330Ω resistors), the following would work.
Taking into account the common Led resistor calculation:
(Vcc - Forward Voltage) / Current
Where Vcc is 5v, Forward Voltage is 1.95v per led, since we have two in series, 1.95v * 2, and Desired Current is 2mA.
(5 - (1.95 * 2)) / 0.002 or (5 - 3.9) / 0.002 or 1.1 / 0.002 = 550.
Since you have 330Ω resistors, adjusting for that would give 3mA per Series. Not per led, but per series, as current is equal in a series path. Each series of resistors, in this case two, would use the same 3mA of current. So this simplifies the equation to 3mA * 25 series chains, only 75mA that needs to be switched.
Any common small signal transistor like the 2n3904 can handle 75mA without issue. A 1kΩ base resistor is used between the transistor base and the MCU pin.
Note, the schematic below only shows one led bar, you would just add the rest in the same fashion. Wire the first led's cathode to the next led's anode, and one resistor per pair.

simulate this circuit – Schematic created using CircuitLab

A: You should use the pin on the Arduino to control a transistor that turn on a relay and the relay contacts turn on the all the LEDs by apply ground. If you must use a transistor, then yes you need to find one that can handle all the current. Even with a relay, be sure to check the contact current ratings. See sample circuit below. Depending on the current rating and coil resistance of the relay you select, you may or may not need R2.


text:
Q: Duplicate a record with related records in another table duplicated also I have a database(Access 2010) with about 6 tables related to 1 master table, and I would like to duplicate a record from the master table, and take with it the related tables from the other tables. Is there a simpler way to do this than my current method which involves:

*

*Find the next master ID number

*insert the old record with the new ID into the master table.

*Use the new ID number to insert into each of the related tables.
I am currently using VBA to find the new ID and run the SQL. I would prefer to run this a 1 SQL query, and I am running this from a button press, so VBA is not out of the question.
Thanks for any help.

A: No, that sounds about how you have to do it, as near as I know.
Attempting to UPDATE would of course not leave any behind...
Your current solution (using VBA) is honestly probably your best bet; sure, you could use another language, or wrap it in a stored procedure, but you're still stuck with these exact steps.  It's pretty much a feature of the language (SQL) and systems (RDBMSs in general) design.


text:
Q: Calendar date picker - PHP I'm trying to use this date picker in the link below (date 3 script).
http://www.triconsole.com/php/calendar_datepicker.php
It shows me this error:
Fatal error: Uncaught Error: Class 'tc_calendar' not found in C:\xampp\htdocs\test\a.php:5 Stack trace: #0 {main} thrown in C:\xampp\htdocs\test\a.php on line 5

What should I do to correct it?
Thanks
here is a.php script:
<html>
<head><script language="javascript" src="calendar.js"></script></head>
<body>
<?php
$myCalendar = new tc_calendar("date5", true, false);
      $myCalendar->setIcon("calendar/images/iconCalendar.gif");
      $myCalendar->setDate(date('d'), date('m'), date('Y'));
      $myCalendar->setPath("calendar/");
      $myCalendar->setYearInterval(2000, 2017);
      $myCalendar->dateAllow('2008-05-13', '2017-03-01');
      $myCalendar->setDateFormat('j F Y');
      $myCalendar->setAlignment('left', 'bottom');
      $myCalendar->setSpecificDate(array("2011-04-01", "2011-04-04", "2011-12-25"), 0, 'year');
      $myCalendar->setSpecificDate(array("2011-04-10", "2011-04-14"), 0, 'month');
      $myCalendar->setSpecificDate(array("2011-06-01"), 0, '');
      $myCalendar->writeScript();

?>
<form action="somewhere.php" method="post">
<?php
//get class into the page
require_once('classes/tc_calendar.php');

//instantiate class and set properties
$myCalendar = new tc_calendar("date5", true);

$myCalendar->setDate(1, 1, 2000);

//output the calendar
$myCalendar->writeScript();

?>
</form>
</body>
 </html>

A: Did you require calendar php file in your a.php before use it?
require_once('classes/tc_calendar.php');

If so, don't you give the wrong path to the file?

A: You didn't import the class tc_calendar.
Todo so you need to download the tc_calendar and place it in your solution.
Then you need to include the php class with for example an include();
http://php.net/manual/en/function.include.php

A: You have to require first your "tc_calendar.php" file before starting to use it ,and let it the first line directly after starting the php tag for example :
<?php
//get class into the page
require_once('classes/tc_calendar.php');
$myCalendar = new tc_calendar("date5", true, false);


text:
Q: Select items with a condition in d3.js This guide is helpful for styling values <= 400 in red.
.style("fill", function(d) {
    if (d.name <= 400) { return "red" }
    else { return "black" }
;})

I would like to know how to return a specific string for custom styling. I've tried this
.style("fill", function(d) {
    if (d['title'] = "blog") { return "red" }
    else { return "black" }
;})

I'd also like to be able to select an array. For example, I would like all elements generated with the array collection to be red. How would I go about doing this?
collection = [{
  "title" : "Blog",
  "categories" : [ "Category-1", "Category-2" ]
}],

library = [{
  "title" : "Blog",
  "categories" : [ "Category-1", "Category-2" ]
},];

A: I think @George got it correct. There is a problem in your if condition.
d['title'] = "blog" actually assigns the string "blog" to d.title. What you need is a boolean comparison.
.style("fill", function(d) {
        if (d['title'] == "blog") {return "red"}
        else    { return "black" }
    ;})


text:
Q: Datamaps - eliminating white space at top/bottom Several datamaps templates have a lot of whitespace above and below the actual outline of the continents (for example, the "basic" and US maps have this; chloropleth does not have much whitespace. See: http://datamaps.github.io/)
Is there a way to shrink that empty space?
I don't see any such option in the documentation, but would it be possible to go into the map source code itself and simply edit out this whitespace? Any tips on how that might be done?
Thank you!

A: The fix I used for this issue was to fiddle with the CSS properties of the div that holds the map. This also allows you to better position the elements based on what you have around it.


text:
Q: Why are Threads so much slower than Tasks in my code I decided to learn more about threading and created a .NET 5 console application that uses 3 different ways to find all prime numbers from 2 to 100,000 and to compare how long they take to execute.
The IsPrime is used for determining if a number is a prime number and returns a boolean value
    private static bool IsPrime(int number)
    {
        bool dividedByNotItself = false;

        for (int i = 2; i < number; i++)
        {
            if (number % i == 0)
            {
                dividedByNotItself = true;
            }
        }

        if (dividedByNotItself)
        {
            return false;
        }

        return true;
    }

My Main method calls the the three methods below
FindPrimeSt (single threaded)
    private static void FindPrimeSt(int from, int to)
    {
        DateTime start = DateTime.Now;
        List<int> primeNumbers = new List<int>();

        for (int i = 2; i < to; i++)
        {
            if (IsPrime(i))
            {
                primeNumbers.Add(i);
            }
        }

        DateTime end = DateTime.Now;
        TimeSpan timeTaken = end - start;

        System.Console.WriteLine(
            $"FindPrimeSt found {primeNumbers.Count} prime numbers in {timeTaken.TotalSeconds}"
        );
    }

FindPrimeUsingTasks
    private static void FindPrimeUsingTasks(int from, int to)
    {
        List<int> primeNumbers = new List<int>();

        DateTime start = DateTime.Now;

        List<Task<bool>> tasks = new List<Task<bool>>();

        for (int i = from; i < to; i++)
        {
            int copyInt = i;

            tasks.Add(
                Task.Run(() => {return IsPrime(copyInt);})
            );

        }

        Task.WaitAll(tasks.ToArray());

        foreach (Task<bool> task in tasks)
        {
            if (task.Result)
            {
                primeNumbers.Add(1);
            }
        }

        DateTime end = DateTime.Now;
        TimeSpan timeTaken = end - start;

        System.Console.WriteLine(
            $"FindPrimeUsingTasks found {primeNumbers.Count} prime numbers in {timeTaken.TotalSeconds}"
        );
    }

FindPrimeUsingThreads
    private static void FindPrimeUsingThreads(int from, int to)
    {
        List<int> primeNumbers = new List<int>();

        DateTime start = DateTime.Now;

        for (int i = from; i < to; i++)
        {
            int copyInt = i;

            new Thread(() => {

                bool result = IsPrime(copyInt);

                if (result)
                {
                    primeNumbers.Add(i);
                }
            }).Start();
        }

        DateTime end = DateTime.Now;
        TimeSpan timeTaken = end - start;

        System.Console.WriteLine(
            $"FindPrimeUsingThreads found {primeNumbers.Count} prime numbers in {timeTaken.TotalSeconds}"
        );
    }

This is the output of the program
FindPrimeSt found 9592 prime numbers in 19.4423727 seconds
FindPrimeUsingTasks found 9592 prime numbers in 6.2772479 seconds
FindPrimeUsingThreads found 9592 prime numbers in 72.4205661 seconds
Now, FindPrimeUsingThreads is quite a lot slower than FindPrimeUsingTasks. Is all of that down to the overhead for creating the threads and Tasks taking advantage of the threadpool?
Sneaky side question:
Is using List<T>.Add() in FindPrimeUsingThreads or FindPrimeUsingTasks thread-safe, or should I create a wrapper function with a lock?
Thank you.


text:
Q: Postgresql materialized view is refreshed by itself I have this materialized view in my Postgres 9.4 database:
                 Materialized view "public.v_videolist"
  Column  |  Type   | Modifiers | Storage  | Stats target | Description
----------+---------+-----------+----------+--------------+-------------
 id       | integer |           | plain    |              |
 title    | text    |           | extended |              |
 embed    | text    |           | extended |              |
 img      | text    |           | extended |              |
 imgs     | text    |           | extended |              |
 tags     | text    |           | extended |              |
 category | text    |           | extended |              |
 vid      | bigint  |           | plain    |              |
 views    | bigint  |           | plain    |              |
 likes    | bigint  |           | plain    |              |
 unlikes  | bigint  |           | plain    |              |
 duration | integer |           | plain    |              |
 site     | integer |           | plain    |              |
Indexes:
    "i_vl_id" UNIQUE, btree (id)
View definition:
 SELECT videolist.id,
    videolist.title,
    videolist.embed,
    videolist.img,
    videolist.imgs,
    videolist.tags,
    videolist.category,
    videolist.vid,
    videolist.views,
    videolist.likes,
    videolist.unlikes,
    videolist.duration,
    videolist.site
   FROM videolist
  ORDER BY random();

Time to time this view refreshed by itself. There is no cron job to refresh it or something like that. It is just refreshed by itself from time to time, and I can't find who does it. I fully log all queries. There is no any refresh materialized view in the log.
Why is my view renewed? Any suggestions?

A: A job could be scheduled to update the statistics  using this SQL statement:
REFRESH MATERIALIZED VIEW public.v_videolist;

You can use pg_cron to schedule the job.


text:
Q: Reduce the number of operations on a simple expression Lets say I take a computation that involves only addition and multiplication:
(a+b)*(c+d)

which can be done in many other ways, eg.
a*(c+d) + b*(c+d)
a*c + a*d + b*c + b*d

In terms of additions and multiplications the number of operations required for each of the three examples shown are (2,1) (3,2) (3,4) respectively. Clearly, if the goal is to reduce the total number of operations the first is superior. Is there a way, given an arbitrary expression to find the computation order that requires the least number of operations?
Note: This question is being re-asked from SE.math for the insight and perspective of the CS crowd.

A: What you want is to effectively generate all possible equivalent algebraic expressions, and choose the one that takes the least costly number of steps (adding X three times is cheaper on most machines than multiplying X by 3).
It is impractical to do this, as the number of "equivalent" formulas is infinite.
However, Pelegrí-Llopart figured out a scheme to generate optimal code given a fixed number of algebraic rewrite rules, called  "BURS" (bottom-up rewrite system).  This has been implemented in some code generators.
In essence, he constructs offline a big automata whose states track the set of possible applied rewrites.  Each state knows what to generate when it occurs, so the online time for code generation is cheap.

A: Ignoring powers of variables and integer coefficients, this reduces to a Karnaugh Map problem.
K-Maps can be represented in sum-of-products form and product-of-sums form, each of which represents a binary circuit.  A "fewest operations" form would represent an optimized binary circuit, right?

A: There is a Horner's Rule  for the efficient evaluation of polynomials in monomial form. According to it, given a polynomial of degree n
p(x) = anxn + an-1xn-1 + ... + a1x1 + a0
Only n multiplications are needed (not n+(n-1)+(n-2)+...+1 = n(n+1)/2, as it may seem from the first glance). That is because the polinomial can be rewritten as
p(x) = (((anx + an-1)x + an-2)x + ... a1)x + a0

A: One idea - let's consider the variables as boolean values and write the maxterm form
link text

A: Not sure about the general case, but it does seem that factoring polynomials improves performance. An example from a distant comp sci course:
a * x^2 + b * x + c

is improved by factoring out x:
x * (a * x + b) + c


text:
Q: How to rename a table in sql? I try to rename the table 'folks' to 'users'.
How does it work?

A: In this case you can use ALTER TABLE with RENAME TO.
Syntax:
ALTER TABLE <Tablename>
RENAME TO <new Tablename>;

Example:
ALTER TABLE folks
RENAME TO users;

A: If you want to rename the column and also change its type
ALTER TABLE [TableName] CHANGE [Column] [ColumnName] [New type];

For example:
ALTER TABLE folks CHANGE FolkAddress Address VARCHAR(1024);


text:
Q: Rider not recognizing dotnet A few days ago, my dotnet just stopped working. I purged and reintstalled it but after that, rider stopped recognizing it and only lists .Net Framework versions from mono. I tried the version from the snap store and the way from microsoft, but both did not work.
My dotnet installation:
https://pastebin.com/6FV17eik
Ubuntu version: Ubuntu 22.04.1


text:
Q: Android theme changes do not change reliably I am trying to learn how to edit custom app themes in Android.
But for some reason changes in my styles.xml (manually and with theme editor) are being reflected on my device in an unreliable sporadic way. The behavior is perplexing.
Like I did 50 build , cleans, rebuild, etc last night trying to get option menu items text to change color and it wouldn't. Then today it just changed...and I dont know why.
I try to change the main background color, and it wouldn't change. Then all of a sudden after a build the optionmenu background color changed to the color I set main background color to.
I have not found anything reliable or reproducible in this problem.
Theme changes just are not working for me and when they do it is sporadically.
I have disabled instant run, and uninstalled app, as well as cleaned , rebuild, and made project. None of those actions have any effect on whether theme changes will take hold.
My v11, v14, and v21 styles.xml are empty, and I only modify the main styles.xml.
styles.xml
<resources>

<style name="AppBaseTheme" parent="android:Theme.Material">
    <!--
    Theme customizations available in newer API levels can go in
    res/values-vXX/styles.xml, while customizations related to
    backward-compatibility can go here.
    -->
    <item name="android:colorBackground">@color/black</item>
    <item name="android:colorForeground">@color/common_signin_btn_dark_text_pressed</item>
    <item name="android:textColorPrimary">@color/text_color_primary</item>
    <item name="android:textColorSecondary">@color/text_color_secondary</item>
    <item name="android:textColorSecondaryInverse">@color/text_color_inverse</item>
    <item name="android:textColor">@color/text_color_primary</item>
    <item name="android:itemTextAppearance">@style/MenuItemTextAppearance</item>
    <item name="android:dialogTheme">@style/DialogTheme</item>
</style>

<style name="MenuItemTextAppearance">
    <item name="android:textColor">#000000</item>
</style>

<style name="DialogTheme" parent="android:Theme.Material.Dialog.Alert">
    <item name="android:colorBackground">@color/background</item>
</style>

androidmanifest

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.me.myapp"
          xmlns:android="http://schemas.android.com/apk/res/android"
          android:versionCode="1"
          android:versionName="1.0">

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="21"/>

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

    <application
        android:name=".LocalApp"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppBaseTheme">
        <activity
            android:name=".ActMain"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".ActExport"
            android:label="@string/title_activity_export"
            android:windowSoftInputMode="stateAlwaysVisible">
        </activity>
        <!--
             ATTENTION: This was auto-generated to add Google Play services to your project for
             App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information.
        -->
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version"/>

        <activity
            android:name=".ActSaveFile"
            android:label="@string/title_activity_act_save_file">
        </activity>
        <activity
            android:name=".ActLoadFile"
            android:label="@string/title_activity_act_load_file">
        </activity>
    </application>

</manifest>

A: Your style AppBasteTheme which extends from android:Theme.Material is supported only above 21 sdk level your min sdk level is 15 which is small.Instead of this use this style which works fine.
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
<item name="android:colorBackground">@color/black</item>
<item name="android:colorForeground">@color/common_signin_btn_dark_text_pressed</item>
<item name="android:textColorPrimary">@color/text_color_primary</item>
<item name="android:textColorSecondary">@color/text_color_secondary</item>
<item name="android:textColorSecondaryInverse">@color/text_color_inverse</item>
<item name="android:textColor">@color/text_color_primary</item>
<item name="android:itemTextAppearance">@style/MenuItemTextAppearance</item>
<item name="android:dialogTheme">@style/DialogTheme</item>

A: You have to write like this you missed additional styles.
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />


text:
Q: Load a Level as child of Current level in Unity C# I want to load next screen with previous screen also visible to user. Something like that

as previous screen is covered with light white background and above it content of my next screen will appear. Can someone please guide me regarding this?

A: Use Application.LoadLevelAdditive:
http://docs.unity3d.com/ScriptReference/Application.LoadLevelAdditive.html


text:
Q: How to draw a floating resizable rectangle over any other application using a service? I have created am overlay floating icon using a service which is visible over any application. I have implemented it as follow: http://www.piwai.info/chatheads-basics/
Now what I want is that when a user drags this overlay icon in any direction a rectangle should be drawn along with it starting from the initial positon of the overlay icon to its new position. I tried creating a resizable rectangle using canvas and adding it to windowmanager but I am unable to resize it when it gets added to the window.
So in short this is what I want to achieve:
1>User press the overlay icon at positon say (x1,y1)
2>User drags the overlay icon to positon say (x2,y2)
3>A rectangle is created as the user drags the overlay icon from (x1,y1) to (x2,y2).
I have already seen this and this.
This is what I have tried so far:
    public class MyService extends Service
{
   .....
    public void onCreate()
    {
        super.onCreate();
        floatingFaceBubble = new ImageView(this);
        floatingFaceBubble.setImageResource(R.mipmap.ic_launcher);
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        final LayoutParams myParams = new WindowManager.LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT,
                LayoutParams.TYPE_PHONE,
                LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);
        myParams.gravity = Gravity.TOP | Gravity.START;
        myParams.x = 0;
        myParams.y = 100;
        windowManager.addView(floatingFaceBubble, myParams);

        try
        {
            floatingFaceBubble.setOnTouchListener(new View.OnTouchListener()
            {
                private int initialX;
                private int initialY;
                private float initialTouchX;
                private float initialTouchY;
                private long touchStartTime = 0;

                @Override
                public boolean onTouch(View v, MotionEvent event)
                {
                    switch (event.getAction())
                    {
                        case MotionEvent.ACTION_DOWN:
                            touchStartTime = System.currentTimeMillis();
                            initialX = myParams.x;
                            initialY = myParams.y;
                            initialTouchX = event.getRawX();
                            initialTouchY = event.getRawY();
                            floatingFaceBubble.setVisibility(View.INVISIBLE);

                            rectangleview=new RectangleView(getApplicationContext(),initialTouchX,initialTouchY,event.getRawX(),event.getRawY());
                            windowManager.addView(rectangleview,myParams);

                           break;
                        case MotionEvent.ACTION_UP:   //this case will be executed when button(image) is released
                            break;
                        case MotionEvent.ACTION_MOVE:   //this case will be executed when button(image) is moved
                               floatingFaceBubble.setVisibility(View.VISIBLE);
                               myParams.x = initialX + (int) (event.getRawX() - initialTouchX);
                               myParams.y = initialY + (int) (event.getRawY() - initialTouchY);
                               windowManager.updateViewLayout(v, myParams);
                               break;}}}}}

This is my Rectangleview:
public class RectangleView extends View
{
    Paint paint = new Paint();
    float pointX;
    float pointY;
    float startX;
    float startY;

    public RectangleView(Context context,float x1,float y1,float x2,float y2)
    {
        super(context);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.RED);

        startX=x1;
        startY=y1;
        pointX=x2;
        pointY=y2;    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        pointX = event.getX();
        pointY = event.getY();
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                startX = pointX;
                startY = pointY;
                return true;
            case MotionEvent.ACTION_MOVE:
                pointX=event.getX();
                pointY=event.getY();
                break;
            default:
                return false;
        }
// Force a view to draw again
        postInvalidate();
        return true;
    }

    @Override
    public void onDraw(Canvas canvas)
    {
        canvas.drawRect(startX, startY, pointX, pointY,paint);
    }
}


text:
Q: Look for value and sum specific column interval - Excel I have a table with sugar cane replication data and field management
I'd like to search in the red interval for the FIM SAFRA value. It may vary in position depending on the time of the year.
Once I find which column contains it, I need to perform a sum in the interval painted in blue, but the sum must stop exactly one column before the FIM SAFRA column
I've already tried with INDEX, MATCH and VLOOKUP. Not sure what is the best way. Any Ideas?

A: Try this,
=SUM(V11:INDEX(11:11, 1, MATCH("FIM SAFRA", 10:10, 0)-1))
'to start the rum left of V11,
=SUM(C11:INDEX(11:11, 1, MATCH("FIM SAFRA", 10:10, 0)-1))


text:
Q: I can't read the values from json_decode() array I try to pass some students data through json in wordpress. The data is taken from csv file and it has  a header line and 4 lines of values. I send data to php using
JSON.stringify(inp).
The data is sent without any problem and I decode it using json_decode: $csvdata=json_decode(str_replace("\\","",$_POST['body2']));
-- I use str_replace() because without it the data is not read properly -- $csvdata is ok. I send it back to my page using wp_send_json($csvdata); and I can see my data in console. However when I try to get the values of $csvdata, whatever I try, I get a result of 3 null, null, null data.
$i=0;
foreach($csvdata as $value) {
    $out[$i]=$value->student;
    $i++;
  }

and
wp_send_json($out);
It should get the values of my data of 'student' field. I tried almost everything with no result. Every time $out returns null, null, null
I tried also $json_decode($_POST['body2'],true) to read data as an array without any luck. Also tried html_entity_decode() or str_replace() with many combinations and always no result
Any advices???
[edit] I tried to manually recreate my csvdata like this:
$data2 =  json_decode('[{"student":"1","a1":"0"},{"student":"2","a1":"2"},{"student":"3","a1":"0"},{"student":"4","a1":"3"}]');//works
$a=0;
foreach($data2 as $value) {
    $out1[$a]=$value->student;
    $a++;`
 }
    wp_send_json($out1);

Now values are read properly. I  notice that on the first place when I wp_send_json($csvdata) in console log there are extra ... (there dots) at the end of each line, which may cause the problem, but I cannot figure out how to solve it...
{student: 1, a1: 0, a2: 0, a3: 0, a4: 0, …}
My data sent to php
console result of $csvdata

A: After 3 days of attempts I found that the error was because through JSON I was passing metadata together with my data. So I needed to replace JSON.stringify(inp) with JSON.stringify(inp.data)  and everything worked.


text:
Q: ggplot + scale_size_area , how show proportions from another cat variable After successfully plotted categorical vs categorical data
ggplot(data=data_big, aes(job, education)) +
  geom_count() +
  scale_size_area(max_size = 12)+
  theme_bw()+
  theme(axis.text.x=element_text(angle=45,hjust=1))

I wish to add one dimension making those points a 'mini pie chart'. Basically I want to add info about another (binary) categorical data.
I've calculated those proportions with
data_big %>% group_by(job,education,y) %>% summarise(n=n()) %>% mutate(rel.freq  = round(100 * n/sum(n), 2)))

giving a table like (incomplete tbl)
job     education   y/n q   rel.freq
admin. illiterate no 1 100.00
admin. basic.4y yes 10 12.99
admin. basic.4y no 67 87.01
admin. basic.6y yes 8 5.30
admin. basic.6y no 143 94.70
admin. basic.9y yes 42 8.42
admin. basic.9y no 457 91.58
admin. high.school yes 382 11.47
admin. high.school no 2947 88.53
admin. professional.course yes 49 13.50
admin. professional.course no 314 86.50
admin. university.degree yes 823 14.31
admin. university.degree no 4930 85.69
admin. unknown yes 38 15.26
admin. unknown no 211 84.74
blue-collar illiterate no 8 100.00
blue-collar basic.4y yes 123 5.31
blue-collar basic.4y no 2195 94.69
blue-collar basic.6y yes 107 7.50
blue-collar basic.6y no 1319 92.50
blue-collar basic.9y yes 240 6.62
blue-collar basic.9y no 3383 93.38
blue-collar high.school yes 94 10.71
blue-collar high.school no 784 89.29
blue-collar professional.course yes 41 9.05
blue-collar professional.course no 412 90.95
blue-collar university.degree yes 9 9.57
blue-collar university.degree no 85 90.43
blue-collar unknown yes 24 5.29
blue-collar unknown no 430 94.71
entrepreneur illiterate yes 1 50.00
entrepreneur illiterate no 1 50.00

How can I add the rel.freq data into my first plot ?
What I've tried :

*

*Count the number of observations at each location

*Proportion by fill
but somehow it explains how to show proportion based on one of the 'initial' categories, and not a 3rd one.
Edit : After exchanging with @Nathan who pointed me towards a better direction, i managed to get to this :
final

A: just leave geom_count behind and do what it was doing with a new column:
# added a few new rows for multiple jobs
job     education   y/n q   rel.freq
admin.  illiterate  no  1   100.00
admin.  basic.4y    yes 10  12.99
admin.  basic.4y    no  67  87.01
admin.  basic.6y    yes 8   5.30
admin.  basic.6y    no  143 94.70
admin.  basic.9y    yes 42  8.42
tech    basic.9y    no  22  10
tech    basic.4y    no  58  50

maybe you want sum(q) here instead:
# this is all geom_count really does but it's ornery with aes(fill)
data_big <- data_big %>% group_by(education, job) %>% mutate(cnt = sum(q))

# color for effect
ggplot(data=data_big, aes(job, education)) +
    geom_point(aes(size = cnt, fill = rel.freq),shape = 21) +
    scale_size_area(max_size = 12, name = "Count")+
    scale_fill_distiller(palette = "RdBu", name = "Rel.Freq") +
    theme_bw()+
    theme(axis.text.x=element_text(angle=45,hjust=1))

or you could take advantage of faceting to display data_big$y/n like this :
data_big <- data_big %>% group_by(education, job, `y/n`) %>% mutate(cnt = sum(q))

ggplot(data=data_big, aes(job, education)) +
    geom_point(aes(size = cnt, fill = rel.freq),shape = 21) +
    scale_size_area(max_size = 12, name = "Count")+
    scale_fill_distiller(palette = "RdBu", name = "Rel.Freq") +
    theme_bw()+
    facet_wrap(~`y/n`) +
    theme(axis.text.x=element_text(angle=45,hjust=1))


text:
Q: Why isnt java finding my json file? Ive checked spelling and everything So I'm making a Minecraft mod for 1.12.2 and me and my friend are both getting stuck on a json file not being found.
Tut >>>>
https://www.youtube.com/watch?v=42z8_UDLmk4

We have both been trying to figure this out for a while now and cant seem to find out why. He has done this exact thing before and it worked for him.

A: Add this to your build.gradle,
sourceSets {
    main { output.resourcesDir = output.classesDir }
}

Then, do gradlew --refresh-dependencies


text:
Q: Handling scroll Animation in React What is the correct way of dealing with scroll position in React? I really like smooth scrolling because of better UX. Since manipulating the DOM in React is an anti-pattern I ran into problem: how to scroll smoothly to some position/element? I usually change scrollTop value of an element, but this is a manipulation on the DOM, which is not allowed.
JSBIN
code:
import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
  handleClick = e => {
    for (let i = 1; i <= 100; i++) {
      setTimeout(() => (this.node.scrollTop = i), i * 2);
    }
  };

  render() {
    const someArrayToMap = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    return (

 this.node = node} style={{overflow: 'auto', height: '100vh'}}>
        <button onClick={this.handleClick}>CLICK TO SCROLL</button>
        {
            [...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap].map((e, i) =>
some text here
)
        }

    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

How to achieve this in a React way?

A: Here's a small, no-dependancy solution using hooks
const useSmoothScrollTo = id => {
    const ref = useRef(null)
    useEffect(() => {
        const listener = e => {
            if (ref.current && location.hash === id) {
                ref.current.scrollIntoView({behavior: 'smooth'})
            }
        }
        window.addEventListener('hashchange', listener, true)
        return () => {
            window.removeEventListener('hashchange', listener)
        }
    }, [])
    return {
        'data-anchor-id': id,
        ref
    }
}

You use it like this:
export const FeaturesSection = () => {
    const bind = useSmoothScrollTo('#features')
    return (

        ...

    )
}

Then anywhere else in your app you only need to do
Go to Features

Obviously, same caveats as above apply to .scrollIntoView({behavior: 'smooth'})

A: You can just use refs and the scrollIntoView method (with behavior: 'smooth' for smooth scrolling). It's only a few lines of code and doesn't require a package.
Say this is what you want to scroll to

[1] ...

And some sort of button
<button onClick={() => {this.scroll(this.myRef)}} className="footnote">[1]</button>

to call the scroll method

class App extends Component {
  constructor() {
    super()
    this.myRef = React.createRef();

  scroll(ref) {
    ref.current.scrollIntoView({behavior: 'smooth'})
  }
}

EDIT: Because this method is not yet supported by all browsers (overview of browser support), you might want to use a polyfill.

A: window.scroll({top: 0, left: 0, behavior: 'smooth' }) works for me.
You also need to check for browser's compability
Or use polyfill

Edit: For the completeness' sake, here is how to dynamically polyfill with webpack.
if (!('scrollBehavior' in document.documentElement.style)) {
//safari does not support smooth scroll
  (async () => {
    const {default: smoothScroll} = await import(
      /* webpackChunkName: 'polyfill-modern' */
      'smoothscroll-polyfill'
      )
    smoothScroll.polyfill()
  })()
}

By this dynamic polyfill, the package is loaded via ajax unless the browser supports the smooth scroll.
polyfill-modern is an arbitrary chunk name, which hints webpack compiler to combine packages together, in order to reduce the number of requests to the server.

A: The Simplest way to do: -
window.scrollTo({top: 0, left: 0, behavior: 'smooth' });

This simple JavaScript code is working with all browser.

A: A couple good packages out there already that can handle this for you:
https://github.com/fisshy/react-scroll - Demo
https://www.npmjs.com/package/react-scroll-to-component
Simple scroll to component
Hope this helps!

A: There are several libraries for scrolling to anchors in React. The one to choose depend on the features you're seeking and the existing setup of your page.
React Scrollable Anchor is a lightweight library that's specifically for scrolling to anchors that are mapped to URL hashes. It also updates the URL hash based on currently focused section. [Full disclosure: I'm the author of this library]
React Scroll, mentioned in another answer, is a more fully featured library for scrolling to anchors, without any reflection of location in the URL.
You can also hook up something like React Router Hash Link Scroll if you're already using React Router, which will then also tie into your URL hash.

A: I really enjoy the react-router website in the API section, they seem to use this scrollToDoc component that is a really sweet translation of a typical VanillaJS smooth-scroll function into React which depends on react-motion!

A: Simple hook:
function useScrollTo(): [string, () => void] {
    const id = useId();
    const handleScroll = useCallback(() => {
        const element = document.getElementById(id);
        if (element) {
            element.scrollIntoView({ behavior: 'smooth' });
        }
    }, [id]);

    return [id, handleScroll];
}

And usage:
function App() {
    const [section2, scrollToSection2] = useScrollTo();

    return (
        <>
            <button onClick={scrollToSection2}>Scroll</button>

Section 2

        </>
    )
}


text:
Q: How do i change the color of the anchor link in bootstrap's navbar-inverse class Here's the problem that i'm facing, the color of anchor link in the navbar-inverse class by default is set to a greyish color.
When i make changes in the css, im only able to target the link color when it is active or in focus or when hovered.
The moment i click outside (the link goes out of focus) it changes back to grey.
    .navbar-inverse .navbar-nav > .active > a,
    .navbar-inverse .navbar-nav > .active > a:hover,
    .navbar-inverse .navbar-nav > .active > a:focus
    {
        background:  aquamarine;
        color: white ;

            }

How do i specifically target color attribute of the anchor element when its not active in the navbar ?.

A: The issue is in the fact that you are specifying an anchor tag with active class, but anchor might not have active class, therefore you are seeing it as grey.
First two blocks are targeting the anchor <a> tag without the .active class. And the last one that you had in your question, is essentially the same with .active class.
.navbar-inverse .navbar-nav > li > a {
    color: #fff;
}
.navbar-inverse .navbar-nav > li > a:hover,
.navbar-inverse .navbar-nav > li > a:focus {
    color: #fff;
}
.navbar-inverse .navbar-nav > .active > a,
.navbar-inverse .navbar-nav > .active > a:hover,
.navbar-inverse .navbar-nav > .active > a:focus {
    color: #fff;
    background: aquamarine;
}


text:
Q: How do I extract an array of bits 2-9 from a bytearray? I have a 100,000 long bytearray, where every 16-bit line is a 10-bit address and 6-bit counts concatenated. I want to convert the 16-by-100,000 array into two separate (address and data) arrays in an array-wise, efficient manner. A short run-time is critical to my application.
What I have so far is

*

*read binary into a uint16 array

    f = open(curfile, mode="r")
    aint = np.fromfile(f, dtype=np.uint16)

*read each line inside a for-loop

    line = '{0:15b}'.format(aint[nn])

*extract integers from binary

    addr[nn] = 2**8*return0ifempty(line[0]) + return0ifempty(line[1:9])
    count[nn] = line[-6:]

(return0ifempty returns 0 when ' ' is input)
The whole binary => uint16 => binary => uint16 idea is extremely inefficient. There must be a better way to do this. Are there any ways to truncate the array as in matlab, e.g., A(5:10,:)?

A: Assuming you want low 10 bits and high 6 bits:
low_10 = aint & 1023
high_6 = aint >> 10

If you want low 6 bits and high 10 bits:
low_6 = aint & 63
high_10 = aint >> 6

Unlike a Python loop, this is vectorised and runs much, much, much faster (also, no conversion to string).
EDIT: Looking at your example, you want 10 high for addr, and 6 low for count; so...
count = aint & 63
addr = aint >> 6

Some explanation for 63: it is 0b111111, so & 63 will preserve 6 low bits and switch off any higher ones.


text:
Q: Не запускается JavaFX в Eclipse Не помню как устанавливал эту библиотеку в первый раз, но помню что она встала не сразу. В этот раз, уже больше полугода не программирую из-за этого, и никак не могу решить проблему.

Устанавливал и через Eclipse Marketplace, и вручную, прописывая переменные среды. Подскажите пожалуйста, что я делаю не так и FX не запускается. Может установить ее с нуля? Я пробовал около трех туториалов на полностью чистой от Java ОС, на русском, на английском и даже смотрел видео от индуса, но у меня ничего не получается. Я не понимаю, что упускаю каждый раз.


text:
Q: Can't insert data into database with ASP.NET/C# I've been trying to create a simple registration page and connecting it with database, but when I click on the button to register a new user it returns the following message:
at MappingDatabase.Connection () [0x00016] in <bea5b5103c9f4cfba42ba460a8c4180f>:0
at PersonDatabase.Insert (Person p) [0x00002] in <bea5b5103c9f4cfba42ba460a8c4180f>:0

Here's the code:
using System.Data;
using MySql.Data.MySqlClient;
using System.Configuration;

public static class MappingDatabase
{

    public static IDbConnection Connection()
    {
        MySqlConnection connection = new MySqlConnection(ConfigurationManager.AppSettings["databaseConnection"]);
        connection.Open();
        return connection;
    }

    public static IDbCommand Command(string sqlQuery, IDbConnection connection)
    {
        IDbCommand runCommand = connection.CreateCommand();
        runCommand.CommandText = sqlQuery;
        return runCommand;
    }

    public static IDbDataAdapter Adapter(IDbCommand command)
    {
        IDbDataAdapter adapter = new MySqlDataAdapter();
        adapter.SelectCommand = command;
        return adapter;
    }

    public static IDbDataParameter Parameter(string parameterName, object value)
    {
        return new MySqlParameter(parameterName, value);
    }
}

public static class PersonDatabase
{

    public static int Insert(Person p)
    {
        try
        {
            IDbConnection dbConnection = MappingDatabase.Connection();
            IDbCommand dbCommand;
            string sql = @"INSERT INTO PER_PERSON VALUES(0, ?name, ?email, ?password);";
            dbCommand = MappingDatabase.Command(sql, dbConnection);
            dbCommand.Parameters.Add(MappingDatabase.Parameter("?name", p.Name));
            dbCommand.Parameters.Add(MappingDatabase.Parameter("?email", p.Email));
            dbCommand.Parameters.Add(MappingDatabase.Parameter("?password", p.Password));
            dbCommand.ExecuteNonQuery();
            dbConnection.Close();
            dbCommand.Dispose();
            dbConnection.Dispose();
            return 0;
        }
        catch(Exception e)
        {
            Console.WriteLine(e.StackTrace);
            return -1;
        }
    }
}

Here's the repository on GitHub
It worked before on a computer running Windows 10.
Could it be a problem with the connector file (MySql.Data.dll)? How can I fix that?
Note: I use Linux Ubuntu 20.04

A: You can fix this error by downloading the right connector in the hyperlink below:
Download Connector