text:
Q: Stop event propagation on focus JQuery I'm testing keyboard navigation, but as I move on a dropdownlist it index change itself, I mean if it value is A as we focus on it through keyboard it value will become B.
I've used this to stop this but still no luck.
 e.preventDefault();
e.cancelBubble = true;
return false;

Here is the entire script of navigation.
<script type="text/javascript">
var _parent;
var _selectedIndex = 0;
$(document).ready(function() {

    $("input.flat,select.flat").click(function(){

        $("input.flat,select.flat").each(function(){
            $(this).removeClass('active_ele');
        });

        $(this).addClass('active_ele');

    });

    $("select.flat").bind('focus',function (e) {

        //e.preventDefault();
        //e.focus();
        //return false;
        //e.cancelBubble = true;
        //return false;
    });

    $("input.flat,select.flat").bind('keydown',function (e) {

        switch(e.keyCode)
        {
            case 37:
                /////Right
                _parent = $(this).parent().prev();

                if(_parent.hasClass('combo'))   ///this is select
                {
                    $(this).removeClass('active_ele');
                    nNode = _parent.children("select.flat");
                    nNode.addClass('active_ele');
                    _selectedIndex = nNode[0].selectedIndex;
                    nNode[0].focus();
                    nNode[0].selectedIndex = _selectedIndex;

                }
                else if(_parent.hasClass('inputBox'))   ///this is select
                {
                    $(this).removeClass('active_ele');
                    nNode = _parent.children("input.flat");
                    nNode.addClass('active_ele');
                    nNode.focus();

                }

            break;

            case 39:
            //////////Left

                _parent = $(this).parent().next();

                if(_parent.hasClass('combo'))   ///this is select
                {
                    $(this).removeClass('active_ele');
                    nNode = _parent.children("select.flat");
                    nNode.addClass('active_ele');
                    _selectedIndex = nNode[0].selectedIndex;
                    nNode[0].focus();
                    nNode[0].selectedIndex = _selectedIndex;
                }
                else if(_parent.hasClass('inputBox'))   ///this is select
                {
                    $(this).removeClass('active_ele');
                    nNode = _parent.children("input.flat");
                    nNode.addClass('active_ele');
                    nNode.focus();
                }

                break;

            case 40:
                /////Down
                _nNode = $(this).parent();
                _index = _nNode.attr('data');

                _index =  parseInt(_index) + 1
                ///td
                _nNode = _nNode.parent()
                    .next()
                    .children(0)[_index];

                _nNode = $(_nNode);

                if(_nNode[0])
                {
                    if(_nNode.hasClass('combo'))
                    {

                        _nNode = _nNode.children("select.flat");
                        _nNode.addClass('active_ele');
                        $(this).removeClass('active_ele');
                        _selectedIndex = _nNode[0].selectedIndex;
                        _nNode[0].focus();
                        _nNode[0].selectedIndex = _selectedIndex;

                    }
                    else if(_nNode.hasClass('inputBox'))
                    {
                        _nNode = _nNode.children("input.flat");
                        _nNode.addClass('active_ele');
                        $(this).removeClass('active_ele');
                        _nNode.focus();
                    }
                }

                break;

            case 38:
            /////Up
                    _nNode = $(this).parent();
                _index = _nNode.attr('data');
                    _index =  parseInt(_index) + 1
                ///td
                _nNode = _nNode.parent()
                    .prev()
                    .children(0)[_index];
                _nNode = $(_nNode);
                if(_nNode[0])
                {
                    if(_nNode.hasClass('combo'))
                    {

                        _nNode = _nNode.children("select.flat");
                        _nNode.addClass('active_ele');
                        $(this).removeClass('active_ele');
                        _selectedIndex = _nNode[0].selectedIndex;
                        _nNode[0].focus();
                        _nNode[0].selectedIndex = _selectedIndex;
                    }
                    else if(_nNode.hasClass('inputBox'))
                    {
                        _nNode = _nNode.children("input.flat");
                        _nNode.addClass('active_ele');
                        $(this).removeClass('active_ele');
                        _nNode.focus();
                    }
                }
                break;

            case 46:
                $(this).val("");
        }

        e.preventDefault();
        e.cancelBubble = true;
        return false;

    });
});

</script>

Link to the file, please suggest a solution, how to stop this index changing.
http://69.175.126.242/~develope/younussal/test/test.htm

A: Try e.stopPropagation();
It is in the JQuery documentation: http://api.jquery.com/event.stopPropagation/

A: I had encountered this same problem :
The hack I used was to blur it
node.addEventListener('focus',function(){this.blur();},false);

A: Use the 'TAB' key to move between controls instead of the arrows key (standard keyboard navigation).
Do not intercept arrow keys, you need them to change the values in the controls (selected items in the select boxes).
The browser and the OS should already do most of the work for you.


text:
Q: Deploy .NET Console App on a different PC I built two quick programs today.  The one I'm showing here is just a quick program that will change the date of a virtual machine to a specific date.  I've tested it and deployed it, but to no avail I cannot get it working on another machine.  I've double checked my work by following this documentation.  Both PC's are running .NET 4.7.  I'm not sure what the problem is.  Any help is appreciated!
The error:

Error: assembly specified in the dependencies manifest was not found -- package:  'microsoft.codeanalysis.common', version: '1.3.0', path: 'lib/netstandard1.3/Microsoft.CodeAnalysis.dll'

Project.cs
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows;

namespace vmRedundancy {

class Program {

    public struct SYSTEMTIME {
        public ushort wYear, wMonth, wDayOfWeek, wDay,
        wHour, wMinute, wSecond, wMilliseconds;
    }
    /// <param name="lpSystemTime">[out]</param>
    [DllImport ("kernel32.dll")]
    public extern static void GetSystemTime (ref SYSTEMTIME lpSystemTime);
    /// <param name="lpSystemTime">[in]</param>
    [DllImport ("kernel32.dll")]
    public extern static uint SetSystemTime (ref SYSTEMTIME lpSystemTime);

    static void Main (string[] args) {
        SYSTEMTIME st = new SYSTEMTIME();
        GetSystemTime(ref st);
        Console.WriteLine("The date was: " + st.wMonth + @"\" + st.wDay + @"\" + st.wYear);
        st.wDay = 1;
        st.wMonth = 6;
        st.wYear = 2017;
        SetSystemTime(ref st);
        Console.WriteLine("The date is: " + st.wMonth + @"\" + st.wDay + @"\" + st.wYear);
        //Console.WriteLine("The day of the week is: " + st.wDayOfWeek); 4
        Console.WriteLine("The time is: " + (st.wHour - 4) + ":" + st.wMinute + ":" + st.wSecond + " " + st.wMilliseconds + "ms");
            Console.ReadKey();
        }
    }
}

ChangeDateTime.json
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <RuntimeIdentifiers>win7-x64;win10-x64</RuntimeIdentifiers>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

</Project>

**The Publish: **
dotnet publish -r win7-x64

dotnet --info (deployment)

.NET Command Line Tools (1.0.4)
Product Information:
    Version:            1.0.4
    Commit SHA-1 hash: af1e6684fd
Runtime Environment:
   OS Name:     Windows
   OS Version:  10.0.15063
   OS Platform: Windows
   RID:         win10-x64
   Base Path:  C:\Program Files\dotnet\sdk\1.0.4

dotnet --info (client)

.NET Command Line Tools (1.0.4)
Product Information:
   Version:            1.0.4
   Commit SHA-1 hash: af1e6684fd
Runtime Environment:
   OS Name:     Windows
   OS Version:  6.1.7601
   OS Platform: Windows
   RID:         win7-x64
   Base Path:   C:\Program Files\dotnet\sdk\1.0.4

A: I was able to make this work by downloading and installing the .NET 4.7 SDK and changing everything to suit.  Seems weird that "core" compiled items don't work across different platforms.  I am sure I am misunderstanding something; I just don't know what!
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <RuntimeIdentifiers>win7-x64</RuntimeIdentifiers>
    <TargetFramework>net47</TargetFramework>
  </PropertyGroup>

</Project>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jest - Get Test and Description Name I am trying to get the name of the test name that was passed into it(name: string) Jest function, as well as the description name that was passed into describe(name: string, ....).
Is there a way to access this somehow?
E.g.
describe("Description", () => {
  it("Test", () => {

    const description = "How do I get the description name?"
    const test = "How do I get the test name?";

    expect(`${description} - ${test}`).toBe("Description - Test");
  });
})

CodeSandbox Link
Update 1
Underlying reason why I want this is because I want to do some custom snapshot naming conventions based on describe, test, and some environment variables (e.g. viewport sizes + mock/real data).

A: You can achieve this using a custom matcher
expect.extend({
  testName(exp) {
      return {
          pass: this.currentTestName === exp,
          message: () => '',
      };
  },
});

describe("Description", () => {
  it("Test", () => {
      expect(`Description Test`).testName();
  });
});

A: Perhaps, the most obvious solution is what you want. Instead of passing literals to describe and it just store them in a respective constants which could then be easily accessed inside the respective test cases though the outer scope.
These constants could be easily initialized either by values from the environmental variables or by literal defaults.
const suiteA = 'Description';
describe(suiteA, () => {
  const testA = 'Test';
  it(testA, () => {
    expect(`${suiteA} - ${testA}`).toBe("Description - Test");
  });
})


text:
Q: Evitar a alteração da informação no HTML Olá,
Eu estou a desenvolver uma aplicação web que, em determinadas páginas, tem uma tabela com informação e tenho um evento (em jQuery) que está sobre as linhas da tabela que quando clicadas passam para uma página de detalhe. A minha dúvida está relacionada com a forma com que eu identifico as linhas.
Neste momento estou a fazer o seguinte: <div class="test" data-id="3">.
No entanto, qualquer pessoa que saiba utilizar as ferramentas de programador, pode ir alterar o valor e passa a ver outro tipo de informação.
Existe alguma de ter este identificador mas que não possa ser alterado tão facilmente?


text:
Q: Adding facebook sdk to android I want to add the Facebook SDK to work in the emulator. I am following this tutorial:
https://developers.facebook.com/docs/android/getting-started/
I don't know what does this line mean:
adb install %HOMEPATH%\facebook-android-sdk-3.5\bin\FBAndroid-3.5.apk

the android sdk is in : C:\android-windows-sdk
and the facebook sdk is in: E:\facebook-android-sdk-3.5

A: You need to pass adb the path to your apk file. %HOMEPATH% resolves to \Documents and Settings\<your username> on Windows XP and below, and \Users\<your username> on Windows Vista and above
Since your Facebook SDK is in E:\facebook-android-sdk-3.5, try using:
adb install E:\facebook-android-sdk-3.5\bin\FBAndroid-3.5.apk


text:
Q: It is safe to use "." has MQTT topic level separator instead of "/"? The are several devices connected to RabbitMQ using MQTT protocol and there are many nodejs process subscribed with AMPQ protocol to RabbitMQ to fetch data from those devices.
The devices are publishing with topics structured like this: data.DEVICETYPE.IDDEVICE, for example one nodejs process is subscribed on the topic data.# for getting ALL messages from devices.
My concern is about the separator that, in this case, is the "."; because in all examples and the documentation of the MQTT protocol, they always use "/" (like a path folder) so i started to think that using the point instead of slash could be a problem.
It's worth to mention that the system actually works well, but i really don't know if in the future this decision could rise compatibly problems.
EDIT: Actually my structure is like this: RabbitMQ Topic structure
I started from this to create that topic structure.

A: / is the hierarchy separator in MQTT. If you use . instead, it "works", but you just have a large number of distinct top level topics.
You couldn't subscribe using wildcards using data.# - that is an invalid subscription topic. # must be the last character for a subscription and must be on its own level. As . is not a hierarchy separator you violate this last rule.


text:
Q: Getting jQuery slideshow animation to stop on click I have a slide show built with jQuery that pauses on hover. It has a group of thumbnails sitting on top of the image that advances the image when clicked, otherwise the slideshow just auto-rotates through all the images.  There is also a +/- to expand and contract a caption related to each image.  I want to have the slideshow's automatic advancing to stop if one of the thumbnails is clicked, or the +/-. Basically, just stop whenever a user clicks anywhere within the gallery (div class=".homeImg").  I'm having a major brain fart in getting this working properly and could use some advice.  Here's the jQuery:
$(document).ready(function() {

$(".main_image .desc").show(); //Show image info
$(".main_image .block").animate({ opacity: 0.85 }, 1 ); //Set Opacity

//Click and Hover events for thumbnail list
$(".image_thumb ul li:first").addClass('active');

// * Adds a class 'last' to the last li to let the rotator know when to return to the first
$(".image_thumb ul li:last").addClass('last');

$(".image_thumb ul li").click(function(){
//Set Variables
var imgAlt = $(this).find('img').attr("alt"); //Get Alt Tag of Image
var imgTitle = $(this).find('a').attr("href"); //Get Main Image URL
var imgDesc = $(this).find('.block').html(); //Get HTML of block
var imgDescHeight = $(".main_image").find('.block').height();   //Calculate height of block

if ($(this).is(".active")) { //If it's already active, then…
return false; // Don't click through
} else {
//Animate
$(".main_image img").animate({ opacity: 0}, 800 );
$(".main_image .block").animate({ opacity: 0, marginBottom: -imgDescHeight }, 800, function() {
$(".main_image .block").html(imgDesc).animate({ opacity: 0.85, marginBottom: "0" }, 250 );
$(".main_image img").attr({ src: imgTitle , alt: imgAlt}).animate({ opacity: 1}, 250 );
});
}

$(".image_thumb ul li").removeClass('active'); //Remove class of 'active' on all lists
$(this).addClass('active'); //add class of 'active' on this list only
return false;

}) .hover(function(){
$(this).addClass('hover');
}, function() {
$(this).removeClass('hover');
});

//Toggle teaser
$("a.collapse").click(function(){
$(".main_image .block").slideToggle();
$("a.collapse").toggleClass("show");
return false; // added to remove # browser jump
});

// If we are hovering over the image area, pause the clickNext function
pauseClickNext = false;
$(".homeImg").hover(
function () {
pauseClickNext = true;
},
function () {
pauseClickNext = false;
}
);

// Define function to click the next li
var clickNext = function(){
if(!pauseClickNext) {
/// find the next li after .active
var $next_li = $("li.active").next("li");
if($("li.active").hasClass("last") ){
$(".image_thumb ul li:first").trigger("click");
} else {
$next_li.trigger("click");
}
}
};

// Time between image transition
setInterval(clickNext, 6000);

});

A: On your last line: var slideTimer = setInterval(clickNext, 6000);
Then when you want to stop the animation: clearInterval(slideTimer);
Then when you want to restart it just set it again: slideTimer = setInterval(clickNext, 6000);

A: I recently set up a slide show inside a div and used recursion to make the slide show keep playing until my "stop" variable was set to "true".  Using this approach, slideshow animation would stop anytime you set stop=true; during onclick or otherwise:
var stop = false;
var i = 0;

function playGallery(){
  $("#playerWrapper").fadeOut(1500, function() {

    if(i<8){
      i = i+1;
    }
    else{
      i = 1;
    }

    $("#playerWrapper")
     .css('background-image','url("images/' + 'brooke' + i + '.jpg' + '")');

    if(!stop) {
      //Use recursion here to keep rotating slides until stop==true
      playGallery();
    }

  }).fadeIn(1500);
}


text:
Q: How do I prevent the page from scrolling when the usestate changes in react hook?     const [posttotal, settotal] = React.useState(0);

> here is changing useState value. and page scrolling to top.

   function changeVerdigiHizmetler(slct,fiyat){

        if (slct==true) {
            settotal(posttotal+Number(fiyat))

        } else {
            settotal(posttotal-Number(fiyat))
        }

    }

    function changeVerdigiHizmetler_EkHizmetler(event,adi,slct,fiyat){

        changeVerdigiHizmetler(slct,fiyat)

    }

**When I go to the onclick event, I get the price total and print it on the screen with posttotal.
There is no problem in operation.
But the page scrolls up because the useState has changed. I want to avoid this as it is annoying.
How can I prevent the page from scrolling?**


text:
Q: VCPKG: list available versions of a package For example, how can I list available GDAL library versions ?
They are not listed on VCPKG packages website neither by vcpkg search gdalcommand.

A: Try this! it is a quick fix until vcpkg supports pkgs version listing. https://github.com/hamaney/vcpkg_version_finder.
on a related note:
to look up a package by name and get the latest available version of it use vcpkg search <pkg name>
UPDATE SEP-11-2021:
I just found out that you can use the experimental flag x-history. for example vcpkg x-history <pkg name> (you might need an internet connection the first time you run this command).

A: You can use https://vcpkg.link/ in order to find all the versions of a package and when it got released (e.g. https://vcpkg.link/ports/gdal/versions for gdal). Besides, you can also see from which version a given feature has been introduced by looking at the overview of a package.
Disclosure: I'm the creator of the platform.


text:
Q: FPDF page break in fpdf I am using PHP and FPDF to generate a PDF with a list of items. My problem is, item does not                goes to a second or third page.
I want to print next block of  data in 2nd page of pdf.
     Someone please help me. I have used setautopage break()   but not working.   PLEASE HELP!
       <?php

        require('fpdf.php');

        class PDF extends FPDF {

            function Header() {

                $this->SetFont('Arial','B',10);
                $this->Rect(50,30,100,30,'F');
                $this->Text(80,45,"3D");
                $this->SetXY(20,20);
                $this->Cell(30,10,'A',1,0,'L');
                $this->SetXY(80,20);
                $this->Cell(30,10,'B',1,0,'L');
                $this->SetXY(80,60);
                $this->Cell(30,10,'C',1,1,'L');
                $this->SetXY(150,60);
                $this->Cell(30,10,'D',1,1,'L');
            }

            function Footer() {
                $this->SetY(-12);
                $this->Cell(169,20,'Page '.$this->PageNo().'/{nb}',0,0,'C');
            }

            $pdf=new PDF();
            $pdf->AddPage();
            $pdf->SetFont('Arial','B',16);
            $pdf->AliasNbPages();
            $pdf->Output();

A: You would need to use GetY and Addpage for this purpose.
Use GetY to get the current position, subtract it from the height of your document. If that is less than 6x (you have 6 rows) your multicell height, then force a page break by using AddPage.
See a detailed answer here


text:
Q: Why am I not able to initialize Generic Parameter and Array? I am trying to initialize Generic Parameter and Array
like
import java.util.ArrayList;
import java.util.List;

public class GenericExample<T> {

/*
 * Complier error -->
 *
 * Cannot instantiate the type T
 */
private T t = new T();

/*
 * Complier error -->
 *
 * Cannot create a generic array of T
 */
private T[] tArray = new T[10];

/*
 * No Complier error.
 */
private List<T> list = new ArrayList<T>();

}

There is no error when initialize list with Generic type as follows:
      /*
 * No Complier error.
 */
private List<T> list = new ArrayList<T>();

However, Complier errors appear when I am using the following initialization.
/*
 * Complier error -->
 *
 * Cannot instantiate the type T
 */
private T t = new T();

        /*
 * Complier error -->
 *
 * Cannot create a generic array of T
 */
private T[] tArray = new T[10];

Can someone help me out with the following 2 questions:
Q1: Why List<T> list = new ArrayList<T>(); does not encounter Complier error?
Q2: Why Complier error is thrown when using private T t = new T(); and private T[] tArray = new T[10]; ?

A: This is due to type erasure. The JVM has no idea what T is during runtime, since generic information is not retained for use during runtime (Java doesn't have reified generics). So when you have T t = new T(); and private T[] tArray = new T[10];, the JVM has no idea what T is.
List<T> list = new ArrayList<T>();

This works because you actually end up the following after compilation:
List list = new ArrayList();

Explicit casts to the appropriate type are then used when retrieving. That is, if you have:
List<String> list = new ArrayList<String>();
list.add("hello");
String hello = list.get(0);

During runtime what the JVM actually sees is:
List list = new ArrayList();
list.add("hello");
String hello = (String) list.get(0);

A: In Java you cannot initialize a generic object if the generic has to be stored in memory (like in your first case and in the case of an object).
There are workarounds to this, you can cast your generics to the Object class. I can't remember how you do it in terms of syntax, but search for generic casting of arrays.


text:
Q: Errors converting a form to JSON Having 2 issues submitting a form as JSON via jQuery .ajax method fiddle is here. Using my current function to get the form data, I get the error 'Uncaught TypeError: Converting circular structure to JSON' and believe it is due to submitting a date from a date picker in the form.

From json.org : "A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested."

I can't seem to get the format right either, I need to submit the data like this:
{
    "type": "value",
    "identification": {
        "ssn": "value"
    },
    "date_of_birth": "value",
    "name": {
        "first": "value",
        "middle": "value",
        "last": "value"
    },
    "address": {
        "street1": "value",
        "street2": "value",
        "city": "value",
        "state": "value",
        "postal_code": "value",
        "country_code": "value"
    }
}

and not sure how to get the nested parent, child and grandchild nesting. Here is my convert to JSON funciton:
function ConvertFormToJSON(form) {
    var array = $(form).serializeArray();
    var json = {};

    $.each(array, function(){
    json[this.name] = this.value || '';
});
  return json;
}

and here is my attempt at the submission
$('#USForm').validate({
    errorLabelContainer: "ul#msgBox",
    wrapper: "li",

    submitHandler: function(form) {

        var form = this;
        var json = ConvertFormToJSON(form);
        $.ajax({
          type:'POST',
          url:'http://ec2-54-201-216-39.us-west-2.compute.amazonaws.com/testc/WebService.asmx?op=VerifyIdentityJson',
          crossDomain:true,
          data: json,
          dataType : 'json'
        })
        .always(function(){
          console.log("always:" + json);
        })
        .done(function (response){
          console.log("done:" + json);
        })
        .fail(function(){
         console.log("fail" + json);
        });
        return false;
    },
    rules: {
        //rules
    },
    messages: {
      //messages
});

A: The first parameter (form) returns the validator instance for me. The currentForm property of it gives you the current form element.
For creating the JSON structure I would suggest using identifiers for grouping the form controls, I have used data-group attribute in the following demo:
<input type="hidden" data-group="address" name="country_code" id="country_code" value="US">

Then you can create an object using a loop:
// Please do not use a StudlyCase name for a non-Constructor function
function ConvertFormToJSON(form)
{
    var elems = [].slice.call(form.elements);
    var o = {};
    $.each(elems, function() {
        var $this = $(this),
            g = $this.data('group');

         // if the current element has data-group attribute
        if (g) {
            // if the object doesn't have `group` property yet
            // create an object so we can set a property to it later
            if ( !o.hasOwnProperty(g) ) {
               o[g] = {};
            }
            o[g][this.name] = this.value;
        } else {
           // otherwise set a top level property
           o[this.name] = this.value;
        }
    });

    return o;
}

Please note that I have manipulated the rules property just for passing validation.
http://jsfiddle.net/4nLLM/


text:
Q: Telegram Bot - How bind an InlineKeyboardButton with a CallbackQuery I'm using node-telegram-bot-api. I would have multiple InlineKeyboardButton and bind them with different CallbackQuery throw answerCallbackQuery method. Can you show me an example please? Thank you.

A: I have used the following workaround:
...
var eventEmitter = new events.EventEmitter();

eventEmitter.on('my_fancy_event_1', function(){
  ...
})

eventEmitter.on('my_fancy_event_2', function(){
  ...
})

eventEmitter.on('my_fancy_event_3', function(){
  ...
})

var options = {
  polling: true
};

...

var bot = new TelegramBot(token, options);

bot.onText(config.commands.commandStart, function onMessage(msg) {
  var options = {
    reply_markup: {
        inline_keyboard: [
            [{text: config.inlineText.addPurchase, callback_data: 'my_fancy_event_1'}],
            [{text: config.inlineText.addRevenue, callback_data: 'my_fancy_event_2'}],
            [{text: config.inlineText.getReport, callback_data: 'my_fancy_event_3'}]
        ]
    }
};
bot.sendMessage(msg.from.id, "Choose an operation.",options);
});

bot.on('callback_query', function onCallbackQuery(callbackQuery) {
   eventEmitter.emit(callbackQuery.data);
   bot.answerCallbackQuery(callbackQuery.id, "Hi", false);
});


text:
Q: matrix multiplication associative properties I want to ask a question about the associative property of matrices.
I was given an introductory course into vectors, specifically relating to matrices and then watched a video on 3Blue1Brown.
In his video, he gives a proof that the order of multiplying matrices matter.
He shows a shear and then a rotation in two different orders and shows that the basis vectors $i$ and $j$ do not match up.
$$M_1M_2 \neq M_2M_1$$
This made sense to me through his animations.
However, he later gives a proof for matrix multiplication being associative i.e.
$$(AB)C = A(BC)$$
and this didn't make sense to me.
I thought in both cases he was doing matrix multiplication, and he says in his first proof that order does matter, and then says that they're associative i.e. the order doesn't matter - and this has left me confused.
What am I missing here that's leaving me confused?

A: Order does matter, in that matrix multiplication is not commutative:
$$AB \neq BA, \text{in general}.$$
It is easy to come up with examples to show this. Most choices of matrices will do the trick, just avoid multiples of the identity, etc.
However, order does not matter in that matrix multiplication is associative:
$$ A(BC) = (AB)C.$$
That said, in proving this, you cannot assume the result. You have to assume order does matter until proven otherwise.
This is all summarized neatly in the observation that $\text{GL}_n(\mathbb{C})$ is a non-abelian group under multiplication, but don't worry if you have not come across these objects/terms yet.

A: The order in which the matrices appear matters. But given that order, the order in which we multiply them in pairs does not. (To put it another way, the order of operations is irrelevant.) In other words, you don't need brackets to clarify what $ABC$ means, but you do need to avoid conflating $AB$ with $BA$.


text:
Q: How to hide Parse.com URL properly in activation email? I have integrated Parse.com to my app, so that I managed to signup and login with my app to the Parse.com backend.
I also enabled Settings --> Email --> Email Settings --> Verify user emails
New users will receive an email with an activation link like:
https://www.parse.com/apps/testemaillogin/verify_email?token=C6MDk6PBgegdfgH1boMPj&username=name%40email.com
Parse.com provides to hide Parse.com URLs:

By uploading attached file to your server and entering its address
  below, you can hide parse.com from your users. This page is an iframe
  for Parse that lets your domain be the front-end to our back-end.

<!DOCTYPE html>

  We apologize, but user management requires javascript

I renamed that file to parse.html and uploaded it to http://my.space.com/parse.html
Then I entered under
Parse.com --> Settings --> Email --> Hide Parse.com URL --> Parse Frame URL
the above mentioned phrase:
http://my.space.com/parse.html
Now, the activation link in my email is like:

http://my.space.com/parse.html?link=%2Fapps%2testemaillogin%2Fverify_email&token=BPkcfIrEfvcnbj6uDnFsdfpWI&username=name%40email.com

as you can see to the previous version,

https://www.parse.com/apps/testemaillogin/verify_email?token=C6MDk6PdedgdfgH1boMPj&username=name%40email.com

the / in the URL were replaced by %2F (as in between testemaillogin and verify_email)
When I click on the new activation link, nothing happens --> My Parse.com backend still tells me for the emailVerfication field false
What did I make wrong?
EDIT, just for completeness: When I enter just the server to that settings field
http://my.space.com?link=%2Fapps%2Ftestemaillogin%2Fverify_email&token=wyFHdG4iQeqAcJ8I3to4UbPII&username=name%40email.com
I get:

403 Forbidden
      Code: AccessDenied
      Message: Access Denied
      RequestId: 775E40B2F6002281
      HostId: t34pG3CX5JBDRjnm0MfvlU7J7Ox9pOCYNTf44oTw3JMbolYOMZ2c7r2yyuyRzH0S3Cxvc=
  An Error Occurred While Attempting to Retrieve a Custom Error Document
      Code: AccessDenied
      Message: Access Denied


text:
Q: Intuition behind receive a straight in poker I know the answer is on wiki and other sites, but I am looking for some intuition of how to get there. Given that I am being dealt 5 cards from a well shuffled deck, there are $52 \choose 5 $ ways to pick these. Now, for a straight to occur:
There are 10 ways to pick the first card ( This could be 1,2,3,4,5,6,7,8,9,10 ), So we have $10\choose 1$ possibilities. Now the remaining four cards are constrained to being the next ascending 4 numbers: So there are $4 \choose 1$ way to pick the second card, $4 \choose 1$ way for the second,...
So in total, there should be $10\choose1$ ${ 4 \choose 1}^4$, but the answer should be $10\choose1$ ${ 4 \choose 1}^5$? What's the intuition behind this? Or am I thinking about the whole problem incorrectly?
Also, if the first card is any of 5,6,7,8,9,10, shouldn't we multiply the frequency by 2 since we can either go backwards of forward to make a straight? ie. if first card is a 5, we need either 6,7,8,9 or 1,2,3,4

A: There are $10$ different lowest ranks, as you've pointed out.  Once you pick the lowest rank, you have four choices for the lowest card (one of each suit), four choices for the second lowest, etc.  That yields $10 \cdot 4^5 = 10240$.
From that must be subtracted the number of straight flushes (which are rated higher than straights, of course!), which can be reasoned out in a similar way.  There are again $10$ different lowest ranks, and then four choices for the lowest card (one of each suit), but after that only one choice for each of the four remaining cards.  That yields $10 \cdot 4 = 40$.
Since every straight flush was counted as a straight originally, the number of straights (that are not also straight flushes) is $10240-40 = 10200$.


text:
Q: How to read INI file in Linux How would you read an INI file using Linux commands? I know in Windows you can use API calls like GetPrivateProfileString..
Example; how to get version under system2:
[system1]

version=XYZ

date=123

[system2]

version=ABC

date=985

A: Have a look at crudini which is a dedicated tool to manipulate ini files from shell
version=$(crudini --get example.ini system2 version)

Details on usage and download at:
http://www.pixelbeat.org/programs/crudini/

A: You might be interested in the python module ConfigParser:
In [1]: import ConfigParser

In [2]: config = ConfigParser.ConfigParser()

In [3]: config.read('file.ini')
Out[3]: ['file.ini']

In [4]: config.get('system2','version')
Out[4]: 'ABC'

As a script pass_config.py:
import ConfigParser

config = ConfigParser.ConfigParser()
config.read('file.ini')
print config.get('system2','version')

Run:
$ python pass_config.py
ABC


text:
Q: Slice list of paired strings and integers I want to subset a list of paired integer and string elements according to the string element found in a list (String_list).
String_list = ['I','D','X']

CIG_list = [(65, '='), (1, 'X'), (91, '='), (3, 'D'), (60, '='), (1, 'X'),
(7, '='), (2, 'S')]

I then want to take the sum of the integer elements that precede that element and the integer of that element.
    for n in CIG_list:
        if n[1] in String_list:

            hope=CIG_list[0:(CIG_list.index(n)-1)]

            if len(hope) >= 2:
                hope = CIG_list[0:(CIG_list.index(n)-1)]
                hope4=sum([m[0] for m in hope])

            else:
                hope = CIG_list[0:(CIG_list.index(n))]
                hope4=sum([m[0] for m in hope])

Best I can tell, this strategy has not worked because the index of the list is not unique (1, 'X') occurs multiple times.
Ideally, I would be able to take the sum of the integers per subset and the string associated where the slice occurred.
Desired Output:
[(65, '='), (1, 'X')] , 66 , X
[(65, '='), (1, 'X'), (91, '='), (3, 'D')] , 160 , D
[(65, '='), (1, 'X'), (91, '='), (3, 'D'), (60, '='), (1, 'X')] , 221 , X

A: You can try like this.

Note: I've just used the concept of list comprehension & enumerate() function.

String_list = ['I','D','X']

CIG_list = [(65, '='), (1, 'X'), (91, '='), (3, 'D'), (60, '='), (1, 'X'), (7, '='), (2, 'S')]

for index, tup in enumerate(CIG_list):
    ch = CIG_list[index][1]
    if ch in String_list:
        slice_l = CIG_list[:index + 1]             # Used to slice from start to matching point
        total = sum([t[0] for t in slice_l])       # 66, 160, 221 etc.
        last_char = slice_l[-1][1]                 # X, D, X etc.
        print(slice_l, ",", total, ",", last_char) # Print slice_l, total, last_char

Output:

[(65, '='), (1, 'X')] , 66 , X
[(65, '='), (1, 'X'), (91, '='), (3, 'D')] , 160 , D
[(65, '='), (1, 'X'), (91, '='), (3, 'D'), (60, '='), (1, 'X')] , 221 , X


text:
Q: Why is Visual Studio 2008 always rebuilding my whole project? I have a Visual Studio project with about 60 C++ source files. I can do a build, and it completes without errors. But if I immediately hit F7 again, it always re-compiles about 50 of the source files. It doesn't re-compile all of the files, which is strange.
I have 'Enable minimal rebuild' (/Gm) set. Any ideas why it might be doing this?
None of the files have a Modified Date in the future.

A: Are any of your file dates in the future?  This can occur if you changed time zones or changed the system clock time.  Dates in the future will confuse the IDE and force a rebuild every time F7 or F5 is hit.

A: I've solved the same problem.
In my case compiler displayed warning, that /Zi option is required if /Gm is specified.
/Gm enables "minimum rebuild", which requires debug information in .pdb file. So, if you don't want to use .pdb, also disable minumum rebuild - it solved a problem in my case.

A: Most probably is a matter of dependencies.
Consider the following possibilities:

*

*If you have custom build tools defined for some of the files in your solution, make sure that the output property contains the right file name(s). If the output of the build tool doesn't correspond to the one(s) specified in the output file names, the builder will rebuild that file.

*If you have custom build events, check whether the output from those build events don't affect the dependencies of the files to be built.

*I had problems when trying, at post-build, to copy or move some of the output files to a build folder. The post build operations that affect the timestamp of the ouput files of the build process will determine rebuild each time.

A: In my case of such effect (C++ via VS2005) it was on Release configuration only, and the Studio tells in the build output, that compiler option /Gm is ignored if /Zi - option is not set. After setting /Zi via
Configuration Properties -> C/C++ -> General -> Debug Information Format : Program Database (/Zi) ,
it was ok. But isn`t there something wrong, when the Release Configuration needs something about Debugging? Not yet clear to me!

A: Project Properties -> "C/C++" -> "Output Files" -> "Program Database File Name" option should not be empty. Set this option by selecting from drop-down box . The option will be set like this: $(IntDir)\vc90.pdb. And line ProgramDataBaseFileName="" will be removed from vcproj file.
Then only changed *.cpp files will be recompiled when you build the project or solution.

A: I'm having the same problem, and it seems to be because I've turned browse information off.  Properties->C/C++->Browse Info->Enable Browse Info->None.  The only fix I've found is turning it back on.  This is for an xbox 360 project, fwiw, my other projects don't have the problem.

A: It seems that this problem can be caused by many things, but what fixed it for me was:

*

*Closing Visual Studio

*Manually deleting all bin and obj folders (Clean doesn't seem to do the trick)

*Opening the solution and running Clean (I'm not sure if this is necessary, but I did it just in case...)

*Building like normal

Note: This was for a C# program in Visual Studio 2010.

A: After a couple days of googling, I ended up with a solution to my problem.
I encountered this problem when I moved my projects to a new PC. I had checked several times the creation date of the files. These dates were up-to-date, however the modification dates were in the bast (kinda bizarre) even when I changed the files.
A simple update of the files resolved the problem.

A: A reason is if the 'date last modified' for one of the source file is set for some date in the future: it rebuilds, and then the source file is still later than the executable.
This problem with the dates can happen if the source file is located in a directory a remote machine (a network share), and/or may even happen if your machine's time isn't synchronised with the date of the machine which is running the server of your source version control system.

A: Check your project includes any .h header file that doesn't exist on disk.  Always happens to me when I delete a header file I'm not actually including anywhere, but forget to delete it from my solution navigator in VS. Note: missing headers produce no errors during the build (when not #included anywhere).

A: Check your project's Program Database Filename setting.  For some reason, if this is set to the name of a directory (such as "$(IntDir)\"), it can sometimes cause VS to rebuild your project every time, even if you're not generating PDB files (i.e. Debug Information Format is set to "Disabled").
This is a bug in VS2008; I have not yet reproduced it yet in VS2010, but my tests haven't been thorough, so I'm not confident saying that the behavior isn't present in VS2010.

A: What caused similar symptoms at me was:
I have several projects in a solution. There were .cpp files which were referenced (and therefore compiled) by >1 projects. Unfortunately Visual Studio creates .obj files with a very simple naming - it just replaces ".cpp" by ".obj". Creating wrapper .cpp-s with different named solved the problem.

A: I had something similar.  Even though I did have pre and post build events, they weren't causing the issue.  It turned out that I had a number of projects down the reference chain that had content files that were marked as "copy always" instead of "copy if newer" meaning that these projects were always considered "out of date".  By changing all of these to "copy if newer", changes to my unit test project no longer forced a recompile of all of the other projects.

A: Disabling "minimal rebuild" (Configuration Properties > C/C++ > Code Generation) fixed it for me.  The compiler even left a clue:
1>cl : Command line warning D9007 : '/Gm' requires '/Zi or /ZI'; option ignored
Although I must point out, the compiler did not ignore the option as it said.

A: In my case I changed system data time to previous date so it is rebuilding every time because of different time stamp of the files once changed to the current time its not rebuilding every time.

A: We have that here regularly:

*

*delete all intermediate and output files by hand. The clean option in vstudio is sometimes not enough. From a fresh start do the complete build. If after a complete build vstudio still wants to recompile certain files it might be related to next bullet.

*if in your vcxproj a header file is referenced which is not on disk, the project is also recompiled. You might check this by some hidden feature described on MSDN blogs or just touch (i.e. click on it to open) all header files in the project exploder and see if one does not exist on disk

A: Had the same problem. Solved by:
-delete output folder (obj,exe,all files)
-run cygwin
-cd project folder
-run "touch *", which reset file modify date/time
-build and enjoy problem fixed

A: There is similar issue with project rebuild.
Visual Studio does not recompile but re-links a project every time on F7 hit.
Fix is simple. Try to open in Editor all files included into project (from Solution Explorer double click on each file) and remove from solution those files which do not exist.


text:
Q: TypeError: Data must be a buffer I have an http request in which I want to pass some sensitive data so I tried to encrypted these data.
In my React Native app I generated a pair of keys with react-native-rsa-native and I crypte my string with the public key via the function RSA.encrypt(my string, my public key).
After this I send the generated crypt data in my http request and I try to decrypt it in my node.js environment (Google Cloud Functions). For this I use the Crypto module.
I import it with:
const crypto = require('crypto');

And I try to decrypt my data with the RSA private key generated in my react-native module :
crypto.privateDecrypt(rsaPrivateKey, myCryptedString)

But I obtain the error:

TypeError: Data must be a buffer
      at TypeError (native)
      at Object.privateDecrypt (crypto.js:375:12)
      at exports.createPaymentMethod.functions.https.onRequest (/user_code/index.js:928:10)
      at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:37:41)
      at /var/tmp/worker/worker.js:783:7
      at /var/tmp/worker/worker.js:766:11
      at _combinedTickCallback (internal/process/next_tick.js:73:7)
      at process._tickDomainCallback
  (internal/process/next_tick.js:128:9)

Does someone have a solution to my issue ?

A: According to the documentation, the ciphertext should be an instance of Buffer rather than a String, therefore you can try to wrap the ciphertext into a buffer:
crypto.privateDecrypt(rsaPrivateKey, Buffer.from(myCryptedString))


text:
Q: How to make rake db:migrate dump the right schema when we use Scenic to manage views Every time a run rake db:migrate it generate as a result a useless db/schema.rb file which can't be loaded with rake db:schema:load simply because my views are being dumped incorrectly.
I noticed the dump is coming with my views and a table with the same name. This cause to raise an error due to a table name which already exists.
I'm currently using rails 4.2.11 and the Scenic version in my gemfile is 1.4.1.
This is a few of my tables and a view which uses them, I tried to remove all the definition for table foo_bar (same name of the view) manually and after that the rake db:schema:load worked. But the next time I ran a db:migration those useless table will come again.

ActiveRecord::Schema.define(version: 2) do

  create_table "foo_bar", id: false, force: :cascade do |t|
    t.integer  "id",                  limit: 4,                           default: 0,    null: false
    t.string   "uuid",                limit: 36
    t.decimal  "quantity",                       precision: 20, scale: 4, default: 0.0
    t.integer  "bar_id", limit: 4,                           default: 0
    t.decimal  "price",               precision: 20, scale: 4,  default: 0.0
  end

  create_table "foo", force: :cascade do |t|
    t.string   "uuid",            limit: 36
    t.decimal  "quantity",        precision: 20, scale: 4, default: 0.0
  end

  create_table "bar", force: :cascade do |t|
    t.decimal  "price",               precision: 20, scale: 4,  default: 0.0
    t.integer  "foo_id",            limit: 4
    t.decimal  "quantity",            precision: 20, scale: 4,  default: 0.0
  end

  add_index "bar", ["foo_id"], name: "index_bars_on_foo_id", using: :btree

  add_foreign_key "bar", "foo"

  create_view "foo_bar",  sql_definition: <<-SQL
      select `s`.`id` AS `id`,`s`.`uuid` AS `uuid`,`s`.`quantity` AS `quantity`,`t`.`id` AS `bar_id`,`t`.`price` AS `price` from (`foo` `s` left join `bar` `t` on(((`t`.`foo_id` = `s`.`id`))))
  SQL

end

My database is much bigger than this, and now every time I need to initiate a new app I have to run all the migrations from scratch and it takes much time and the schema:load does not


text:
Q: Why would a user's changes be overwritten without mention of a conflict? I am working on a two person team. I made some changes to a file called PostSet. I pushed those changes. My partner had also made changes to the same file, and even to the same query. He ran
git pull --rebase origin master

in order to put his changes on top of mine and keep the working history clean, as we always do. Normally we get conflicts if we edit the same line.
He was notified of a whole bunch of conflicts relating to some image files (a completely different issue). Just to explain everything, he fixed that problem by using
git rm -r path/to/image/dir

and then
git add -A

to add all of those changes to the index. After using
git rebase --continue

there were no more conflicts. We immediately noticed, however, that the relevant query was now using MY changes, not his. In fact, the entire file PostSet was on an old version after the rebase.
Shouldn't there have been some sort of conflict warning about the PostSet file? Is there something we did wrong with the rebase?
In short, we can't confidently continue development until we know changes will stop being overridden, so we're fairly frustrated.
Thanks a lot,
Paragon
Edit: We replicated our steps exactly and got the same result.
Edit: Given that nobody seems to have any clue, I will likely be reporting this as a bug in git. I'll leave it up for a while longer on the off chance that someone has a wild suggestion.

A: I did the same steps using git version 1.7.3.1.
After the step:
git rm -r path/to/image/dir

The file PostSet is still in conflict mode, you can verify by requesting that status (here is my output):
$ git status -s
UU PostSet
D  images/test.jpg

Now you still need to solve the conflict in PostSet.
If you skip that and execute instead
git add -A

you get the following case where git considers it as a solved conflict while you haven't actually done that:
$ git status -s
M  PostSet
D  images/test.jpg

So better to solve the conflict first and use afterwards git add -A
Or I might be missing some information here?


text:
Q: Dining Philosophers implementing pipes in C Have to design the Dining Philosophers program while using pipes for a class. Having some trouble in the piping message passing. Here's my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define N 5
#define LEFT (i + 4) % N
#define RIGHT (i + 1) % N
#define THINKING 0
#define HUNGRY 1
#define EATING 2

sem_t spoon;
sem_t phil[N];
int state[N];
int philNum[N] = {0, 1, 2, 3, 4};
int fd[N][2];
pid_t pid, pids[N];
int i;
int num;

void philosopher(int i);
void test(int i);
void takeSpoon(int i);
void putSpoon(int i);

char buffer[100];

I'm pretty sure the problem is with the pipes.
int main()
{
   for(i = 0; i < N; i++)
   {
      pipe(fd[i]);
      pids[i] = fork();
      printf("i = %d\n", i);
      printf("pids[i] = %d\n", pids[i] );

      if(pids[i] == 0)
      {
         dup2(fd[i][1], 1);
         close(fd[i][0]);
         close(fd[i][1]);
         philosopher(i);
         exit(0);
      }

      else if(pids[i] > 0)
      {
         dup2(fd[i][0], 0);
         close(fd[i][0]);
         close(fd[i][1]);
      }
    }

    for(i = 0; i < N; i++)
    {
      waitpid(pids[i], NULL, 0);
    }
    return 0;
}

void philosopher(int i)
{
  while(1)
  {
    sleep(1);
    takeSpoon(i);
    sleep(2);
    putSpoon(i);
    sleep(1);
  }
}

trying to figure out why the message passing is happening via the pipe implementation.
void takeSpoon(int i)
{
  sem_wait(&spoon);
  state[i] = HUNGRY;
  printf("Philosopher %d is hungry\n", i + 1);
  test(i);
  sem_post(&spoon);
  sem_wait(&phil[i]);
}

void putSpoon(int i)
{
  sem_wait(&spoon);
  state[i] = THINKING;
  printf("Philosopher %d puts downspoon %d and %d\n", i + 1, LEFT + 1, i + 1);
  printf("Philosopher %d thinks\n", i + 1);
  test(LEFT);
  test(RIGHT);
  sem_post(&spoon);
}

void test(int i)
{
  if(state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING)
  {
    state[i] = EATING;
    printf("Philosopher %d takes spoon %d and %d \n",i + 1, LEFT + 1, i + 1);
    printf("Philosopher %d eats \n", i + 1);
    sem_post(&phil[i]);
  }
}

Output:
i = 0
i = 0
pids[i] = 282
pids[i] = 0
i = 1
i = 1
pids[i] = 283
pids[i] = 0
i = 2
i = 2
pids[i] = 284
pids[i] = 0
i = 3
i = 3
pids[i] = 285
pids[i] = 0
i = 4
i = 4
pids[i] = 286
pids[i] = 0


text:
Q: How can I custom multidimensional array? I have array like this :
$a  = array('value' =>
    array(
        'lesson_id' => array('1','6'),
        'knowledge_value' => array('2','7'),
        'knowledge_description' => array('3','8'),
        'skill_value' => array('4','9'),
        'skill_description' => array('5','10')
    )
);

I want to change it to be like this :
$a = array('value' =>
    array(
        array(
            'lesson_id' => '1',
            'knowledge_value' => '2',
            'knowledge_description' => '3',
            'skill_value' => '4',
            'skill_description' => '5'
        ),
        array(
            'lesson_id' => '6',
            'knowledge_value' => '7',
            'knowledge_description' => '8',
            'skill_value' => '9',
            'skill_description' => '10'
        ),
    )
);

How can I do it?

A: Demo Link
Here is the snippet for you to work, please see inline doc for explanation
$temp = [];
$keys = array_keys($a['value']); // fetched all keys
for ($i = 0; $i < count($a['value']['lesson_id']); $i++) { // compared with first count of lession_id
    $temp['value'][] = array_combine($keys, array_column($a['value'], $i)); // combined key and values
}

array_keys — Return all the keys or a subset of the keys of an array
array_combine — Creates an array by using one array for keys and another for its values
array_column — Return the values from a single column in the input array


text:
Q: Full screen activity in Android I've a settings activity, in which the user can set the app in fullscreen mode. When the back button is hitted, the user jumps back to the main activity.
I would like to make the activity fullscreen if he had setted fullscreen inside the settings activity, preferably withouth restarting the activity.
Also it would be great if the method is supported from android API 9, to Android API 19.
If there isn't a way that i can achive this without killing the activity, is there a way i can reload the activity with the same content without manually save it somewhere on the device?
Thanks a lot for help

A: That supports API 7 to 19,
add the following before setContentView,
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);


text:
Q: Interfaces: parametrise over value or use higher-kindedness? I'm trying to get my head around the difference between these three interfaces, and when to use each
interface Foo (xs : List Nat) (n : Nat) bar where
  ...

interface Foo' (xs : List Nat) (bar : Nat -> Type) where
  ...

interface Foo'' (bar : List Nat -> Nat -> Type) where
  ...

I assume it's similar to Functor vs Show, but I'm a bit vague on that too. Any thoughts?
Context
I currently use Foo', and I'm using it in a type alias
Baz : Foo' xs bar => Type
Baz {bar} = forall m . Vect m Double -> bar m

but at usage site I need to specify xs twice: Baz {xs=[1]} {bar=MyFoo [1]} for some Foo' xs (MyFoo' xs) where, which I don't really understand because there's only one possible value that could work for xs in the application of Baz. I'm exploring the others to see if they work (no success yet), but I'm not very clear on what the API implications of each are.


text:
Q: Assign year variable to column alias for excel sheet I have an excel sheet which is bound to a stored procedure. In the stored procedure I am selecting the columns that appear in the excel sheet. Now I'm facing an issue when I wanted to add some more columns:

*

*Some value 2016

*Some value 2017

*Some value 2018

The first column is adding the actual year to the header and the two others the next one and the year after the next one.
My problem is that I don't know how to do this dynamically. I've tried something like this:
DECLARE @actualYear INT = YEAR(GETDATE())

SELECT tab.Name,
    myTable.SomeValue [Some value @actualYear],
    myTableNext.SomeValue [Some value @actualYear+1],
    myTableAfterTheNext.SomeValue [Some value @actualYear+2]
FROM SomeTable tab
LEFT JOIN MyTable myTable ON tab.SomeId = myTable.SomeId
    AND myTable.[Year] = @actualYear
LEFT JOIN MyTable myTableNext ON tab.SomeId = myTableNext.SomeId
    AND myTable.[Year] = (@actualYear+1)
LEFT JOIN MyTable myTableAfterTheNext ON tab.SomeId = myTableAfterTheNext.SomeId
    AND myTable.[Year] = (@actualYear+2)

The output is the following:
+------+------------------------+--------------------------+--------------------------+
| Name | Some value @actualYear | Some value @actualYear+1 | Some value @actualYear+2 |
+------+------------------------+--------------------------+--------------------------+

Second try:
SELECT tab.Name,
    myTable.SomeValue ['Some value' + @actualYear]
    ...

Output:
+------+----------------------------+ ...
| Name | 'Some value' + @actualYear | ...
+------+----------------------------+ ...

How can I get the correct column headers dynamically?

A: You'll have to create a dynamic sql query like so (short example):
declare @i int;
declare @sql nvarchar(max);

set @i = 2016;
set @sql = N'select 1 as [' + cast(@i as nvarchar) + N']';

exec(@sql);

Translated to your sql query this should be something like this:
declare @sql nvarchar(max);
declare @actualYear int = year(getdate());

set @sql = @sql + N'select  tab.Name, '
set @sql = @sql + N'        myTable.SomeValue [' + cast(@actualYear as nvarchar) + N'], '
set @sql = @sql + N'        myTableNext.SomeValue [' + cast(@actualYear + 1 as nvarchar) + N'], '
set @sql = @sql + N'        myTableAfterTheNext.SomeValue [' + cast(@actualYear + 2 as nvarchar) + N'] '
set @sql = @sql + N'from    SomeTable tab '
set @sql = @sql + N'left join MyTable myTable '
set @sql = @sql + N'on      tab.SomeId = myTable.SomeId '
set @sql = @sql + N'        and myTable.Year = @actualYear '
set @sql = @sql + N'left join MyTable myTableNext '
set @sql = @sql + N'on      tab.SomeId = myTableNext.SomeId '
set @sql = @sql + N'        and myTable.Year = (@actualYear + 1) '
set @sql = @sql + N'left join MyTable myTableAfterTheNext '
set @sql = @sql + N'on      tab.SomeId = myTableAfterTheNext.SomeId '
set @sql = @sql + N'        and myTable.Year = (@actualYear + 2); '

exec(@sql);

How to easily convert an SQL query into a dynamic SQL query:

Note, within Notepad++ you should replace the regular expression ^(.*)$ with set @sql = @sql + N'\1 '.
Update
Possible implementation of the above into a stored procedure (short example only):
IF OBJECT_ID('procTest', 'P') IS NOT NULL
    DROP PROCEDURE procTest;
GO

CREATE PROCEDURE procTest
AS
BEGIN
    DECLARE @i INT;
    DECLARE @sql NVARCHAR(MAX);

    SET @i = 2016;
    SET @sql
        = N'insert into #t (Column1) VALUES (' + CAST(@i AS NVARCHAR)
          + N'); ' + N'insert into #t (Column1) '
          + N'SELECT cast(1 as nvarchar) as [' + CAST(@i AS NVARCHAR) + N']';

    EXEC (@sql);
END;
GO

CREATE TABLE #t
(
    Column1 NVARCHAR(MAX)
);

EXEC dbo.procTest;

SELECT *
FROM #t;

DROP TABLE #t;


text:
Q: How do i capture the text in the Instant Search box in Outlook 2010 in vba I've amended some code I found which will allow me to create a ribbon button to search back sixty days.
Sub LastSixtyDays()
    Dim myOlApp As New Outlook.Application
    Dim tDate As Date
    tDate = Now - 60
    txtsearch = "received: (" & Format(tDate, "dd/mm/yyyy") & ".." & Format(Now, "dd/mm/yyyy") & ")"
    myOlApp.ActiveExplorer.Search txtsearch, olSearchScopeCurrentFolder
    Set myOlApp = Nothing
End Sub

which works perfectly, but how do i append "txtsearch" to the existing contents of the Instant Search box just like the clicking on the "has attachments", "subject", "from" in the search tab does?
So, if "From:bob" is in the Instant Search box, clicking my button will result in "From:bob received: (23/02/2015..24/04/2015)"

A: The Outlook object model doesn't provide any property or method for that.
You may try to use CurrentView property of the Folder or Explorer class which returns a View object representing the current view. To obtain a View object for the view of the current Explorer, use Explorer.CurrentView instead of the CurrentView property of the current Folder object returned by Explorer.CurrentFolder. For example:
Sub GetView()
  'Creates a new view
   Dim objName As NameSpace
   Dim objViews As Views
   Dim objView As View
   Set objName = Application.GetNamespace("MAPI")
   Set objViews = objName.GetDefaultFolder(olFolderInbox).Views
   'Return a view called Table View
   Set objView = objViews.Item("Table View")
End Sub

The TableView class provides the Filter property which returns or sets a string value in DAV Searching and Locating (DASL) syntax, that represents the current filter for the view.
Private Sub FilterViewToLastWeek()
  Dim objView As View
  ' Obtain a View object reference to the current view.
  Set objView = Application.ActiveExplorer.CurrentView
  ' Set a DASL filter string, using a DASL macro, to show
  ' only those items that were received last week.
  objView.Filter = "%lastweek(""urn:schemas:httpmail:datereceived"")%"
  ' Save and apply the view.
  objView.Save
  objView.Apply
End Sub


text:
Q: Making a text editor in Racket. Creating a Key map I'm attempting to create a text editor in Racket. I've created an editor-canvas class and I'm trying to override the on-char event
(define cnv%
  (class editor-canvas% ; base class
    ; Override on-event
    (define/override (on-char event)
      (display (format "event is: ~a" (send event get-key-code))))
    (super-new)))

I figured I could use a combination of (get-control-down) and the key to check for navigation, but instead it just seems to be disabling my ability to type in the canvas. I don't think this is the right way to do it but I'm unsure how to proceed from here.


text:
Q: How to disable calculating with nans while pandas resample().mean() and resample().sum()? I need to calculate the annual mean from monthly data. If there is a nan value in my monthly data, I want the whole year to be nan as well.
This is my code so far:
station_data = pd.read_csv(station_data_files[0], sep=';', header=0)
station_data = station_data.replace(-999, np.nan)
station_data = station_data.set_index("MESS_DATUM_BEGINN") # it is a row with time dates

station_data_anual = pd.DataFrame()
station_data_anual["Y_TT"] = station_data["MO_TT"].resample("A").mean()
station_data_anual["Y_RR"] = station_data["MO_RR"].resample("A").sum()

The problem is, that it ignores the nans. Which means e.g. that station_data_anual["Y_RR"] values are to low. For years in which I have only nans as monthly values, it returns 0.
Note: There are some questions similar to mine, but they didn't help me.
Note: Python
some clarifications:
Input Data:
station_data
Out[235]:
                   STATIONS_ID MESS_DATUM_ENDE  QN_4  ...  MO_RR  MX_RS  eor
MESS_DATUM_BEGINN                                     ...
1981-01-01               403.0      1981-01-31  10.0  ...   51.5   10.0  eor
1981-02-01               403.0      1981-02-28  10.0  ...   23.8    5.4  eor
1981-03-01               403.0      1981-03-31  10.0  ...  116.5   28.0  eor
1981-04-01               403.0      1981-04-30  10.0  ...   24.1    9.5  eor
1981-05-01               403.0      1981-05-31  10.0  ...   29.4    8.4  eor
                       ...             ...   ...  ...    ...    ...  ...
2010-08-01               403.0      2010-08-31  10.0  ...    NaN   29.1  eor
2010-09-01               403.0      2010-09-30  10.0  ...    NaN   29.8  eor
2010-10-01               403.0      2010-10-31  10.0  ...    NaN    5.5  eor
2010-11-01               403.0      2010-11-30  10.0  ...    NaN   17.5  eor
2010-12-01               403.0      2010-12-31  10.0  ...    NaN    8.2  eor

[360 rows x 16 columns]

have a closer look:
station_data["MO_RR"][276:288]
Out[242]:
MESS_DATUM_BEGINN
2004-01-01    66.3
2004-02-01     NaN
2004-03-01     NaN
2004-04-01     NaN
2004-05-01     NaN
2004-06-01     NaN
2004-07-01     NaN
2004-08-01     NaN
2004-09-01     NaN
2004-10-01     NaN
2004-11-01     NaN
2004-12-01     NaN
Name: MO_RR, dtype: float64

Output Data:
station_data_anual
Out[238]:
                        Y_TT   Y_RR
MESS_DATUM_BEGINN
...
2003-12-31          9.866667  430.5
2004-12-31          9.620833   66.3
2005-12-31          9.665833    0.0
2006-12-31         10.158333    0.0
2007-12-31         10.555000    0.0
2008-12-31         10.361667    0.0
2009-12-31          9.587500    0.0
2010-12-31          8.207500    0.0

my result has to look like:
                        Y_TT       Y_TX      Y_TN   Y_RR
MESS_DATUM_BEGINN
...
                        Y_TT   Y_RR
MESS_DATUM_BEGINN
...
2003-12-31          9.866667  430.5
2004-12-31          9.620833    nan    # getting nan instead of 66.3 is especially important
2005-12-31          9.665833    nan
2006-12-31         10.158333    nan
2007-12-31         10.555000    nan
2008-12-31         10.361667    nan
2009-12-31          9.587500    nan
2010-12-31          8.207500    nan

A: I have never used sampling and there might be better solutions out there which could simply ignore the "group" based on "condition". But a very simple solution could be to use a custom mean function after resample.
def very_mean(array_like):
    if any(pd.isnull(array_like)):
        return np.nan
    else:
        return array_like.mean()

station_data_anual["Y_TT"] = station_data["MO_TT"].resample("A").apply(very_mean)

A: Could you try to remove the nan values first using?
station_data_anual = pd.DataFrame()
station_data_anual["Y_TT"] = station_data["MO_TT"].dropna().resample("A").mean()
station_data_anual["Y_RR"] = station_data["MO_RR"].dropna().resample("A").sum()

A: It seems that NaN values are not included in the mean, considering the following experiment:
df_ = pd.DataFrame(index=pd.date_range("2022","2023",periods=12))
df_['a'] = np.ones(12)
df_.iloc[1]['a'] = np.NaN
df_.resample("2M").mean()

All of the averaged 2 month periods still have 1.0 as the mean value in the output of the mean() calculation above:
              a
2022-01-31  1.0
2022-03-31  1.0
2022-05-31  1.0
2022-07-31  1.0
2022-09-30  1.0
2022-11-30  1.0
2023-01-31  1.0


text:
Q: Implement Asp.Net Ajax Controls in MVC I was reading telerik post
 About Telerik ASP.NET AJAX Controls in MVC project. According to them we can implement Telerik AJAX control in Asp.Net MVC. So my question is can we implement ASP.Net Ajax control in my Asp.Net MVC Project.
If Yes how could it should be done?

A: Yes you can, but you must be aware of the limitations.  You can read more from their documentation on Telerik.com; they have some documentation on this process.  I would recommend using the MVC helpers where possible.


text:
Q: How do you move an ImageButton without compressing the image? As you can see here, my calendar image is roughly equal on both sides of the white layout, which is what I want, however the image was compressed/shrunk when I added 'paddingLeft'. How could I move the image to the right without shrinking it horizontally to fit?
Here is the XML:
<LinearLayout
        android:id="@+id/leftTopLinearLayout"
        android:layout_width="match_parent"
        android:layout_height="140dp"
        android:layout_weight="1"
        android:paddingRight="7dp"
        android:background="#ffffff">

        <ImageButton
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="5dp"
            android:scaleType="fitXY"
            android:translationX="2dp"
            android:background="#ffffff"
            android:src="@drawable/calendar"
            android:adjustViewBounds="true"/>

</LinearLayout>

Also, when I change the 'paddingLeft' to 'layout_marginLeft', it does the exact same thing, it compressed the image horizontally rather than shifting it to the right.


text:
Q: TFS Deployment to Azure Error: cannot find ClientPerfCountersInstaller.exe I configured our implementation to use the Azure Caching provider to maintain session state between all cloud instances like described here:
http://msdn.microsoft.com/en-us/library/windowsazure/gg185668.aspx
This created a new startup task on my csdef file that always fails with this error:
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\Windows Azure Tools\2.0\Microsoft.WindowsAzure.targets (987): CloudServices64 : Cannot find file named 'approot\bin\Microsoft.WindowsAzure.Caching\ClientPerfCountersInstaller.exe' for startup task Microsoft.WindowsAzure.Caching\ClientPerfCountersInstaller.exe install of role MyRole.Web.
The .exe in the nuget package and in the main folder is included in the source control that TFS uses for the deployment.
I found this previous question that addresses this same issue:
Azure Deployment Error: cannot find ClientPerfCountersInstaller.exe
But the accepted answer states to just delete the startup task that installs the .exe needed for the caching to take place.

A: Make sure the .exe is marked as CopyAlways so that it is copied to your \bin directory.
To do so, right click on the .exe in Visual Studio and select properties. Make sure it looks like this:

A: I had a similar issue with a dedicate cache worker role, but in my case the Microsoft.WindowsAzure.Caching folder never showed up in VisualStudio. In the end, I had to open the .csproj file for the worker role project and this:
<None Include="Microsoft.WindowsAzure.Caching\ClientPerfCountersInstaller.exe.config">
  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Microsoft.WindowsAzure.Caching\ClientPerfCountersInstaller.exe">
  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Microsoft.WindowsAzure.Caching\PerformanceCounters.xml">
  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>

I put that within the same <ItemGroup> tag as the app.config file, and now it's deploying as it should.


text:
Q: Heteroskedasticity in a VEC model, adding robust standard errors and plotting forecasts I'm dealing with a data set which required me to log and take first differences of it to induce stationary. A VECM as a result was prodouced.
Everything seemed fine until I checked for hetroskedasticity using arch.test command in R and found that it was present.
How do I add factor in robust standard errors into my forecasts? More specifically, what should my code look like?

A: The arch.test tells you the residuals display autoregressive conditional heteroskedasticity. To properly account for it, you can model the conditional variance of your time series with a multivariate GARCH model, e.g. BEKK-GARCH or DCC-GARCH; the latter is available in the rmgarch package in R. There you may

*

*specify (dccspec) the conditional mean model as VAR (knowing that VECM has an equivalent representation as VAR) alongside the conditional variance model;

*fit the model (dccfit); and

*produce forecasts from them in an automated way (dccforecast).

Check out the rmgarch vignette (p. 3-6) and the help files.
The tricky part will be specifying the VAR model so that it obeys the restrictions due to the cointegrating relationship, i.e. so that it corresponds to the VEC model. To avoid this, you may fit your model in two stages: first the conditional mean just the way you did it, and then the conditional variance of the model residuals. You will get the point forecasts just as before and you will have to add the confidence bounds based on the conditional variance forecasts from the conditional variance model. I am not aware of any R commands that would do this directly, so I am afraid you will have to do a little bit of programming yourself.


text:
Q: Prove that any postage greater than 17 can be made using 4 and 7 cent stamps Please use strong induction for the problem. I know that regular induction doesn't work. I assume there is a proof by logic by simply saying that 18, 19 and 20 cents can be made using these stamps and that you just need to subtract a 7 cent stamp and then add two four cent stamps to get the next higher cent value. However, that is not formaly strong induction.

A: Hint 1
$$18=7+7+4 \\
19=7+4+4+4\\
20=4+4+4+4+4 \\
21=7+7+7$$
Hint 2: If $n \geq 21$ and  you know that $P(1), P(2),.., P(n)$ is true, then $P(n-4)$ is true.

A: Hint: If you can make any four consecutive denominations you can make any afterward by adding four-cent stamps. So all you have to do is show combinations adding up to 18 to 21 cents.


text:
Q: requestAnimationFrame() not refreshing I'm learning how to use requestAnimationFrame() and the animation changes when refreshing the page. Shouldn't it should continuously change the font size without having to refresh it?
var x = Math.floor((Math.random() * 100));

function draw(){
  for (i=0; i < 100; i++){
    $("#lw").css("font-size", x);
  }
  requestAnimationFrame(draw);
}

requestAnimationFrame(draw);

A: requestAnimationFrame is working like it's supposed to. You're never changing the conditions between calls or loop iterations.

function draw(){
  for (var i = 0, x = Math.floor((Math.random() * 100)); i < x; i++){
    $("#lw").css("font-size", i);
  }
  requestAnimationFrame(draw);
}

requestAnimationFrame(draw);

Test

A: The problem is that your loop is setting the css to the value of x. Which is set outside of the loop.  If you want the size to get bigger set the font size to i instead of x


text:
Q: Creating a web server proxy for static website in Azure I have a static website in Azure that's hosted using the blob storage account. I need to make requests from this website to services hosted in other domains. In order to handle CORS, I need to build a forward proxy server that handles the requests from client and forwards them to the requested service. Similarly, response from the services will be forwarded to the client. What is the recommended way to achieve this?

A: You can write an Azure Function (with consumption plan) using your favourite programming language. Just send requests from front end to the Azure Function, then once you get the reply from 3rd party servers, return it to the front end.
PS: use the Http Trigger binding
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook?tabs=csharp


text:
Q: Can I use grep matches to execute command? I need to upgrade php from 5.3 to 5.4. I've installed it with rpm.
I want clean install: delete all 5.3 packages, and install all necessary 5.4.
Here is the command to see all installed packages:
rpm -qa |grep php

It prints out a list of packages, and I want to remove all them with:
rpm -e *pakage.name*

Can I iterate over all matches in grep results and use each match in:
rpm -e *grep.match*

A: Try this:
rpm -qa | grep php | xargs rpm -e

A: You generally don't want to remove packages like this in pieces since there's typically dependencies that you're skipping over. Better to do this removal all at once like so:
$ rpm -e $(rpm -aq | grep php)

Better still I would encourage you to use yum to do this vs. RPM.
$ yum remove $(rpm -aq | grep php)

Even better then these would be to figure out a pattern that matches all the PHP packages and tell YUM to remove based on the pattern . Yes YUM is aware of regular expressions.
$ yum remove 'php*'

You'll need to make sure that your entire list of packages will fit on the command line but doing this using xargs or individually is wrought with problems, if you tell rpm to remove 1/2 of the PHP related packages in one command, followed by another rpm command with the rest.

A: Try this script:
for p in $(rpm -qa |grep php) ; do rpm -e ${p} ; done

A: ( IFS='
' ; printf 'rpm -e "%s"\n' $(rpm -qa |grep php) |
    . /dev/stdin )

There you go.


text:
Q: AWS API Gateway access private API Gateway in another account Is it possible to have a (public) AWS API Gateway in account A access a private API Gateway sitting in account B?
If so, how is this configured?
This article describes the setup, but uses a VPC within account A with an NLB and VPC peering.
Are there any other alternatives?

A: Apart from the VPC peering approach, you can implement your use case using Lambda functions (placed in a VPC in account A) and the private API in account B allowing the VPC in account A access in its resource policy. Also note, the two VPCs should be in the same region for this setup.
How it would look:

*

*Public API in account A has integration set up with a Lambda function in the same account

*Lambda function is placed inside a VPC (let's call this VPC A)

*Private API in account B allows VPC A access in its resource policy

*Lambda function in account A should now be able to invoke the private API and return the required data


text:
Q: Predict_generator giving same output value for all images (CNN- regression) I am doing image regression using a CNN. I am currently testing my model on 4K images but plan to expand to 12K images. My code works perfectly fine with Keras test_train_split.
I am trying to use ImageDataGenerator to allow me to load images in memory easily.
train_generator = datagen.flow_from_dataframe(dataframe= df,
                                          directory='ImageChips_Group1',
                                          x_col='EB_ID',
                                          y_col='TOT_P',
                                          subset = 'training',
                                          target_size = (img_height, img_width),
                                          seed=42,
                                          batch_size= Batch_size,
                                          shuffle= False,
                                          pickle_safe = True,
                                          workers=1,
                                          class_mode='raw')

validation_generator = datagen.flow_from_dataframe(dataframe= df,
                                          directory='ImageChips_Group1',
                                          x_col='EB_ID',
                                          y_col='TOT_P',
                                          subset ='validation',
                                          target_size = (img_height, img_width),
                                          seed=42,
                                          batch_size= Batch_size,
                                          shuffle= False,
                                          pickle_safe = True,
                                          workers=1,
                                          class_mode='raw')

My best score using fit_generator is loss: 39.3873 - val_loss: 20.0538 (MAE) since I am using Callbacks to store the best model I expect my evaluate and predict functions to have similar results.
ValScore = saved_model.evaluate_generator(validation_generator,
                                          steps = validation_generator.n,
                                          verbose =1,
                                         )
print("Test set Accuracy = ", ValScore )

TrainScore = saved_model.evaluate_generator(train_generator,
                                            steps = train_generator.n,
                                           verbose =1,
                                            )
print("Train set Accuracy = ", TrainScore)

However using evaluate I get 28.9 % and 50.8% on val and test set respectively.
Moreover I get worse results using predict_generator
 validation_generator.reset()
 y_predict =saved_model.predict_generator(validation_generator,
                                            steps = validation_generator.n//validation_generator.batch_size +1,
                                            verbose=1)

I have found that my predictions are just repeating the same number. I also calculated MAE using the validation_generator.labels to get 39.51%. I don't understand why this is different from evaluate_generator (As my model has trained well I don't think there is anything wrong the data or the training, there is something wrong in the way its being evaluated )
Similar issues have been posted here and here, which mainly point to setting shuffle=False and resetting the generator (which I did but didn't solve the issue).

A: It could also be that the problem is very hard to learn. I've had this and actually after 6 hours of identical outputs in each batch (which happens because the 'average' answer is the easiest to minimize loss), the network finally started learning:

Some things I plan on doing to make the learning happen earlier:

*

*changes in learning rate

*using features from earlier in the network


text:
Q: How to IPC with the parent process when creating child processes in a loop (Ruby) I have the following code snippet (a simplified representation of what I'm trying to do - training wheels). The sleep(2) would represent some network operation in my real code:
arr = []

5.times do |i|
     rd, wr = IO.pipe
     fork do
         sleep(2) # I'm still waiting for the sleep to happen on each process ... not good, there is no parallelism here
         rd.close
         arr[i] = i
         Marshal.dump(arr, wr)
     end
     wr.close
     result = rd.read
     arr = Marshal.load(result)
end

# Process.waitall
p arr

Q: is it possible to somehow create new processes in a loop, pass the results back but not waiting on each iteration. I'm pretty rusty and don't know / remember a great deal about IPC ... especially in Ruby.

*

*Actual result is wait time of 2s*5 = 10s

*Expected ~2s tootal (async processing of the sleep())

So a good comment clarifying things, explaining the theory would help a lot. Thanks.

A: In your loop you wait for each child process to write its results to the pipe before starting the next iteration.
The simplest fix would be to save the read ends of the pipes in an array and don't read any of them until the loop is finished and you've started all the child processes:
arr = []
# array to store the IOs
pipes = []

5.times do |i|
  rd, wr = IO.pipe
  fork do
    sleep(2)
    rd.close
    # Note only returning the value of i here, not the whole array
    Marshal.dump(i, wr)
  end

  wr.close
  #store the IO for later
  pipes[i] = rd
end

# Now all child processes are started, we can read the results in turn
# Remember each child is returng i, not the whole array
pipes.each_with_index do |rd, i|
    arr[i] = Marshal.load(rd.read)
end

A more complex solution if the wait/network times for different child processes variad might be to look at select, so you could read from whichever pipe was ready first.


text:
Q: Jordan-Hahn decomposition in Robert Ash's book I was reading through the book "Real Analysis and Probability" by Robert Ash, and got really confused by the proof given to the Jordan-Hahn decomposition. The theorem states the following.
Let $\lambda$ be a countably additive extended real valued function on the $\sigma$ field F, then defining:
$\lambda ^+(A)= \sup\{\lambda(B): B \in F , B\subset A\}$
$\lambda ^-(A)= -\inf\{\lambda(B): B \in F , B\subset A\}$
Then $\lambda^+, \lambda^-$ are measures on F and $\lambda=\lambda^+-\lambda^-$
In the proof he says we can assume that $\lambda$ doesn't assume the value $- \infty$, by using the following reasoning. If $- \infty$ belongs to the range of $\lambda$ then, $\infty$ does not, by the definition of countable additive function.Thus $-\lambda$ never takes the value $- \infty$, but I don't understand how this last sentence justifies that we can assume such fact.

A: Suppose that $\lambda (A)=\infty $ and for all measurable $B\subset C=\left(\bigcup \{X:X\in F\}\right)\setminus A$ we have $\lambda (B)-$ is finite or $\lambda (B) =\infty.$ Then for every $D\in F$ we have $\lambda (D) =\lambda ((D\cap A)\cup (D\cap C))=\lambda (D\cap A) +\lambda (D\cap C)$ is finite or equal $\infty.$
Now assume that $\lambda (T) =\infty$ and $\lambda (S)=-\infty $ for some $T, S\in F$ then by the above there exists $S_1 \in F$ such that $T\cap S_1 =\emptyset $ and $\lambda (S_1 ) =-\infty.$ But this is imposible since $T\cup S_1 \in F$ and $$\lambda (T\cup S_1 ) =\lambda (T) +\lambda (S_1 ) =\infty -\infty$$ is undefined.

A: Any signed measure cannot attain both the values $\infty$ and $-\infty$ (as explained in the other answer). If $\lambda$ does attain the value $- \infty$, then $- \lambda$ does not attain the value $-\infty$ since it is a signed measure that attains the value $\infty$. Hence we can instead decompose $-\lambda$ and obtain from that the decomposition of $\lambda$ since $$(-\lambda)^+ = \lambda^- \text{ and } (- \lambda)^- = \lambda^+, \text{ so } \lambda = - (-\lambda) = - \lambda^- + \lambda^+.$$
Furthermore $\lambda^+$ and $\lambda^-$ are measures by the above relations once we have proven both claims under the assumption that $\lambda$ does not attain the value $-\infty$. Thus we may replace $\lambda$ by $-\lambda$ to assume that $\lambda$ does not attain the value $-\infty$.


text:
Q: Append column to a dataframe using list comprehension format I would like to append a column of zeros to a dataframe if the column in question is not already inside the dataframe.
If the dataframe looks like this:
df = pd.DataFrame({'a':[0,1,0], 'c':[1,1,1]})

----------------------------------------------
    a   c
0   0   1
1   1   1
2   0   1

And the complete list of column names that the dataframe should have are:
col_names = ['a', 'b', 'c']

I would like the output to look like this after applying the list comprehension to the df:
    a    b    c
0   0    0    1
1   1    0    1
2   0    0    1

This is the complete code I have so far:
col_names = ['a','b','c']

df = pd.DataFrame({'a':[0,1,0], 'c':[1,1,1]})

# This is what I would like to convert into a list comprehension (one line) format if possible
for col in col_names:
    if col not in df.columns:
        df[col] = 0

# Re-order the columns into the correct order
df = df[col_names]

print(df)

A: A list comprehension would produce a list. You don't want a list, you want to add columns to your dataframe. List comprehensions should not be used for side effects, ever.
You can however, produce the columns you want to add as a list and use advanced indexing to assign all the columns at the same time:
df[[col for col in col_names if col not in df.columns]] = 0


text:
Q: Can we show 0 instead of negative values in hyperion planning dimensions? The requirement is to display zero or nothing when the value in a cell negative?

A: It's simple- try a CASE construct.
SELECT CASE
           WHEN myColumn < 0 THEN 0 -- or NULL
           ELSE myColumn
       END AS myColumnAlias
  FROM myTable
 WHERE <myConditions>

A: A couple years late. Hope you already figured it out.
As for your question, I believe the only solution would be to create a business rule/calc script that would check all existing data and overwrite negative values with 0. Please make sure:

*

*use dense dimension member on the left side of the equation to ensure the performance and not create unnecessary blocks.

*turn FRMLBOTTOMUP ON; since you only execute this calculation on existing data so it is safe and faster to use this command.


text:
Q: Stargate Universe blunder: whey do they keep talking about Naquadria when it should be Naquada...? I can't be the only one to notice that in Stargate Universe they keep talking about Naquadria when it should be Naquada, because, as far as I'm aware, Naquadria only existed on Langara, Jonas Quinn's homeworld, after experiments done by a Goa'uld named Thanos. That's when we learn it's not naturally occurring anywhere in nature, yet in SGU we are on planets with a Naquadria core. Is this a major oversight on the writers part, forgetting their own lore? Because this is a huge mistake on their part, and it drives me mad every time I watch it.

A: I think you've fundamentally misunderstood what's happening here. Langara has been tampered with by a Goa'uld in order to turn a seam of naquada into a seam of naquadria, using crystal technology similar to that employed by the Tok'Ra.
Jonas is convinced that naquadria can only be found on his planet...

JONAS: We found a reference to a process the Goa'uld discovered which allowed them to convert raw Naquada into Naquadria while it's still in the ground. Now somehow it started a change reaction which has continued on down through the veins getting deeper and deeper and deeper, and we believe that the process is ongoing.
...
You know for the longest time I was wondering why we never found any naquadria anywhere else in the galaxy and now I'm thinking it's because it doesn't exist in nature at all.

...but he is, in fact, incorrect. There are multiple planets in the universe with naquadria cores, including Dr. Rush's 'Icarus' planet (P4X-351), another planet located by the Lucian Alliance (which comes complete with a pyramid, indicating that it possibly belonged to the same Goa'uld that was experimenting on Jonas' world) and a planet found in the galaxy that the Destiny is currently mapping.

KIVA: Similar naquadria deposits. We had some issues adapting the equations, but there should be enough power to get us there.
RUSH: You've found another Icarus planet.
SGU: Subversion

And

RUSH: Yeah. We now have data on literally thousands of Gates that have already been seeded. Only managed to get through a fraction of it, but I found something quite interesting.
WALLACE: Woah! Almost the same mineral composition as the Icarus planet.
SGU: Life


text:
Q: Amarok in KDE and Banshee in gnome I want to do something to prevent Banshee from start in KDE (even accidentally)
Edit: I want to do somehow lock the banshee in KDE. (/bin/banshee be only valid in gnome.)

A: To hide banshee from the menu's in KDE you'll need to change the desktop file to only show the menu item in Unity/Gnome
mkdir -p ~/.local/share/applications
cp /usr/share/applications/banshee.desktop ~/.local/share/applications

Edit the file ~/.local/share/applications/banshee.desktop
Add to the bottom of this file
OnlyShowIn=GNOME;Unity;

Save.
However the above only hides banshee.  To prevent banshee from starting in KDE you'll need to edit the banshee executable script
sudo nano /usr/bin/banshee

now add the following at the position shown:
if [ x"$KDE_FULL_SESSION" = x"true" ]; then
  exit
fi


text:
Q: GRUB freezes when I reboot with usb mouse connected I'm running EFI dual-boot with windows 10 and Ubuntu 20.04.
HP Spectre with NVIDIA graphics card.
The problem only happens if I boot up and there is a flash drive or any device connected to the USB port. GRUB freezes and stays there. I have to force reboot the computer and remove the device, only that way it would boot up normally

A: I was having the same problem. I tried to disable the USB boot option from BIOS, but it did not work. To solve the problem I used the efibootmgr command.
First I ran sudo efibootmgr to see the current boot options. Mine was correctly set to start from ubuntu and USB Drive was the last one, so I don't know how the problem was occurring on the first place. Then I sudo efibootmgr -b <USBbootnum> -A to make the USB Drive option inactive. This worked for me. After reboot the computer the USB Driver option became active again (don't know why), but the problem went way.

A: Doing further research, I was able to notice that the problem happened with a specific brand of mice. Logi devices(Logitech). I was able to reach out to them and submit a report. Apparently their USB dongle contained some sort of firmware that would trigger some bug in the BIOS at bootup.
They weren't able to fix the issue for me since the bug report error was tedious and I thought moving forward with that process was going to be extensive.
Solution, I bought a mouse from a different brand. It works perfectly.

A: I had the exact same issue on an HP Spectre x360 laptop. Grub would freeze if any USB device was connected at startup (Logitech or other). Fixed by updating the BIOS firmware of the laptop.


text:
Q: Integral of complex variable I have to calculate integral:
$$\int_{- \infty}^{\infty} \cfrac{\cos(z - \cfrac{1}{z})}{1 + z^2} dz$$
It is relay converge to $\cfrac{\pi}{e^2}$, but I have lost some opportunity to find solution.
EDIT: This was the OP's deleted attempt.

I have tried to reduce to:
$$\int_{- \infty}^{\infty} \cfrac{\cos(z - \cfrac{1}{z})}{1 + z^2} dz= \Re \left( \int_{- \infty}^{\infty} \cfrac{\exp(i(x-1/x))}{1+x^2} dx \right) = $$
$$= \Re \left( \oint - \int_{0}^{\pi} \cfrac{\exp \left( i \left( \epsilon \exp(i \phi)  - \cfrac{1}{\epsilon \exp(i \phi)} \right) \right)}{1+\epsilon^2 \exp(2 i \phi)}d\phi - \int_{\pi}^{0} \cfrac{\exp \left( i \left( R \exp(i \phi)  - \cfrac{1}{R\exp(i \phi)} \right) \right)}{1+R^2 \exp(2 i \phi)}d\phi \right) = $$
$$\Re \left( - \int_{0}^{\pi} \cfrac{\exp \left( i \left( \epsilon \exp(i \phi)  - \cfrac{1}{\epsilon \exp(i \phi)} \right) \right)}{1+\epsilon^2 \exp(2 i \phi)}d\phi + \int_{0}^{\pi} \cfrac{\exp \left( i \left( \cfrac{1}{\epsilon} \exp(i \phi)  - \cfrac{\epsilon}{\exp(i \phi)} \right) \right)}{1+\cfrac{1}{\epsilon^2} \exp(2 i \phi)}d\phi \right)$$
or another way:
$$\int_{- \infty}^{\infty} \cfrac{\cos(z - \cfrac{1}{z})}{1 + z^2} dz = \oint - \int_{0}^{\pi} \cfrac{\cos\left( i \left( \epsilon \exp(i \phi)  - \cfrac{1}{\epsilon \exp(i \phi)} \right) \right)}{1+\epsilon^2 \exp(2 i \phi)}d\phi - \int_{0}^{\pi} \cfrac{\cos\left( i \left( R \exp(i \phi)  - \cfrac{1}{R\exp(i \phi)} \right) \right)}{1+R^2 \exp(2 i \phi)} d\phi =$$
$$ \pi \cosh(2) -  \int_{0}^{\pi} \cfrac{\cos\left( i \left( \epsilon \exp(i \phi)  - \cfrac{1}{\epsilon \exp(i \phi)} \right) \right)}{1+\epsilon^2 \exp(2 i \phi)} d\phi$$
I don't exclude, that i have done a mistake, but it way i have tried.


text: Q: Detect Browser Forward OR Backward Click Event My question is this: Is it possible to detect which browser navigation button was clicked, the forward button or the back button. I am aware of the 'popstate" API but it seems to only show that one of the navigation buttons was clicked and doesn't differentiate which one was clicked. Is there a definitive way to detect which browser navigation button is clicked?


text:
Q: Why does using tabular inside of chemfig's chemname alter the vertical position of the text? chemfig offers the \chemname  command that allows us to add an annotation (name, number,...) to a chemical compound. To save space and avoid repetition when dealing with similar compounds, "R"  is often used instead of a more specific substituent. "R" is usually defined below the compound. For this, I tried to use the \chemname{<compound>}{>name>} command, but with a  tabular in the <name> part of the command.
While the horizontal alignment looks as expected, the vertical alignment is off, if compared to compounds that are named without using a tabular. (See image below, left: with tabular, middle and right: without tabular). An alternative, that does not alter the vertical position of the text would be using a \parbox, but this approach requires determining the width of the text in order to get it centered below the molecule and it does not allow for the same column-like alignment of substituents and numbers, that a tabular does.

What causes this additional white space above text inside of a tabular and is there a better way to achieve the desired output?
Here is the code used to create the screenshot shown above.
\documentclass{report}
\usepackage{chemfig}

\begin{document}

\schemestart
    \chemname{\chemfig{R-OH}}
             {{\begin{tabular}[t]{l@{\;}l}
               R = \textit{n}-Bu: & 1a\\
               R = Et: & 1b\\
             \end{tabular}}}
    \chemname{\chemfig{Me-OH}}
             {2}
    \chemname{\chemfig{R-OH}}
             {\parbox{2.25cm}{R = \textit{n}-Bu:  1a\\ R = Et:  1b\\}}
\schemestop

\end{document}

Related: https://tex.stackexchange.com/a/605961/134144

A: How about this?

\documentclass{report}
\usepackage{chemfig}
\begin{document}
\schemestart
\begin{tabular}{ccc}
\chemfig{R-OH}
&
\chemfig{Me-OH}
&
\chemfig{R-OH}
\\
\begin{tabular}[t]{l@{\;}l}
 R = \textit{n}-Bu: & 1a\\
 R = Et: & 1b
\end{tabular}
&
2
&
\parbox[t]{2.25cm}{
 R = \textit{n}-Bu: 1a\\
 R = Et: 1b
}
\end{tabular}
\schemestop
\end{document}


text: Q: Is there a way to disable all browsers exept Firefox in Javascript i have been running into some Problems on my website and now i want to block all browsers exept firefox at least till i fix the issues


text:
Q: Made a simple chatbot. How to differentiate "hi" as greetings from words including "...hi..."? I have created a simple chatbot and so far it is working good. The problem is, if I type for example "hibernate", the script will recognize this as a greetings. I am German and we have a lot of words containing "hi".
This is my Python code:
import json
import random

eingabe = input('DU: ')
eingabe = eingabe.lower()

with open('ebaykleinanzeigen\intents.json') as file:
    data = json.load(file)

for intent in data['intents']:
    for pattern in intent['patterns']:
        if pattern in eingabe:
            antwort = random.choice(intent['responses'])
            print(antwort)

    def getReply(eingabe):
        for intent in data['intents']:
            for pattern in intent['patterns']:
                if pattern in eingabe:
                    antwort = random.choice(intent['responses'])
                    print(antwort)

while 'beenden' not in eingabe:
    eingabe = input('DU: ')
    eingabe = eingabe.lower()
    getReply(eingabe)

And this is my JSON file:
{"intents": [
    {"tag": "gruessen",
     "patterns": ["hi"],
     "responses": ["Hi!"]
    }
]
}

Thanks in advance.


text:
Q: Gnuplot bad data on line 1 Well, I am getting the error
    gnuplot> plot "plot_error.p"
                  ^
             Bad data on line 1

when trying to execute the plotting script plot_error.p on the following datafile (tesc_error.dat)
    2       0.02373300      0.00187922
    3       0.12182900      0.01080161
    4       0.30066000      0.02936487
    5       0.88415600      0.07882007
    6       1.70864800      0.14576794
    7       4.11814900      0.44127670
    8       8.79967900      0.84273207
    9       22.09179700     2.25049799
    10      54.13644000     5.28557289
    11      164.75478299    20.67593118
    12      376.32501997    39.98897077
    13      807.50995700    82.47956624

The script is
    set encoding iso_8859_1
    set terminal postscript eps enhanced color solid
    set xrange[1:14]
    set yrange[0:900]
    set title "1D MFPT"
    set xlabel "{/Symbol G}"
    set ylabel "t_{esc}"
    unset key

    set output "tesc_error.eps"

    y(x)=1/(9*x**(2/3))*exp(x-1)

    plot "tesc_error.dat" with yerrorbars, y(x) lt rgb "blue"

    set key

The most weird thing is that I have recently plotted it without errors, but suddenly it pops that error. I've inspected line 1 of the datafile and nothing seems strange in it.

A: The issue is that you call a script with the plot command.
Try:
load "plot_error.p"

instead.
The plot command expects a data file and not a script.