text:
Q: MS ACCESS 2010 Syntax error (missing operator) in query expression in List Box I have made a List Box in MS Access 2010. I am using this query for showing up only distinct values from the column (AOM) from which the List Box is getting data:
SELECT [Exhibit Recording].ReferenceNo, DISTINCT [Exhibit Recording].AOM
FROM [Exhibit Recording];

Now When I am using this an error "syntax error (missing operator) in query expression 'DISTINCT [Exhibit Recording].AOM'." keeps popping up, but disappears when I remove DISTINCT.
Is there any way to have distinct values in a list box and not get that error?
I also tried using:
SELECT DISTINCT [Exhibit Recording].AOM
FROM [Exhibit Recording];

The query runs fine, but the text in the listbox disappears and when you click on it it shows a dark band to show that something has been selected. Any way of getting around this ?

A: As you have discovered, Access SQL does not support queries of the form
SELECT x, DISTINCT y FROM z

If you haven't done so already, try
SELECT DISTINCT [Exhibit Recording].ReferenceNo, [Exhibit Recording].AOM FROM [Exhibit Recording];

(Notice that DISTINCT immediately follows SELECT. Access SQL supports DISTINCT across the entire query, but not on individual columns.)
If that doesn't give you distinct values for [AOM] and you really need them then you'll have to use a GROUP BY query that arbitrarily chooses a [ReferenceNo] to go along with each [AOM] value:
SELECT First([Exhibit Recording].ReferenceNo), [Exhibit Recording].AOM FROM [Exhibit Recording] GROUP BY [Exhibit Recording].AOM;


text:
Q: drawing a point over an image on QLabel I displayed a picture on QLabel and wanted to take coordinates and paint a point on image on mouse click event. I am able to get coordinates but painter is painting point below my image on label, i want it above my image.
My code is :
main.cpp
#include "imageviewer.h"
#include <QApplication>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    imageviewer w;
    w.showMaximized();

    return a.exec();
}

imageviewer.h
#include <QPushButton>

class imageviewer : public QLabel
{
    Q_OBJECT

public:
    explicit imageviewer(QWidget *parent = 0);

private slots:

    void mousePressEvent(QMouseEvent * e);
    void paintEvent(QPaintEvent * e);

private:

    QLabel *label1 ;
    int mFirstX;
    int mFirstY;
    bool mFirstClick;
    bool mpaintflag;

};

#endif

imageviewer.cpp
#include <QtGui>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include "imageviewer.h"
#include <QDebug>

imageviewer::imageviewer(QWidget *parent)
    : QLabel(parent)
{

    label1 = new QLabel;
    label1->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    QPixmap pm1("/home/nishu/Pictures/img_0002.jpg");
    label1->setPixmap(pm1);
    label1->adjustSize();
    label1->setScaledContents(true);

    QHBoxLayout *hlayout1 = new QHBoxLayout;
    hlayout1->addWidget(label1);

    setLayout(hlayout1);
}

void imageviewer :: mousePressEvent(QMouseEvent *e)
{
    mFirstX=0;
    mFirstY=0;
    mFirstClick=true;
    mpaintflag=false;

    if(e->button() == Qt::LeftButton)
            {
                //store 1st point
                if(mFirstClick)
                {
                    mFirstX = e->x();
                    mFirstY = e->y();
                    mFirstClick = false;
                    mpaintflag = true;
                    qDebug() << "First image's coordinates" << mFirstX << "," << mFirstY ;
                    update();

                }

            }
}

void imageviewer :: paintEvent(QPaintEvent * e)
{

    QLabel::paintEvent(e);

    if(mpaintflag)
    {
               QPainter painter(this);
               QPen paintpen(Qt::red);
               paintpen.setWidth(10);
               QPoint p1;
               p1.setX(mFirstX);
               p1.setY(mFirstY);
               painter.setPen(paintpen);
               painter.drawPoint(p1);
            }

}

Help me to sort out what exactly problem is?

A: with line QPainter painter(this); you set QPainter to draw on your main widget instead of QLabel's pixmap. Change block to this and it will work:
if(mpaintflag)
    {
           QImage tmp(label1->pixmap()->toImage());
           QPainter painter(&tmp);
           QPen paintpen(Qt::red);
           paintpen.setWidth(10);
           QPoint p1;
           p1.setX(mFirstX);
           p1.setY(mFirstY);
           painter.setPen(paintpen);
           painter.drawPoint(p1);
           label1->setPixmap(QPixmap::fromImage(tmp));
    }

EDIT:
Just noticed, that you derived from QLabel, not from QWidget, as i assumed automatically, looking at layout. Indeed, you don't need label1 and layout inside of our imageviewer class. That whole point of subclassing is that you implement behavior and filter events the way you want it and then you add them to main widget if that is needed
EDIT2:
Imageviewer class should be derived from QLabel, remove label1 and layout, and paint not on image, but on imageviewer itself, i.e. this. Then you need to add new class to your program, which is derived from QMainwindow or QWidget for example, where you should include your imageviewer class, create layout and add your class to it like this:
#include "imageviewer.h"
//.... somewhere in constructor ....
imageviewer *viewer1=new imageviewer(this); // creating new object of imageviewer
viewer1->setPixmap(...);
hlayout1->addWidget(viewer1);

A: You derived your class from QLabel, so you should not create another QLabel *label1 and put it inside label's layout. That doesn't make any sense. Why would anyone put a label into a label? You need to remove label1 and use the imageviewer object as a label instead. Your constructor should contain only the following code:
setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
QPixmap pm1(...);
setPixmap(pm1);
adjustSize();
setScaledContents(true);

I've checked that it fixes your problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to test Scala macros? What is the proposed way of performing tests on scala macros?
I realize that one needs two projects due to the necessity of separate compilation. This step, if necessary, is acceptable and mostly clear.
But how do you assert a macro expansion fails when it should? Without some special facility, the test case won't compile and therefore the whole test project won't compile.
I think this assert would require another macro of the form
errors(code: => _): List[CompileError]

which returns the compile errors of the inner macro. The same would be required for testing that warnings occur if they should and so on...
Are there some existing testing facilities for Scala macros?

A: You can use assertDoesNotCompile from ScalaTest. Here is an example of using this to test the Scala typechecker:
import org.scalatest.FunSuite

class TypeTest extends FunSuite {
  test("String vals can't hold ints") {
    assertDoesNotCompile("val x: String = 1")
  }
}

You can pass a string containing an example of when your macro expansion should fail to assertDoesNotCompile. Note that that there is also assertCompiles, if you feel the need for that.

A: you could use twitter eval to check if the code copiles
https://github.com/twitter/util/blob/master/util-eval/src/main/scala/com/twitter/util/Eval.scala#L247


text:
Q: Swift add a new property to Model I have a model that I set after receiving data from the server.
public struct Model1: Codable {
    let type1: String
    let type2: Int
    let type3: String
}

But model1 (also model2 and model 3, but will not duplicate the code) is missing one property that I want to add dynamically.
So I change the model to
public struct Model1: Codable {
    let type1: String
    let type2: Int
    let type3: String
    var missingType: String
}

The models are stored in the enum as an associated value.
public enum WalletSection {
    case model1(items: [Model1])
    case model2(items: [Model2])
    case model3(items: [Model3])
}

Once I want to set the value I am trying to do the following:
switch section {
case .model1(let items):
case .model2(let items):
case .model3(let items):
    for item in items {
        item.missingType = setMissingType()
    }
}

And the error I have is: Cannot assign to property: 'item' is a 'let' constant. So the values in the enum are constant and I can not change them.
I also tried to add mutating func setType(), but it also does not work.
So any ideas how can I set this missing property in my model?

A: Just set the item in loop as var : But the result is that is work only if model is a class :
// This is just to show you how to declared method
// that work on struct/class in protocol extension
protocol MissingType {
    // struct/class must have a property named
    // missingType (can be computed var or not)
    var missingType: String {get set}
}

// a extension so that all models with this protocole
// (ie having a missingType property) can use
// this function
extension MissingType {
    mutating func setMissingType(str: String) {
        self.missingType = str
    }

    func printMissingType() {
        print("Missing type : \(self.missingType)")
    }

}

struct testModels {
    public class Model1: Codable, MissingType {
        let type1: String
        let type2: Int
        let type3: String
        var missingType: String
        init(type1: String, type2: Int, type3: String, missingType: String) {
            self.type1 = type1
            self.type2 = type2
            self.type3 = type3
            self.missingType = missingType
        }
    }
    public struct Model2: Codable {
        let type1: String
        let type2: Int
        let type3: String
        var missingType: String
        func printMissingType() {
            print("Missing type : \(self.missingType)")
        }
    }

    public struct Model3: Codable {
        let type1: String
        let type2: Int
        let type3: String
        var missingType: String
        func printMissingType() {
            print("Missing type : \(self.missingType)")
        }
    }

    public enum WalletSection {
        case model1(items: [Model1])
        case model2(items: [Model2])
        case model3(items: [Model3])

        func setMissingType() -> String {
            return "MT"
        }
    }

    func test() {
        func setMissingType() -> String {
            return "MT"
        }
        let section1 = WalletSection.model1(items: [Model1(type1: "t1", type2: 2, type3: "3", missingType: "mt"), Model1(type1: "t12", type2: 22, type3: "23", missingType: "m2t")])
        let section2 = WalletSection.model2(items: [Model2(type1: "2t1", type2: 222, type3: "3", missingType: "mt2"), Model2(type1: "t12", type2: 22, type3: "23", missingType: "m2t3")])

        for section in [section1, section2] {
            switch section {
                case .model1(let items):
                    print("modify section1")
                    // this use a function not declared in the type model1
                    for var item in items {
                        item.setMissingType(str: "11111")
                    }
                    print("items : \(items)")
                case .model2(let items):
                    print("modify section2")
                    for var item in items {
                        item.missingType = setMissingType()
                    }
                case .model3(let items):
                    for var item in items {
                        item.missingType = setMissingType()
                    }
            }
        }

        for section in [section1, section2] {
            switch section {
                case .model1(let items):
                    // here value has been modified
                    items.first?.printMissingType()
                case .model2(let items):
                    // here value was not modified
                    items.first?.printMissingType()
                case .model3(let items):
                    items.first?.printMissingType()
            }
        }

    }

}

let b = testModels()
b.test()

Hope this can help you


text:
Q: How to configure sonar-project.properties for multiple languages(Python and html)? I am setting up Sonarqube for one of my projects which is a mix of Python and Html. I am able to configure the project separately for either of these languages but not together. Is there any way to do this? I tried the following scenario
1)sonar.language is commented in sonar-project.properties
sonar.projectKey=DemoProject
sonar.projectName=Demo Project
sonar.projectVersion=1.0
sonar.sources=.
Sonar.language is commented
#sonar.language=py,web
Output: - But Sonarqube is only analyzing the html (web) files
Can anyone suggest how to configure sonar-project.properties for multiple languages(Python and html)?


text:
Q: What's the difference between segregate and separate as verb? 1 segregate somebody (from somebody) to separate people of different races, religions, or sexes and treat them in a different way
a culture in which women are segregated from men
Whites and blacks were segregated into different parts of town.
a racially segregated community
a segregated school (= one for students of one race or religion only)
opposite integrate
2 segregate something (from something) to keep one thing separate from another
In all our restaurants, smoking and non-smoking areas are segregated from each other.

A: All segregation is separation, but of a particular kind, that of dividing some group into different segments based on some criterion, so a hospital administrator would say

We segregate those with communicable diseases from the rest of the patient population.

This reflects the word's origin from the Latin grex meaning flock.  Separate would work as well.
Separate means generally to divide, so a geographer would say

The Mississippi River separates the United States into east and west.

Segregates would be inapt here.

A: Originally, the difference was that separate meant to take two or more classes of things or people and put them in different places. But segregate meant to take one of these classes and isolate it from all the others.
This was the meaning even before racial segregation was instituted (so you can see that the very word segregation implied that the two races were not treated equally).
From Webster's original 1828 dictionary:

segregate: to separate from others; to set apart.
separate: To disunite; to divide; to sever; to part, in almost any manner, either things naturally or casually joined.

A: In all our restaurants, smoking and non-smoking areas are segregated from each other.
I can't agree this is standard usage at all, for a number of reasons:

*

*Firstly (and obviously) the policy statement is tautologous (if there are smoking and non-smoking areas then they would be separate, you would expect)

*So you would simply say: "In all our restaurants there are smoking and non-smoking sections."

*Segregate / segregated / segregation are very loaded words (with a lot of political baggage), and would not (or should not) be used in the context of a restaurant policy about smoking

So for the avoidance of unwanted political overtones, "separate" is usually the safer word to use for putting or keeping two people (or two objects) apart - "segregate" should be used very cautiously in quite specific ways.  And "integrate" is the antonym of "segregate" only in very specific cases as well.


text:
Q: Best Mobile Game Engine to make a casual game similar to Breakout and Billiards In your opinion, what is the best mobile game engine to make a game like this:
There is a menu. From the menu you go to the level selection. The level select scene knows what levels you have completed because of a variable saved on the device (maybe in the cloud).
You select a level. It goes to what level you selected.
There is a ball in the middle of the screen, you can touch anywhere and the ball will start off in that direction. It will bounce of walls, but never slow down. Once you have completed the stage, or you have failed, a screen will pop up with the options to either restart the game, go back to the menu or continue to the next level (if you passed).
That is the basic overview of the game I want to make (without giving away too much detail). I am trying to do this with Corona SDK, but Corona's Storyboard API is pretty hard to do if you want to be able to go from the level select to the game and repeat that over and over again.
Please only suggest engines that have good documentation.
Otherwise, any game engine would do as long as it has a free option.

A: Honestly , There are tons of mobile engines out there that can help you get the job done. Knowing that it's huge and vast, I find Unity as your best bet. It makes implementing the menu easier and plus you can make menus pretty easily. In addition to that, It also now offers 2D support which I think helps you achieve your goal pretty easily with free mobile deployment.
Alternatives to Unity are :
Corona - Which you have already tried
App Game Kit - Which is also amazing : http://www.appgamekit.com/
I find those engines the three best engines for the game your looking to build since it's easy and needs some fast mobile game development engines.
You can also try some WYISWYG programming environments such as Scirra's Construct 2.
Hope you find that useful.

A: V-Play (I am part of the developer team), a cross-platform 2D game engine, has a breakout demo game template that you can take as a base for your game. There is also a tutorial and template that shows scene and level switching that will be helpful.
The engine is not free, but it has a free trial version where you can test it.

A: If you are using C++ you could try Oxygine 2D framework. It could be build on top of SDL2 or Marmalade.

A: You might also want to try GameSalad (I'm one of the co-founders).  It's a cross platform 2D game engine and drag and drop development tool. On the manuals page there an example project called Crazy Wall Breaker which is a Breakout clone and I know there's a billiards template floating around somewhere.


text:
Q: building a Jquery Tool slider like yahoo.com slider details Hi im trying to achieve a "news slider" like the one you can see in yahoo.com... I almost have the 100% of the code.. (if you want to compare them here is my code http://jsfiddle.net/PcAwU/1/)
what is missing in my code , (forget about design) is that , In my slider you have to clic on each item, i tried to replace Onclick for Hover on the javascript, it worked, but the fisrt image on the gallery stop working, so when you just open the slider, you see a missing image.
Other point.. also very important, in yahoo.com after "x seconds" the slider goes to the next item, and so on ... all the Thumnails are gruped 4 by for 4, (in mine 5 by 5, thats ok) ... after pass all the 4 items, it go to the next bloc..
HOW CAN I ACHIEVE THAT!!. I really looked into the API, everything, really im lost, i hope someone can help me. cause im really lost in here.
Thanks
Here is the script
$(function() {
var root = $(".scrollable").scrollable({circular: false}).autoscroll({ autoplay: true });

$(".items img").click(function() {
    // see if same thumb is being clicked
    if ($(this).hasClass("active")) { return; }

    // calclulate large image's URL based on the thumbnail URL (flickr specific)
    var url = $(this).attr("src").replace("_t", "");

    // get handle to element that wraps the image and make it semi-transparent
    var wrap = $("#image_wrap").fadeTo("medium", 0.5);

    // the large image from www.flickr.com
    var img = new Image();

    // call this function after it's loaded
    img.onload = function() {

        // make wrapper fully visible
        wrap.fadeTo("fast", 1);

        // change the image
        wrap.find("img").attr("src", url);

    };

    // begin loading the image from www.flickr.com
    img.src = url;

    // activate item
    $(".items img").removeClass("active");
    $(this).addClass("active");

// when page loads simulate a "click" on the first image
}).filter(":first").click();

// provide scrollable API for the action buttons
window.api = root.data("scrollable");

});

function toggle(el){
    if(el.className!="play")
    {
        el.className="play";
         el.src='images/play.png';
        api.pause();
    }
    else if(el.className=="play")
    {
        el.className="pause";
         el.src='images/pause.png';
        api.play();
    }

    return false;
}

A: To fix the hover problem you need to make some quick changes: Change the click to a on(..) similar to just hover(..) just the new standard.
$(".items img").on("hover",function() {
....

Then You need to update the bottom click event to mouse over to simulate a hover effect. Trigger is a comman function to use to trigger some event.
}).filter(":first").trigger("mouseover");

jSFiddle: http://jsfiddle.net/PcAwU/2/

Now to have a play feature, you need a counter/ and a set interval like so:
var count = 1;
setInterval(function(){
    count++; // add to the counter
    if($(".items img").eq(count).length != 0){ // eq(.. select by index [0],[1]..
        $(".items img").eq(count).trigger("mouseover");
    } else count = 0; //reset counter
},1000);

This will go show new images every 1 second (1000 = 1sec), you can change this and manipulate it to your liking.
jSFiddle: http://jsfiddle.net/PcAwU/3/

If you want to hover the active image, you need to do so with the css() or the addClass() functions. But You have done this already, All we have to do is a simple css change:
.scrollable .active {
    ....
    border-bottom:3px solid skyblue;

Here is the new update jSFilde: http://jsfiddle.net/PcAwU/4/


text:
Q: Call airdrop contract method keep report error "Error: Transaction ran out of gas. Please provide more gas" I had deployed a ERC20 token on ropsten testnet MyToken
. Now I want to send my token to multiple addresses. After google and some research I found OMG Airdropper may work. So i deployed airdrop on ropsten with the same key as MyToken contract.
I use web3js invoke 'multisend' method on airdrop contract, but got error:
(node:70819) UnhandledPromiseRejectionWarning: Error: Transaction ran out of gas. Please provide more gas:

Checked transaction receipt "gasUsed" is not exceed gasLimit:
{
 "blockHash":
 "0xb14df1fda48c44adb75249b46921b0a2889325ccd5335fc4282206a6731d03ed",
 "blockNumber": 3423377,
 "contractAddress": null,
 "cumulativeGasUsed": 1440969,
 "from": "0x7b4d9ef0740f75dbc79222a323246a3659609896",
 "gasUsed": 30479,
 "logs": [],
 "logsBloom": "0x...many 0",
 "status": false,
 "to": "0xcf3afc7e21da35559269f7503b843ac543392ae0",
 "transactionHash":
 "0x53c7b6842308dec6be5ced3fd1cbb53848c73161da1eb0cfb323c3eb847eebd7",
 "transactionIndex": 15
 }

test code:
var fs = require('fs');
var parse = require('csv-parse');
var Web3 = require('web3');
var abi = require('./abi.json');
var _ = require('lodash');
const Tx = require('ethereumjs-tx');

var web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/secure_key"));
var inputFile = 'smalldata.csv';

const main = async (addrs, tokens) => {
    console.log(`web3 version: ${web3.version}`)

var contractJson = abi.abi;
var tokenAddress = "0x57fdf8001d1c240d4cbfc82b2fede932960dc310";
var myAddress = "0x7b4d9ef0740f75dbc79222a323246a3659609896";
var privateKey = "81d4f6e4b9d628fa15a9ff98f610e87d2662348c5666a7bf0fc39edf74f27b38";
var abiArray = abi.abi;
var contractAddress = "0xCF3aFC7e21Da35559269F7503b843ac543392aE0";

var count = await web3.eth.getTransactionCount(myAddress);
console.log(`num transactions so far: ${count}`);

var contract = new web3.eth.Contract(abiArray, contractAddress, {
    from: myAddress
});

var rawTransaction = {
    "from": myAddress,
    "nonce": "0x" + count.toString(16),
    "gasPrice": "0x003B9ACA00",
    "gasLimit": "0x200B20",
    "to": contractAddress,
    "value": "0x0",
    "data": contract.methods.multisend(tokenAddress, addrs, tokens).encodeABI(),
    "chainId": "0x03",
    "gas": "0x30D40"
};

var privKey = new Buffer(privateKey, 'hex');
var tx = new Tx(rawTransaction);
tx.sign(privKey);
var serializedTx = tx.serialize();

console.log(`Attempting to send signed tx:  ${serializedTx.toString('hex')}`);
var receipt = await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'));
console.log(`Receipt info:  ${JSON.stringify(receipt, null, '\t')}`);
}

var parser = parse({
delimiter: ','
}, function (err, data) {
let addressList = [];
let tokensList = [];
for (let i = 0; i < data.length; i++) {
    addressList.push(data[i][0]);
    tokensList.push(data[i][1]);
}

let addrsList = _.chunk(addressList, 2);
let tokenList = _.chunk(tokensList, 2);

main(addrsList[0], tokenList[0]);
});

fs.createReadStream(inputFile).pipe(parser);

sorry for not proper format code. Format well code at code on gist
csv data is:
0x7710f02222Ae6B4b2C308d98526B1D719D6ff2D5,188
0x34dB0eaDFfFE6ed5C4458badCA042F79ECF2a2A7,128
0xb3d475eB29E4fa88D5dB40d29D1AEa6A3C5cB3C9,288
0x5875A89a2043F0eAA858a26610fF58B4f5514e52,188

Any suggestion or help will be helpful. Thanks.


text:
Q: Can I return true to asp.net OnClientClick After an Ajax call? Or maybe some other way? I m using Ajax call to check whether a user has logged in or not. If not, show login dialog; else I want OnClientClick to return true so that the form will submit. I m thinking about using a global variable and check it until Ajax gives it a value... I am not sure whether it is the right way? Thanks!
(the server side code already works)
in .ascx:
<asp:Button ID="buttonSubmit" Text="Submit" OnClientClick="return buttonSubmitOnclick()" OnClick="buttonSubmit_Click" runat="server"/>

in .js:
function buttonSubmitOnclick() {
  showLogin();
  //What to do here??? how to get the result after the ajax call?
}

//========== Ajax ==============

function showLogin() {
  var xmlhttp;

  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
  }
  else {// code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        if (xmlhttp.responseText == "false") {
            $find('modalPopupLogin').show();  //Show Login Dialog
        };//else is it possible to return a true to buttonSubmitOnclick?
    }
  }
  xmlhttp.open("GET", "AjaxService.aspx?t=auth", true);
  xmlhttp.send();
}

A: when the condition satisfy, you can submit the form manually on response of ajax call using document.forms['myForm'].submit().
Make the button as normal button(not submit button) and remove the return before the function call in the button element and then do as below:
function buttonSubmitOnclick() {
  showLogin();
  }

//========== Ajax ==============

function showLogin() {
  var xmlhttp;

  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
  }
  else {// code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
        if (xmlhttp.responseText === "false") {
            $find('modalPopupLogin').show(); // display the pop up
        }else{
        document.forms['myForm'].submit() // else submit the form,'myForm' is form id'
            }
    }
  }
  xmlhttp.open("GET", "AjaxService.aspx?t=auth", true);
  xmlhttp.send();
}


text:
Q: For an application using Log4J (not SLF4J) how to swap the underlying implementation for something we are developing internally? So I have a large application using log4j. We are developing internally our own log implementation, that has nothing to do with log4j, but it conforms to the log4j API for logging. Therefore we just want to somehow swap log4j for our log implementation without changing anything in our code, in other words, it will continue to use the log4j API with our log implementation under-the-hood.
Has anyone done that or know how to go about doing that?
It would be easy if I was using SLF4J, but unfortunately I'm not.

A: Your best bet would be to write your custom logging framework as an slf4j implementation.
Then, remove log4j from the class path and drop in the log4j-over-slf4j bridge instead.
http://www.slf4j.org/legacy.html
The log4j-over-slf4j bridge will take any calls made to log4j and redirect through slf4j to whichever slf4j subsystem you're using on your classpath, which would in this case be your custom library.


text:
Q: Prove that if $na=mb$ and $(a,b)=1$, then $m=a$ and $n=b$. I'm sorry but I'm having a massive brain fart. I'm trying to show that if $na=mb$ and $(a,b)=1$, with $a,b,n,m \in \mathbb{N}$ of course, then $m=a$ and $n=b$.
Moving to $\mathbb{Q}_+$, we note that
$$\frac{a}{b}=\frac{m}{n}$$
but $a$ and $b$ are relatively prime, so the fraction on the left-hand side is irreducible. Therefore the right-hand side must be also irreducible (if not, reduce it until it is). Therefore $m=a$ and $n=b$.
This, of course, relies on the assumption that $(a/b)=(m/n)$ and $(a,b)=1$ implies that the numerators and denominators are equal, which is basically the same as the initial problem. I know I'm forgetting a super simple proof for this. Could you please tell me it, or at least hint me towards it?.

Edit: Oh and $m$ and $n$ are relatively prime.

A: Your claim is not true. There are infinitely many solutions for $m,n$:
Your assumption is that only the pair (a,b) is relatively prime. It does not stop the other pair  from having common factors: Now set $m=ka$ and $n=kb$; they satisfy $na=mb (=kab)$. This is valid for all integers $k$.

A: By the Bezout's identity, there are integers $r,s,p$ and $q$ such that
$$
ra+sb=1,\\
pm+qn=1.
$$
Multiplying the first equality by $n$ and using $na=mb$, we have
$$
n=rna+snb=rmb+snb=(rm+sn)b\implies b|n.
$$
Similarly, multiplying $1=pm+qn$ by $b$, we get
$$
b=pmb+qnb=pna+qnb=(pa+qb)n\implies n|b.
$$
Because $b$ and $n$ are both positive integers, we infer that $b=n$. From this, $a=m$ is immediate.

A: Yes, we can prove such uniqueness via principality of fractions. Applying the Theorem below,
$\quad\rm (m,n)=1\,$ and $\rm\ \dfrac{a}b\, =\, \dfrac{m}n\,\Rightarrow\ \begin{array}{} \rm a\, =\, \color{#c00}k\,m\\ \rm b\, =\, \color{#c00}k\,n\end{array}\ $ so $\rm\ (a,b)=1\,\Rightarrow\, \color{#c00}{k=1}.\ \ $ QED
Theorem $ $ For $\rm\:m,n,x,y\in \Bbb Z,\,$ if $\rm\ (m,n) = 1,\:$ then $\rm\ \dfrac{x}y\, =\, \dfrac{m}n\ \Rightarrow\:\begin{array}{c}x\, =\, k\,m\\ \rm y\, =\, k\,n\end{array}\ \ $ for some $\rm\ k\in \Bbb Z$
Proof $ $ By Euclid's Lemma, $\rm\ (n,m)=1,\ nx = my\,\Rightarrow\,n\mid y,\:$ so $\rm\ \dfrac{x}m = \dfrac{y}n = k,\:$ for some $\rm\:k\in \Bbb Z.$

A: I'll have a go at this with my small amount of knowledge from a first year proofs class lol.
Since $n = (mb /a)$, and $n$ is a natural number, $a$ has to either divide $m$ or $b$ evenly. However we stated that $b$ and $a$ are co prime, therefore $a$ has to divide $m$. Dividing both sides by $n$ would result in $1 = (mb/an)$. Since $a$ and $b$ are co prime, $m/n$ would have to be the reciprocal of $b/a$, resulting in $1$. Thus, $m = a$ and $n = b$.


text: Q: why there is difference in custom fonts of ios and android i'm using same font.ttf in ios and android. It is looking good in ios but in android, it seems slightly bold. same as fontlight.ttf looking good in ios but in android it is looking like regular. what is the problem with? is it of resolution or i'm missing something.


text:
Q: how to show hello world in react? I am using react-native using ES6 try to show 'hello world' why it is not display hello world text ..
here is my code
https://rnplay.org/apps/zFnEdg
'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

class PropertyFinderApp extends React.Component {
  render() {
    return React.createElement(React.Text, {style: styles.text}, "Hello World!");
  }
}

AppRegistry.registerComponent('PropertyFinderApp', () => PropertyFinderApp);

A: That's not working because you are using styles and styles is not even defined.
Also you have to import React from 'react' library and not from 'react-native', as you can see in the docs
Your code should look like this.
import React, {
  Component,
} from 'react';

import {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View
} from 'react-native';

const styles = StyleSheet.create({
    text: {
        fontSize: 20
    }
});

class PropertyFinderApp extends React.Component {
  render() {
    return (<View>
           <Text style={styles.text}> "Hello World!"</Text>
         </View>)
  }
}

AppRegistry.registerComponent('PropertyFinderApp', () => PropertyFinderApp);

Here you got your example in rnplay, check the android version for example.
rnplay


text:
Q: Find the right value of textbox I have a problem with inserting data inserting data into database.
 <asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1"   OnItemDataBound="Repeater1_ItemDataBound">
   <ItemTemplate>
     <!-- Some other data (text...) -->

     <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("PostId") %>' />

     <asp:TextBox ID="txtAddComment" runat="server" CssClass="textbox"  Width="200px" />
     <asp:Button ID="btnAddComment" runat="server" CssClass="button" Text="Comment"   CausesValidation="false" OnClick="btnAddComment_Click"/>
   </ItemTemplate>
</asp:Repeater>

Code behind:
 Protected Sub btnAddComment_Click(sender As Object, e As EventArgs)
        Dim HiddenField1 As HiddenField = DirectCast(Repeater1.Items(0).FindControl("HiddenField1"), HiddenField)
        Dim txtAddComment As TextBox = DirectCast(Repeater1.Items(0).FindControl("txtAddComment"), TextBox)
        Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString.ToString)
        Try
            If txtAddComment.Text = "" Then
                Exit Sub
            Else
                conn.Open()
                Dim cmd As SqlCommand = conn.CreateCommand()
                cmd.CommandText = "INSERT INTO Comments (PostId, UserName, CommentText) VALUES (@PostId, @UserName, @Text)"

                cmd.Parameters.Add("PostId", System.Data.SqlDbType.Int).Value = CInt(HiddenField1.Value)
                cmd.Parameters.Add("UserName", System.Data.SqlDbType.NVarChar).Value = Context.User.Identity.Name
                cmd.Parameters.Add("Text", System.Data.SqlDbType.NText).Value = MakeLink(HtmlRemoval.StripTagsCharArray(txtAddComment.Text))
                cmd.ExecuteNonQuery()
            End If

        Catch ex As SqlException
        Finally
            conn.Close()
        End Try
    End Sub

I display some text, under the text there is textbox and button for comments. I am bounding textId in hiddenfield for inserting comments. The code works fine, but I can only add comment for the first row in database displayed by repeater. When I want to add comment for other rows (2, 3...), the page refreshes and the text in the TextBox stay there.
It is problem with this line of code:
Dim txtAddComment As TextBox = DirectCast(Repeater1.Items(0).FindControl("txtAddComment"), TextBox)

The ID from HiddenField is right. But the code doesn't perform because the line above references for the first textbox on the page and his value is null.
When I change the line of code like this:
  Dim txtAddComment As TextBox = DirectCast(Repeater1.FindControl("txtAddComment"), TextBox)

It returns an error that Object reference not set to an instance of an object.
How to get the right textbox with right value?
Thanks for the answer

A: cast the sender to a button that sent it, then get the textbox from the parent.  Example:
Protected Sub button_click(ByVal sender As Object, ByVal e As EventArgs)
   Dim myButton As button= CType(sender, button)
   Dim myTextBox as TextBox = CType(myButton Parent.FindControl("buttonName"), TextBox)

end sub


text:
Q: Descriptions of sets and the Axiom of Choice If we specifically do not assume the Axiom of Choice, are all the sets that we can prove to exist specified by some finite formula? (All the other Zermelo-Frankel set theory axioms seem constructive to me, so I want to say yes, but I'm not sure.) If not, what's an example of such a set?
A slightly related questions: in a previous question I had about the Axiom of Choice, some of the answerers mentioned the distinction between a function and "a function you can name". Assuming the Axiom of Choice is basically assuming the existence of a function you can't name; are there examples of unnameable functions if we don't assume the Axiom of Choice? (Again, I want to say no, but I want to make sure.)

A: I believe that your first mistake is that the ZF theory is a lot less constructive then it seems. The axiom of choice in particular.
The answer to your first question is no. If something can be proved to exist, then you can write a formula defining the class of all sets which has this property. From this, however, you cannot say that every such set is definable. You cannot even have a canonical represntative which you can always use explicitly.
Here are some examples of sets that we cannot prove from ZF, or even ZF+Not AC:

*

*Andreas Blass proved in [1] that in ZF assuming that every vector space has a basis implies the axiom of choice, as a result if we assume that the axiom of choice does not hold then we can only tell that in our universe there is a vector space without a basis. We cannot actually define it, or even know over which field it is.

*When asserted, the axiom of choice tells us that every cardinal is an $\aleph$-number, and we have definable representative sets for each $\aleph$. That is there is a class function $C$ such that $C(X)=|X|$ and $C(X)=C(Y)\iff |X|=|Y|$. Such function may not be definable with the absence of choice. However, it may be definable depending on the universe. [2, Theorem 11.3]

*Assuming the axiom of choice itself does not hold, there are restricted versions of it (and there are many different ones) which are independent from one another, each asserting the existence of some sets that you cannot really define otherwise. Unless you specify exactly how much of the axiom of choice is violated there may be some choice hidden in your universe and you cannot prove that. [2, Chapter 8]

*In continuation from the last example, a universe of ZFC is in particular a universe of ZF without choice. If only specifying ZF, without an additional assumption that AC does not hold, it is possible that your universe is actually L, for example.
As for the second question, following from the first, we have that it is yes.
For example, take amorphous sets. These are infinite sets which cannot be written as a disjoint union of two infinite sets. Their existences violates the axiom of choice in a very strong way, as the axiom of choice implies that every infinite set can be written as a disjoint union of two parts equinumerous to the original set.
Suppose $A$ is an amorphous set. Then $A\in V$, and for some $\alpha$ we have that $A\in V_\alpha$ ($V_\alpha$ and $V$ are the von Neumann hierarchy).
It can be shown that the minimal $\alpha$ is a successor ordinal. Therefore for some $\beta$ we have $A\in V_{\beta+1}=\mathcal P(V_\beta)$. This means that there exists a partial function from $V_\beta$ bijective with this crazy set. Where does that happen in the hierarchy? How does the function look like? No one knows. It cannot be in the first $\beta=\omega$ levels, since in there everything is definably well ordered, but we cannot tell much more than that.
Of course that the axiom of choice, by definition, asserts that there are functions which exist and we cannot prove their existence otherwise. However as above shows, in its absence there are also functions which we cannot describe.

Bibliography:

*

*Blass A. Existence of bases implies the axiom of choice, (Axiomatic Set Theory (ed. J. E. Baumgartner, D. A. Martin, and S. Shelah) Contemp. Math. 31 (1984) 31-34).

*Jech T. The Axiom of Choice, North-Holland (1973).

A: There is a strange pathology that occurs when looking deeply at such questions. This pathology is summarized by the following motto:

If you do restrict only to things that must exist, then the Axiom of Choice is likely true.

This is a very general motto and it applies to many contexts even outside set theory. Note, however, that it is just a motto and not an actual theorem.
Before going into the case of set theory, let me talk a bit about constructive analysis where this pathology takes an interesting form. In the very early days of intuitionism, Brouwer introduced a bunch of so-called continuity principles. One such principle can be formulated as follows. Suppose $A(f,n)$ is a statement where $f$ stands for a function from $\mathbb{N}$ to $\mathbb{N}$ (i.e., an element of Baire space ${}^{\mathbb{N}}\mathbb{N}$) and $n$ stands for an element of $\mathbb{N}$.

If $(\forall f \in {}^{\mathbb{N}}\mathbb{N})(\exists n \in \mathbb{N})A(f,n)$, then there is a continuous function $\nu:{}^{\mathbb{N}}\mathbb{N}\to\mathbb{N}$ such that $(\forall f \in {}^{\mathbb{N}}\mathbb{N})A(f,\nu(f))$ holds.

Note that this is actually a variant of the Axiom of Choice, except that it is stronger since the selector $\nu$ is required to be continuous. A majority of systems of constructive analysis satisfy Brouwer's continuity principles, and hence a very strong form of the Axiom of Choice.
You may say: "But this doesn't make sense! What if $A(f,n)$ is the graph of a discontinuous function, like characteristic function of the singleton $\{f_0\}$ for some fixed $f_0 \in {}^{\mathbb{N}}\mathbb{N}$?" Well, this is the magic of constructive systems, you can't prove that $(\forall f \in {}^{\mathbb{N}}\mathbb{N})(f = f_0 \lor f \neq f_0)$ since the Law of Excluded Middle is not constructive. Thus, you cannot prove that $(\forall f \in {}^{\mathbb{N}}\mathbb{N})(\exists n \in \mathbb{N})A(f,n)$ for your particular choice of $A(f,n)$.
There is a very thought provoking moral here:

It is wrong to say that the Axiom of Choice is nonconstructive! In fact, some very strong forms of the Axiom of Choice are essential components of many systems of constructive mathematics.

Note, however, that existence in constructive systems is very strong. There are very strict requirements for being a collection of nonempty sets, so it is not entirely surprising that choice functions exist since there is a lot of implicit information packed in the constructive notion of "nonempty".
Now let's stop this digression and come back to set theory. The first thing to ask is: what exactly are these sets which must exist? (I'll come back to "provable sets" in a bit.) One possible answer are the elements of the minimal model of ZF, i.e., the smallest level $L_\alpha$ of the constructible hierarchy that satisfies ZF. (Note that $\alpha = \mathrm{Ord}$ is a possibility here.) But then $L_\alpha$ is a model of $V = L$, therefore the Axiom of Choice is true! Maybe that's not the answer you had in mind, but it is very likely that the same thing happens with whatever you believe sets that must exist actually are...
Why is this? Well, there is one simple recipe for this in the case of set theory. Sets that must exist all have descriptions since it is very hard to justify the existence of something that you can't even describe. While sets may not be wellordered, descriptions of sets certainly are. So, instead of searching for a particular set, search for a description of that set. This usually gives a very nice global choice function for the universe that consists only of sets that must exist (whatever that means).
But you said "sets that we can prove to exist" while I keep rambling about "sets that must exist", why is that? Well, the notion of "provable sets" is very hard to make sense of and it is unlikely to mean what you think. The reason why it is hard to make sense of this is that "provable" is a syntactic notion and "sets" is a semantic one. Still, there is a way to make some sense of provable sets. It's not easy, and the answers to this MO question actually come to the conclusion that this really only makes sense when one assumes V = OD, which implies the Axiom of Choice for the reasons I explained above...


text:
Q: Writing a ping service to ping 1K websites per minute I want to create a ping service, that would make a http/https/ping/tcp connection to a website to see if the service is up or not.
Would python be suitable for this, seeing as I want to build it to be able to ping 1K endpoints per minute.

A:
Would python be suitable for this, seeing as I want to build it to be able to ping 1K endpoints per minute.

Python has all you need, but there are two bottlenecks, first is OS and the other is network. While planning for such a program, I would do some research on the limit of the IP stack of your target OS and the relevant limits for the source network.

A: Yes, Python would be suitable for this.
(Next time, just try it--it's trivial.)

A: Practically all, if not all, modern programming languages are capable of that speed of execution easily. The network itself would be the bottleneck, and depending on how many actual pings you want to do of each service, they could get backed up.
If I was doing this, I would use Python with a Java frontend if necessary.
So, in short, yes, Python is both capable and (in my opinion) a good choice for such a program.


text:
Q: Zend View Renderer Path appending /script I am learning Zend. I wanted to learn how to use it as a standalone set of classes and so my boot strap is as follows. I have no config.ini From this configuration - I would presume that the path would be to the view script
/controllers/:action.:suffix
However I get errors that the following file does not exist
/controllers/scripts/:action.:suffix
Where is the directory /scripts being appended??
I have looked at every path method I can and i have set Nover/No controller as well.
set_include_path('library');
require ('library/Zend/Loader/Autoloader.php');
$loader = Zend_Loader_Autoloader::getInstance();

$front_controller = Zend_Controller_Front::getInstance();
$front_controller->setControllerDirectory('controllers');

$View = new Zend_View();

$Renderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
$Renderer->setView($View);
$Renderer->setViewSuffix("php");
$Renderer->setNeverController(true);
$Renderer->setViewBasePathSpec('/controllers');
$Renderer->setViewScriptPathNoControllerSpec(':action.:suffix');

echo $Renderer->getViewBasePathSpec();
echo $Renderer->getViewScriptPathNoControllerSpec();

$front_controller->dispatch();

A: It is not located in your controllers folder. It is in the views controller.
    /application/views/scripts/ACTION.phtml

A: When using Zend as an individual set of classes, the viewRender Class still expects your folder setup to be
whatever/scripts
Whatever/helpers
etc.
As such you cannot control absolute path to your views folder. So Zend is best used as a fuill MVC stack as default.
However if you don't need routing and views etc - Its loosely coupled nature makes for a great set of utilities.


text:
Q: Automate Powershell Script to connect to MSOnline while MFA is applied Thanks in advance.
Quick brief, I work in a team managing multiple Microsoft CSPs (Partner Centers), every now and then somebody asks us to run a script that does specific activities or grab specific info from all 30 CSPs we manage and all customers under them.
Previously we used to keep all usernames, passwords, TenantIDs, WebApp IDs in a CSV file and we create a script that runs on every raw to get the required info for each CSP Automatically without prompting credentials using below command:
$credential = (New-Object –TypeName System.Management.Automation.PSCredential –argumentlist $AdminName ,(ConvertTo-SecureString $AdminPassword –AsPlainText –Force))

And then call it in all modules like the below:
#MSonline
Connect-Msolservice –Credential $Credential

#ExchangeOnline
$session = New-PSSession –ConfigurationName Microsoft.Exchange –ConnectionUri https://outlook.office365.com/powershell-liveid?DelegatedOrg=$Customerdomain  –Credential $credential –Authentication Basic –AllowRedirection
Import-PSSession $Session

#Partner Center
Add-PCAuthentication -cspappID $NAtive_clientid -cspDomain $domain -credential $credentials
Connect-MsolService -Credential $credentials

Then MFA was applied on all CSPs, though secure, it presented a problem with automating our scripts. Every time we're asked to run a script we would have to login manually at least 1 time to enter our MFA credentials to be able to run the script on each CSP individually.
The Modules we usually connect to are:
PartnerCenter
MSOnline
CsOnline
AzureRM
AzureAD
Microsoft provided steps to work around this by using secure API Modules: https://learn.microsoft.com/en-us/powershell/partnercenter/secure-app-model?view=partnercenterps-1.5
I've created New APPs with new secrets and call backs , managed to get refresh token and integrated it in PartnerCenter module successfully as follows:
Connect-PartnerCenter -ApplicationId $NAtive_clientid -RefreshToken $refresh_token

Now I'm tying to do the same for the other Modules I'm addressing, as per the above document I could do the same for MS Online and for Azure AD simply by getting 3 other tokens (Graph Token , Azure AD token and Azure token)
$credential = Get-Credential
$refreshToken = 'Your-Refresh-Token-Value'

$azureToken = New-PartnerAccessToken -RefreshToken $refreshToken -Resource https://management.azure.com/ -Credential $credential -TenantId '<Your Tenant Id>'
$graphToken =  New-PartnerAccessToken -RefreshToken $refreshToken -Resource https://graph.microsoft.com -Credential $credential -TenantId '<Your Tenant Id>'
$aadGraphToken = New-PartnerAccessToken -RefreshToken $refreshToken -Resource https://graph.windows.net -Credential $credential -TenantId '<Your Tenant Id>'

#MS Module
Connect-MsolService -AdGraphAccessToken $aadGraphToken.AccessToken -MsGraphAccessToken $graphToken.AccessToken

# Az Module
Connect-AzAccount -AccessToken $azureToken.AccessToken -GraphAccessToken $graphToken.AccessToken -TenantId '<TenantId>'

# AzureRM Module
Connect-AzureRmAccount -AccessToken $azureToken.AccessToken -GraphAccessToken $graphToken.AccessToken -TenantId '<TenantId>'

When Applying this and running the below command I get an error:
New-PartnerAccessToken -RefreshToken $refreshToken -Resource https://management.azure.com/ -Credential $credential -TenantId '<Your Tenant Id>'
New-PartnerAccessToken : Cannot validate argument on parameter 'RefreshToken'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:1 char:38
+ New-PartnerAccessToken -RefreshToken $refreshToken -Resource https:// ...
+                                      ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [New-PartnerAccessToken], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Store.PartnerCenter.PowerShell.Commands.NewPartnerAccessT
   oken

After some investigation I found that the parameter "-resource" no longer exists as per the documentation: https://learn.microsoft.com/en-us/powershell/module/partnercenter/new-partneraccesstoken?view=partnercenterps-3.0
Yet as per the documentation related to MSOnline, it shows I should be able to use it : https://learn.microsoft.com/en-us/powershell/module/msonline/connect-msolservice?view=azureadps-1.0
Now I'm stuck without the resource parameter I can't get the tokens required to use the 3 modules.
My question, is there another way to use App ID, refresh token, secret, Tenant ID to authenticate using powershell without human interference , if not how can I make the above method work for other modules the same way I did with the partner center.

A: According to my research. if the version of your PartnerCenter module is larger than 2.0.1909.1, it has rplaced the Resource parameter with the Scopes parameter for the Connect-PartnerCenter and New-PartnerAccessToken cmdlets. So please use the following script to get access token
New-PartnerAccessToken -ApplicationId 'xxxx-xxxx-xxxx-xxxx' -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.windows.net/.default' -ServicePrincipal -Tenant 'xxxx-xxxx-xxxx-xxxx'


text:
Q: Covariance Estimation for cauchy noise Apart from Ledoit wolf shrinkage technique which can be better shrinkage covariance estimators for data with cauchy distribution?
How to calculate optimum shrinkage intensity for data containing cauchy distribution?
I have gone through many shrinkage covariance estimators dealing with normal data or exponential distributions but didnt get for cauchy distribution can anyone suggest?

A: That's probably because the Cauchy distribution does not have finite variance, so it would not make sense to estimate variance-covariance in the first place. See the Wikipedia page for the Cauchy distribution or google "Cauchy distribution variance" for more information.


text:
Q: Differential on Tangent Spaces and the Chain Rule From Lee's Intro to Smooth Manifolds
I don't see how this is a straightforward application the chain rule. The idea of having different coordinates on the domain and codomain is throwing me off. I would have naively written
$$\left.\frac{\partial}{\partial x^i} \right|_p (f \circ F)=\frac{\partial f}{\partial F^j}(F(p))\frac{\partial F^j}{\partial x^i}(p),$$
since if I write things more explicitly, i.e. since $x=(x^1,..,x^n) \in \mathbb{R^n}$ and $F(x)=(F^1(x),..,F^m(x)) \in \mathbb{R^m},$ we can write $f\circ F$ as
$$f \circ F(x)=f(F^1(x^1,..,x^n),...,F^m(x^1,..,x^n)).$$
Then, disregarding evaluation of the original partial at the point $p$, we have by the multivariable chain rule that
$$\frac{\partial}{\partial x^i} (f \circ F(x))=\frac{\partial}{\partial x^i} (f(F^1(x^1,..,x^n),...,F^m(x^1,..,x^n)))=\frac{\partial f}{\partial F^j}\frac{\partial F^j}{\partial x^i}(x).$$
So either what did I do wrong in my application of the chain rule or where do the coordinates $(y^i)$ come into play?

A: To sum it up: Both are right, but Lee is talking about something else.
For a start, you should not be thrown off by the fact that the coordinates in $V$ have names $y^j$. The function $f$ is defined on $V$. It is in the first place a function ${\bf y}\mapsto f({\bf y})\in{\mathbb R}$, hence a function of the $y^j$. It does not make sense to write ${\partial f\over\partial F^j}$, since you can only partially differentiate with respect to coordinate variables, not with respect to functions. Therefore I'd write your chain rule as
$$\frac{\partial}{\partial x^i} (f \circ F(x))=\frac{\partial}{\partial x^i} (f(F^1(x^1,..,x^n),...,F^m(x^1,..,x^n)))=\frac{\partial f}{\partial y^j}\frac{\partial F^j}{\partial x^i}(x).$$
The linked passage in Lee's book is not about partial derivatives and the chain rule per se. Instead it talks about the effect of the derivative $dF_p$ on the tangent vectors at $p$. The "special" tangent vectors ${\partial\over\partial x_i}\biggr|_p$ (introduced before, I hope) form a basis of $T_p{\mathbb R}^n$. Therefore Lee is out to compute their images $$dF_p\left({\partial\over\partial x_i}\biggr|_p\right)\in T_q{\mathbb R}^m\qquad\qquad(q:=F(p))$$
 in terms of  the "special" tangent vectors ${\partial\over\partial y^j}\biggr|_q$ forming a basis of $T_q{\mathbb R}^m$. In order to find the resulting matrix he looks at the effect
$$dF_p\left({\partial\over\partial x_i}\biggr|_p\right).f$$
of $dF_p\left({\partial\over\partial x_i}\biggr|_p\right)$ on an arbitrary $f$ defined in the neighborhood of $q$. In the resulting computation he then needs the chain rule as quoted by you.

A: For an arbitrary smooth real-valued function $g$ on an open set $U\subseteq\Bbb R^n$, to compute $$\left.\frac{\partial}{\partial x^i}\right\vert_pg,$$ you can compute the whole linear transformation $Dg(p)$ (the total derivative) as a $1$ by $n$ matrix $$Dg(p)=\begin{bmatrix}\partial_jg(p)\end{bmatrix}$$ and then apply this linear transformation to the vector $e_i\in\Bbb R^n$ (the $i$-th canonical basis vector). We would have $$\left.\frac{\partial}{\partial x^i}\right\vert_pg=Dg(p)e_i.$$
With $g=f\circ F$, chain rule tells us that the matrix $D(f\circ F)(p)$ can be computed by first computing the total derivatives of $f$ and $F$ separately, and then composite them. You calculate $$Df(F(p))=\begin{bmatrix}\partial_jf(F(p))\end{bmatrix}, \ \ \ DF(p)=\begin{bmatrix}\partial_jF^i(p)\end{bmatrix}$$ and the matrix $D(f\circ F)(p)$ would be the composition of $Df(F(p))$ and $DF(p)$. Then apply this linear transformation to the vector $e_i$ to obtain the formula $$\left.\frac{\partial}{\partial x^i} \right|_p (f \circ F)=\frac{\partial f}{\partial y^j}(F(p))\frac{\partial F^j}{\partial x^i}(p),$$ where $\frac{\partial f}{\partial y^j}(F(p))$ are the partial derivatives of $f$.
As long as you interpret the symbol $$\frac{\partial f}{\partial F^j}(F(p))$$ as partially differentiate $f$ with respect to the $j$-th variable, you should be fine.
Now, here I include some extra content, to tell you your source of confusion.
You may have learned that chain rule goes like this:

Given a real-valued function $f$ that depends on the variables $y^1,y^2,\dots,y^m$ , which in turn depend on the variables $x^1,x^2,\dots,x^n$, the partial derivative of $f$ with respect to $x^i$ is given by $$\frac{\partial f}{\partial x^i}=\sum_{j=1}^m\frac{\partial f}{\partial y^j}\frac{\partial y^j}{\partial x^i}.$$

Then, you may have naively changed each $y^j$ into $F^j$, to become the formula you wrote.
Whoever taught you that chain rule goes like this, I blame them, for that they are abusing notations before a theorem is properly stated, and without making you understand the abuse of notations.
The proper way of understanding chain rule should be as follows:
There is a real-valued differentiable function $f:V\to\Bbb R$ on an open set $V\subseteq\Bbb R^m$, with its partial derivative with respect to the $j$-th coordinate denoted $\frac{\partial f}{\partial y^j}$. There is also a real-valued differentiable function $F:U\to V$ on an open set $U\subseteq\Bbb R^n$, with its $j$-th component function's partial derivative with respect to the $i$-th coordinate denoted $\frac{\partial F^j}{\partial x^i}$.
We can form the differentiable function $f\circ F$, and try to take partial derivatives of this function. The chain rule states that $$\frac{\partial (f \circ F)}{\partial x^i} =\sum_{j=1}^m\frac{\partial f}{\partial y^j}\frac{\partial F^j}{\partial x^i}.$$
This is the correct one, always. You can change the notation of partial derivatives into, for example, $$\frac{\partial f}{\partial y^j}=\partial_jf, \ \ \ \frac{\partial F^j}{\partial x^i}=\partial_iF^j,$$ but rewriting $F^j$ as $y^j$, or rewriting $y^j$ as $F^j$, both are certainly not correct. Writing the symbol $\frac{\partial f}{\partial F^j}$ is very wrong, in that $f$ should not ever have anything to do with the function $F$, and you just don't differentiate $f$, which has domain $V\subseteq\Bbb R^m$, with respect to a function $F^j$.
Some teachers or authors would abuse notations by writing $f \circ F=f$, $F^j=y^j$, to make the formula looks like in the quote, in hope that the formula is "intuitive" and "simple". And the formula with notation abuse is often presented to students before the correct one. In reality, this confuses every student new to multivariable calculus, and the students won't notice that they learned it wrong until late.


text:
Q: Possible to "fail fast" when running rake test w/ minitest 5? Is it possible to configure 'rake test' to stop running tests as soon as it hits a failure/exception?
My setup:

*

*Rails 4.1

*Minitest 5.3.4

*Tapout (for formatting)

I'd like to start the test suite and immediately stop if a test fails -- the default behavior is to keep running all the tests which, in some cases, is too much data (especially one small bug causes a ton of tests to suddenly fail.)
I had a nice little setup going with the older version of Minitest (4.x) and the Turn gem by following this gist: (Add a simple fail-fast option to minitest/turn/minitest-rails), but I'm working on a new Rails 4.1 app right now and Turn isn't compatible with Minitest 5 (yet).
Any thoughts?

A: If you are using Rails 5, try rails test -f will 'fail fast'. It means abort test run of first failure or error if you run rails test -h

A: You can use this new gem with Rails 4.2 and and Minitest 5.6.1: minitest-fail-fast


text:
Q: Consume multiple queues by priority I have a Producer sending messages to a topic exchange. Each message contains a routing key. (Apologies for the primitive diagram)
       P
       |
       X
     /| |\
    / | | \
   /  | |  \
   Q1 Q2 Q3 Q4
   |   / /  /
   |  / /  /
   | / /  /
   |/ /  /
      C

I'm using php-amqplib and am attempting to consume a number of queues. What I am trying to achieve is to test each queue sequentially, see if it has a message and, if so, process it, otherwise, move on to the next queue. Also, if a message has been found, start the checking process again from Q1. The following code doesn't work but will demonstrate the logic of what I want to do.
$connection = new AMQPConnection(HOST, PORT, USER, PASS, VHOST);
$channel = $connection->channel();

$channel->exchange_declare('myexchange', 'topic', false, false, false);

$channel->queue_declare("Q1", false, true, false, false);
$channel->queue_bind("Q1", 'myexchange', 'priority.1');

$channel->queue_declare("Q2", false, true, false, false);
$channel->queue_bind("Q2", 'myexchange', 'priority.2');

$channel->queue_declare("Q3", false, true, false, false);
$channel->queue_bind("Q3", 'myexchange', 'priority.3');

$channel->queue_declare("DFQ4", false, true, false, false);
$channel->queue_bind("DFQ4", 'myexchange', 'priority.4');

$queues = array('Q1','Q2','Q3','Q4');

$priority = 0;
while (1) {

    $priority = ($priority<4)? $priority+1 : 0;

    $msg = $channel->basic_consume($queues[$priority], $consumer_tag, false, false, false, false);
    if(isset($msg->body)) {
        echo ' [x] ',$msg->delivery_info['routing_key'], "\n";
        $channel->basic_ack($msg->delivery_info['delivery_tag']);
        $priority = 0;
    }
}

$channel->close();
$connection->close();

A: I had the same requirement for my .NET projects. Basically, I had the similar approach but I used header exchange to feed published messages to those queues. The library I created subscribe to all those queues (with same prefetch size value) and put all those messages to an internal memory queue where those messages can be sorted by their priorities. So at the end of the pipeline, the actual code to process messages will read them from the internal queue, messages with higher priority will be processed and then acked before the lower priority one.


text:
Q: Nested Shortcode Inside [caption] Doesn't Process Captions in wordpress do not support nested shortcodes at the moment (v3.6). So, If I do write
[caption] I love my [city][/caption]

Where city is suppose to be processed but it does not. How do I fix this?
Ticket: #24990

A: The latest versions of WP have really improved the filterability of caption arguments, so I think this new answer will have the smallest footprint and safest operation.
What we need to do is directly filter $atts['caption'] during shortcode_atts() for the [caption] shortcode. We can do this with the shortcode_atts_caption filter which only affects the caption shortcode.
As a bonus I added a commented-out line that will test the caption for a specific shortcode before running do_shortcode(). This is useful if you only want to enable a particular shortcode in captions (I use it to enable only the Shortcode Shortcode). Careful though: do_shortcode() will process all shortcodes, not just the one you tested for.
/**
 * Filter Caption shortcode attributes to enable the [shortcode] shortcode inside caption text
 *
 * WP doesn't run do_shortcode on the 'caption' text value parsed out of [caption], which means
 * the [shortcode] shortcode doesn't work.
 *
 * @param array $out atts array as determined by WP to be returned after filtering
 * @param array $pairs
 * @param array $atts
 * @return filtered $out atts
 */
 function wpse_113416_filter_shortcode_atts_caption($out, $pairs, $atts) {
    // OPTIONAL: Look for a specific shortcode before running do_shortcode
    // if (has_shortcode($out['caption'], 'shortcode_to_look_for'))
        $out['caption'] = do_shortcode($out['caption']);

    return $out;
}
add_filter('shortcode_atts_caption', 'wpse_113416_filter_shortcode_atts_caption', 10, 3);

A: There is a hook inside the caption shortcode that will allow you to hijack the whole thing. Most of the following is copied from the Core img_caption_shortcode function.
function nested_img_caption_shortcode($nada, $attr, $content = null) {

  extract(
    shortcode_atts(
      array(
      'id'    => '',
      'align' => 'alignnone',
      'width' => '',
      'caption' => ''
      ),
      $attr,
      'caption'
    )
  );

  $caption = do_shortcode($caption); // process nested shortcodes

  if ( 1 > (int) $width || empty($caption) )
          return $content;

  if ( $id ) $id = 'id="' . esc_attr($id) . '" ';

  return '
'
  . do_shortcode( $content ) . '
' . $caption . '

';
}
add_filter('img_caption_shortcode', 'nested_img_caption_shortcode', 1, 3);

A: Using latest function has_shortcode() introduced on v3.6
add_filter( 'the_content', 'process_wp_caption_shortcodes' ); // hook it late

    function process_wp_caption_shortcodes( $content ){
        if( !function_exists    ( 'has_shortcode' ) )   // no luck for user using older versions :)
            return $content;

        if( has_shortcode( get_the_content(), 'caption' ) ){ // check with raw content
            // caption exists on the current post
            $content = do_shortcode( $content );
        }

        return $content;
    }

This solution can be used on any third party shotcode that didn't implemented nested shortcode support.
Any better solution welcomed!


text:
Q: Как отключить автоформатирование в wordpress? Как отключить автоформатирование в wordpress?

A: Отключить можно добавив в файл functions.php вашей активной темы такие строчки:
в записях
 remove_filter('the_content', 'wptexturize');
 remove_filter('the_excerpt', 'wptexturize');
 remove_filter('comment_text', 'wptexturize');


text:
Q: Why is Await not working in async function? I am trying to use await in an async function. Hwoever, I am getting the error

SyntaxError: await is only valid in async function

I cant figure out where the problem is in the below code.
insertPayrollAllowance: async function(companyId, jobId, basicSalary, employeeId, payrollId) {

        return new Promise((resolve, reject) => {
            sqlQuery = "SELECT * from tblJobAllowances Where tblJobAllowances.companyId = '" + companyId + "' and tblJobAllowances.jobId = '" + jobId + "' and deleterec = 0 order by id"
            db.executeQuery(sqlQuery, null, (err, result) => {
                if (err) {
                    reject(err);
                } else {

                    for (var i = 0; i < result.length; i++) {

                        var insStatus = false;
                        var allowanceId = result[i].allowanceId
                        var allowanceName = await this.getAllowanceName(companyId, allowanceId);
                        var amountType = result[i].typeOfAmount;
                        var amount = result[i].amount;
                        var amountCredited;
                        var taxable = result[i].taxable;

                        if ($.trim(amountType) == "FIXED AMT") {

                            amountCredited = parseFloat(amount.toString().replace(/,/g, ''));

                        } else if ($.trim(amountType) == "% Of Income") {

                            amountCredited = (parseFloat(basicSalary.toString().replace(/,/g, '')) / 100) * parseFloat(amount.toString().replace(/,/g, ''));

                        };

                        var info = {
                            companyId: companyId,
                            employeeId: employeeId,
                            payrollId: payrollId,
                            allowanceName: allowanceName,
                            amountType: amountType,
                            amount: amount,
                            amountCredited: amountCredited,
                            taxable: taxable
                        }

                        sqlQuery = "INSERT INTO tblPayrollAllowanceDetails SET ?"
                        db.executeQuery(sqlQuery, info, (err, result) => {
                            if (err) {
                                insStatus = false;
                            } else {
                                insStatus = true;
                            }
                        });

                    };

                    resolve(insStatus);

                }
            });
        });

    }

I will be glad if anyone could point out why Im getting this error. Any assistance will be highly appreciated.

A: The await is inside another function that's not async
 db.executeQuery(sqlQuery, null, (err, result) => {

It's inside this arrow function (err, result) => {
so to fix it just add async like so:
db.executeQuery(sqlQuery, null, async (err, result) => {


text:
Q: failed to send the qLaunchSuccess packet I am using XCode 4.3.2 and trying to open an already existing project based on the Facebook SDK sample Project for XCODE and run it on a target IPhone with IOS 4.2.
Although it runs on the simulator it crashes on the IPhone printing this error on the console:
failed to send the qLaunchSuccess packet

I really do not know what could be the problem

A: In Xcode 4.3.3, this is caused by re-running the app (command+R) or stopping it (command+.) while halted on a breakpoint. To fix the error once you've gotten it, it usually works to stop the app, (command+.), unplug the device, plug it back in, and run the app again.
To avoid the issue in the future, remember to continue (command+control+y or hit the play button near the debugger output) before stopping. If you have many breakpoints or are in a loop, you can deactivate one breakpoint by going to that line and hitting command + \ or you can deactivate all breakpoints by hitting command + y.
If you eventually get the error ending in "This generally means that another instance of this process was already running or is hung in the debugger," you need to reboot the device.
I submitted a bug report to Apple. I suggest you all do the same so that this gets the attention it deserves.
Edit: the "qLaunchSuccess packet" bug doesn't happen in Xcode 4.4 or 4.5 as it did in 4.3. However, 4.4 and 4.5 experience "Timed out waiting for app to launch" instead--possibly the same issue with a new message. See this question for some possible solutions. Nothing works for met yet. The behavior seems different than 4.3.3 because the error doesn't come up every time I stop while halted on a breakpoint. I will experiment and see if my workaround for 4.3 also fixes the 4.4/4.5 issue.

A: I get this every time my app crashes, and I restart it by doing a Run.  If I hit the Stop button before doing a run then I don't get this.
After some time, if I keep hitting Run instead of Stop first, the iPhone will only show the above error message and the only solution is to restart the iPhone.  Quitting and restarting Xcode does not help.
This may be an Xcode bug.

A: This happened to me when I accidentally tried to do a device debug using a distribution profile.  As soon as I noticed and switched it to a dev profile, the issue went away.

A: You might have some broken privileges or a hung debugger process (one that didn't quite exit fast enough).  Restart Xcode or restart your phone, either way, it's not as bad as it's more annoying cousin, Processes That Can't Be Registered To The BootStrap Server
If all else fails, restore it from a backup.

A: A slightly quicker way to resolve this issue without restarting the device is to change the language.
Settings - > General - > International (4th from bottom) - > Language (top)
Alternatively If you have a bugged News stand app (in a folder) just tap it to restart springboard.

A: I had this error when I was trying to install over a bad version of the app that had been crashing on launch. Restarting Xcode and the device did not make the error go away, but deleting the app fixed the problem.


text:
Q: How can I pass argument as part of selenium webdriver command I have below similar codes. The only difference is the browser I choose. I want to combine the duplicated codes into a function.
driver = webdriver.Chrome()
driver.get('http://www.google.ca')
driver.quit()

driver2 = webdriver.Firefox()
driver2.get('http://www.google.com')
time.sleep(2)
driver2.quit()

I wrote the below function but seems cannot pass the browser_name as part of the command. Any solution for this?
def go_to_baidu(browser_name):
    driver = webdriver.browser_name()
    driver.get('http://www.baidu.com')
    time.sleep(2)
    driver.quit()

A: Instead of passing a value like "Chrome" or "Firefox" to your function, pass webdriver.Chrome or webdriver.Firefox() (without the quotes) instead. The, change the first line of the function like so:
def go_to_baidu(browser_name):
    driver = browser_name()
    driver.get('http://www.baidu.com')
    time.sleep(2)
    driver.quit()

You then run it like this:
go_to_baidu(webdriver.Chrome)

for example.
Functions are objects in Python, and can be passed to other functions just as easily as strings, lists, dicts, etc. can.


text:
Q: Net gain on dice rolling Suppose you have to pay $15$ to roll a dice repeatedly until the first $6$ comes up. Then you will get paid as many dollars as the square of the no of rolls $X^2$.
I have a equation as follows:
$$G = \text{Gain} = X^2 -15 \\
E(G) = E(X^2 - 15) = E(X^2) -15 $$
Since this is a geometric distribution
I found the mean to be $E(X) = 1/p = 1/(1/6) = 6$ and variance $= (1-1/6)/(1/6)^2 = 30$
Therefore I found $E(X^2)$ to be $66$ using $V(X) = E(X^2) − (EX)^2$
The overall net gain was $66-15 = 51$
I am just wondering whether I am on the right track. I thought the net gain would be very low for this $Q$ as you need to roll at least 4+ times to get a gain.
Also can someone direct me how to find the probability that the users net gain will be positive. I was thinking of calculating the probability of rolling at least 4 times.

A: Your calculation of $E(X^2)$ is absolutely correct, it indeed equals $66$. You indeed need to be able to roll the die at least four times to make profit, which means that you need to not throw a $6$ three times in a row. The probability of not throwing a $6$ on a given roll equals $\frac{5}{6}$, so the probability $P(X > 3)$ of making a profit equals:
$$P(X > 3) = \left(\frac{5}{6}\right)^3 = \frac{125}{216} \approx 0.579$$

A: You are on the right track. Intuitively a large reward is plausible because of the squared increase in rewards. Very unlikely events have a huge reward which in this case outweigh the small losses.
Regarding your last question: Calculating the probability of rolling at least 4 times is correct, however, rather difficult. It is easier to calculate the probability of a loss and then using $P(\text{gain}) = 1 - P(\text{loss})$ since we know the two probabilities must sum up to 1.
(I get $P(\text{gain}) \approx 0.58$)


text:
Q: Loop all arguments in a shell script I've created a shell script but I don't know how to do a loop that prints the number of lines in every file you pass to the script as argument. So that the output would be something like this:
2 lines in hello.sh
33 lines in /var/log/syslog

A: Assuming a POSIX shell, you want a for loop here, looping over "$@" which contains the command line arguments:
for filename in "$@"; do
    lines=$(wc -l < "$filename")
    printf '%u lines in %s\n' "$lines" "$filename"
done

Using all the quotes is quite important. It allows you to pass filenames that contain spaces and other characters.
./my_script.sh /var/log/syslog "$HOME/My Dir with Spaces/a file with spaces.txt"

A: In general, to loop over the command line argument in a script or shell function, you may do
for thing do
    commands using "$thing"
done

or
for thing in "$@"; do
    commands using "$thing"
done

In this case, assuming filenames given on the command line do not contain literal newlines, there's no need to do an explicit shell loop for this:
wc -l -- "$@" | sed -E '$d;s/^[[:blank:]]*([[:digit:]]*)[[:blank:]]*(.*)/\1 lines in \2/'

This would take all the command line arguments and run wc -l on them all.
The output is parsed by sed which discards the last line containing the total number of lines in the given files (using $d).  The rest of the output from wc -l is transformed into the output that you want by capturing the number of lines and the filename and then inserting the string lines in in-between.
Running the script with my own .vimrc, .profile and .mailrc files will return
8 lines in .vimrc
8 lines in .profile
4 lines in .mailrc

Notice that wc -l -- "$@" will create output like
   8 .vimrc
   8 .profile
   4 .mailrc
  20 total

which may actually be enough for what you want, without the need for sed.

A: #!/bin/bash

for file in "${@}"; do
    wc -l -- "${file}"
done

#!/bin/bash Program that will execute this script.
${@} Positional arguments. Arguments that you give to the script through command line.
file Variable that will iterate over the arguments given in ${@}.
wc -l -- "${file}" External command that will print the number of lines in ${file} (except when ${file} is - in which case it will print the number of lines on its standard input).

A: Alternative using while and shift
while [ $# -gt 0 ] ; do
    printf '%u lines in %s\n' $(wc -l < "$1") "$1"
    shift
done


text:
Q: Как выводить разную структуру постов в одном цикле wordpress? Добрый, подскажите как реализовать вывод постов с разными калссами и разной структурой в одном цикле, не понимаю как это сделать.
Например:

                 дата
                 линк
                 линк

                     дата
                     линк
                     линк

 какойто текст

                 линк

Накидал простой пример разметки, если можно пример как это сделать.
обертка

     первый пост

     обертка для других постов

         второй пост

         третий пост

         четвертый пост из определенной категории, если это возможно реализовать

повтор цикла

A: У вас есть логическая проблема здесь. Вывод будет зависеть от числа (наличия) постов разных видов.
Для примера - два случая:
Вид 1 - 10шт, Вид 2 - 1шт, Вид 3 -20шт
Вид 2 - 0шт, Вид 2 - 50шт, Вид 3 - 1 шт
В случае 1 - у вас будет пустая вторая колонка начиная со второй строки и пустая первая - с 11 строки.
Во втором - первая вообще пустая, вторая полная, третья - один пост.
Смотреться будет... Странно.
Но, если вы все-таки хотите именно это - то вам надо сделать примерно так:

*

*Выборка всех видов постов и размещение данных в массивы $postsA, $postsB, $postsC и т.д.

*Цикл по макс. кол-ву:

for ( $i = 0; $i < max( count( $postsA ), count( $postsB ), count( $postsC ) ); $i ++ ) {
    if ( !empty( $postsA[ $i ] ) ) {
        //Тут вывод данных поста типа "а"
    } else {
        //Тут вывод заглушки, елси посты данного вида кончились
    }
    if ( !empty( $postsB[ $i ] ) ) {
        //Тут вывод данных поста типа "а"
    } else {
        //Тут вывод заглушки, елси посты данного вида кончились
    }
    if ( !empty( $postsC[ $i ] ) ) {
        //Тут вывод данных поста типа "а"
    } else {
        //Тут вывод заглушки, елси посты данного вида кончились
    }
}


text:
Q: Can static methods be called as a public method? I wrote a small test scenario for testing mixed use of static and non-static methods.
When calling a public method as a static method it generates a strict warning.
That got me thinking that perhaps calling a static method as a public method would generate a similar warning, but it did not.
Is it ok to call static methods as a non-static method? Are there any consequences to doing so?
<?php
class TestS {
  static function _testS() {
    echo("Hello Static
\n");
    // Strict warning: Non-static method TestS::_tS() should not be
    // called statically in TestS::_tS()
    self::_tS();
  }
  public function _tS() {
    echo("tS
\n");
  }
  public function _testP() {
    echo("Hello Public
\n");
    self::_tP();
  }
  static function _tP() {
    echo("tP
\n");
  }
  public function _testSP() {
    $this->_tP();
  }
}

$test = new TestS();
echo("///////////
\n");
$test->_testP();
echo("///////////
\n");
TestS::_testS();
echo("///////////
\n");
$test->_testSP();
echo("///////////
\n");

A:
Is it ok to call static methods as a public method?

Theoretically, it is. That's because a static method doesn't reference $this anywhere, so it will work when called either statically or as an instance method.

Are there any consequences to doing so?

It's a good practice to indicate explicitly what kind of method you're calling; when looking back on your code you will know exactly which method is static because of the way you're calling it, with the notable exception of using parent::method() inside an instance method.
It's also a good practice to avoid using static methods in the first place; if you have a lot of them, it's often indicates a code smell and should be refactored.


text:
Q: MYSQL Count where active across tables I have three tables:
person
-----------
person_id, active

person_team
-----------
person_id, team_id, active

team
-----------
team_id, active

I'd like to get the count on teams from each person where active is true in each table.
So far I have:
SELECT t.id, t.title, t.created_timestamp, COUNT(p_t.tag_id) AS count
FROM team t
LEFT JOIN
    person_team p_t ON p_t.team_id = t.id AND p_t.active = 1
WHERE
    t.active = 1
GROUP BY t.id
ORDER BY t.title

This gets the count where team and person - team are active, but doesn't take into account whether person is active. Should I use a sub query or another type of join?

A: You need to add the person table in a join, and count a column from that table:
SELECT t.id, t.title, t.created_timestamp, COUNT(p.id) AS count
FROM team t
LEFT JOIN
    person_team p_t ON p_t.team_id = t.id AND p_t.active = 1
LEFT JOIN
    person p ON p_t.person_id = p.id AND p.active = 1
WHERE
    t.active = 1
GROUP BY t.id
ORDER BY t.title

A: You should use a inner join on sub select for get the columns not in group by
select k.id, t.title, t.created_timestamp, k.count from
 (  SELECT t.id  COUNT(p_t.tag_id) AS count
FROM team t
LEFT JOIN
    person_team p_t ON p_t.team_id = t.id AND p_t.active = 1
WHERE
    t.active = 1
GROUP BY t.id ) k
inner join team t on t.id = k.id


text:
Q: Visual Studio C# Get sheet visible property I'm trying to fill a dictionary with name as key, and an array with codename and if sheet is visible. This is where I ran into a conversion issue with sheet.visible
If I use == true I get this error:
if I use == Excel.XlSheetVisibility.xlSheetVisible like in the official Microsoft documentation, I get this error:
using Microsoft.Office.Tools.Ribbon;
using System;
using Excel = Microsoft.Office.Interop.Excel;
using Forms = System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
using System.Text;

    private Dictionary<string, string[]> getSheetsDict()
        {
            Excel.Workbook wb =  Globals.ThisAddIn.Application.ActiveWorkbook;
            Dictionary<string, string[]> dSheets = new Dictionary<string, string[]>();

            if (wb.Sheets.Count > 0)
            {
                foreach (Excel.Worksheet sheet in wb.Sheets)
                {
                    //string[] sDetails = { sheet.CodeName, Convert.ToString(sheet.Visible) };
                    string[] sDetails = { sheet.CodeName, (sheet.Visible == true) }; //Error 1
                    string[] sDetails = { sheet.CodeName, (sheet.Visible == Excel.XlSheetVisibility.xlSheetVisible) }; //Error 2
                    dSheets.Add(sheet.Name, sDetails);
                }
            }

            return dSheets;
        }

A: Sorry I missed this, I come from VBA where boolean can be implicitly converted to String.
I defined the array as an array of Objects instead of Strings. Reverberated the change through my code and not it's running smoothly.
Object[] sDetails = { sheet.CodeName, sheet.Visible };


text:
Q: Is there a Good Illustrative Example where the Hinge Loss (SVM) Gives a Higher Accuracy than the Logistic Loss Vladimir Vapnik wrote:

"When solving a problem of interest, do not solve a more general
problem as an intermediate step. Try to get the answer that you really
need but not a more general one."

Vapnik wrote this in the context of transductive learning, but the principle could also be applied to statistical pattern recognition tasks.  If we just need to perform a hard classification, then we should aim to determine the decision boundary directly, rather than estimating the posterior probability of class membership and then threshold that at 0.5 (or some other threshold depending on the misclassification costs).  In principle, we may be able to get better generalisation in terms of accuracy by following this principle as it focusses on the needs of the application, and avoids modelling compromises that benefit modelling of aspects of the data that are not relevant to the application at the expense of other aspects that are.
The performance of the SVM on real-world problems suggest that there may be some merit in this, but it is not easy to find a clear example where this is demonstrably the case.  Can anyone suggest an example where a SVM will give better performance than an equivalent logistic regression model (i.e. kernels and regularisation should be available for the logistic regression model, so we are just comparing the loss used, rather than the other aspects of the models)?  Preferably the example should demonstrate why this is the case.
Obviously the no-free lunch theorem suggests that no classifier system is going to be superior for all datasets, and the theoretical justification for the SVM is largely a worst-case analysis, so the SVM may be better in pathologically difficult problems, but not necessarily the average case.
Personally I prefer kernel logistic regression over the support vector machine, largely because the hyper-parameter tuning is much easier, and I think they are likely to give broadly similar results.  However, I have an open mind where the needs of the application mean that the limitations of the SVM (e.g. having to know misclassification costs a-priori) are not a problem.
Please can we avoid discussions of whether accuracy is a good performance metric.  It has issues, but there are some applications where accuracy is the relevant statistic of interest, and there have already been good discussions of this topic.
Note the answer here is the sort of thing I am looking for, but unfortunately it isn't correct (see my comment on the answer).

A: The example attributed to Olivier Bousquet doesn't work as clearly as depicted in the blog post mentioned in an answer to a related question, but I have been able to make it work to some extent in a more realistic setting, so I'll post it here in case it stimulates further (hopefully simpler or more informative) examples.
The (of course) adversarial learning task is shown below.  The probability of membership of the positive class is given by
$$p(\mathcal{C}_+|x) = \frac{0.5}{(1 + \exp(-100*x))} + 0.25 + 0.24*\sin(20*x)$$

Note there are features of the true probability of class membership that do not affect the decision boundary, so any model may be distracted by modelling those irrelevant undulations at the expense of accurately determining the optimal decision boundary.  To demonstrate that Bousqet's example builds a series of logistic regression-style models, of increasing complexity, based on Legendre polynomials (for numerical considerations).  Here are the first seven basis functions:

The blog example is implemented in Mathmatica, which is a language I don't know, but I have been able to replicate their results in MATLAB tolerably well.  What I think they have done is to fit these Legendre polynomial models firstly using the cross-entropy metric, and then using the hinge loss, but rather strangely they have fitted it directly to the true (sampled) probability of class membership, i.e. the response values lie between 0 and 1.  Using the cross-entropy, I get this result:

Which is broadly the same as the Mathmatica implementation.  Note that in the attempt to model the undulations in the probability of class membership, the model has overshot on occasion and so the accuracy is lower than we would get by simply placing a threshold at $x = 0$.
It wasn't completely clear how to implement the model with the hinge loss, as the logistic function clips the output to lie in the range of 0 to 1, so instead I used the hinge loss on the weighted sum of the Legendre basis functions and then afterwards applied the logistic function.  This is the result:

All the models now achieve the optimal accuracy, although the estimates of the posterior probability of class membership are clearly inferior (if not actually plain wrong!).
HOWEVER this is not what we actually do when we have a classification task.  If we knew the optimal posterior probability of class membership to determine the targets for the training data, we probably wouldn't need to build a classifier in the first place!  So I then modified the code so that instead of the response values being the sampled true probability, I generated random x values (uniform distribution from -1 to +1) and then generated binary responses according to the probability of class membership.
This is the result for the cross-entropy error metric, which is pretty much the same as before.

Here is the result for the hinge loss, which is very different.

So why the difference?  Well in the blog version, if we set the weight "linear" term to a very high value, then the weighted sum will be less than -1 for all of the data to the left of $x = 0$ and a value greater than +1 for all of the data on the right.  In which case, the hinge loss will be zero, and we will get a classifier with minimal error regardless of model complexity.  The hinge loss cannot be negative.  However, if we sample the labels from a conditional Bernoulli distribution, we will have data on both sides of $x=0$ that are both positively and negatively labelled, and if they are the wrong side of $x=0$ they will have a non-zero hinge loss, and hence we will start penalising models with a large linear term increasingly harshly.  It does have some excess error caused by trying to model the right-most undulation, but it does see to be more robust in terms of accuracy than the cross-entropy loss.  So it is an example of how trying to classify the data directly, rather than estimate probability and then threshold, it just isn't as clear cut as the example in the blog suggests.
Update #1:  Here are the results with a larger dataset (so sampling noise is less likely to be a factor).  For the previous results I used 1024 training patterns, and for these I used 65536 (I work in a computer science department ;o).  It seems to improve things a bit for the hinge loss, but the cross-entropy results look broadly similar.
Cross-entropy loss:

Hinge loss:

It is interesting (i.e. worrying) that for some of the simpler models, the output does not go through $(0, 1/2)$...
FWIW, this is the most complex of the hinge-loss models without the logistic transformation (but with an offset of 0.5 to make it easier to compare with the probabilities).

A: The results you shared are fascinating. Here's some more exploration in a similar direction.
The idea behind the Bousquet example is to create a situation where optimizing the logistic loss prioritizes fitting the underlying probability distribution at the expense of accuracy. But, it's not clear to me that accuracy and fit to the distribution would have to be opposed here. For example, it seems like a model that exactly matches the underlying distribution should yield both optimal accuracy and optimal logistic loss (at least in expectation).
I'll build a similar example that tries to simplify things, with only two models in the hypothesis space. One gives better accuracy but worse fit to the underlying distribution, and the  other does the opposite. The tension between these two objectives is explicitly baked into the problem. I'll work directly with expected losses, so issues related to finite samples and/or optimization won't play any role.
True distribution
Suppose each point $x$ is drawn i.i.d. from the uniform distribution on $[-1, 1]$ and its class label $y \in \{-1, +1\}$ is drawn from a Bernoulli distribution $p(y \mid x)$. Similar to the Bousquet example, the conditional probability of the positive class is a 'wavy step function' (see plot below):
$$p(y=1 \mid x) =
.598 \ \sigma(100 x) - .201 + .2 \sin(20 x)$$
where $\sigma$ is the logistic sigmoid function.
Models
Suppose our hypothesis space contains only two models (with no free parameters so 'fitting' means choosing one or the other):

The first model is a step function:
$$\hat{p}_1(y=1 \mid x) = \begin{cases}
  \sigma(1) & x \ge 0 \\
  \sigma(-1) & x < 0 \\
\end{cases}$$
The second is a wavy step function, similar to the true distribution, but with slightly different parameters:
$$\hat{p}_2(y=1 \mid x) =
.398 \ \sigma(100 x) - .301 + .3 \sin(20 x)$$
Where needed (e.g. for computing the hinge loss), 'raw' classifier outputs are computed as $f(x) = \operatorname{logit}(\hat{p}(y=1 \mid x))$. Since we're interested in accuracy, point predictions are computed as the mode of the predicted distribution over class labels (equivalent to the sign of the 'raw' output), which is the optimal decision under the 0-1 loss.

Note that the hypothesis space doesn't contain the true distribution. We're forced to choose between two approximations that make different tradeoffs. The first model (step function) is designed to make more accurate point predictions, at the expense of fit to the underlying distribution. In contrast, the second model (wavy step) is designed to match the underlying distribution better, at the expense of accuracy. To confirm that these tradeoffs are indeed present, the table below shows the expected 0-1 loss (better for model 1) and expected KL divergence from the true distribution to the model (better for model 2).
Hinge vs. logistic loss
Here are the expected losses for each model, where the expectation is taken w.r.t. the true data generating process (calculated by numerical integration). The best model according to each loss function is shown in bold+parentheses:
$$\begin{array}{rc}
  & \text{Model 1 (step)} & \text{Model 2 (wavy step)} \\
  \text{0-1} & \mathbf{(.208)} & .269 \\
  \text{KL} & .113 & \mathbf{(.044)} \\
  \text{Hinge} & \mathbf{(.416)} & .580 \\
  \text{Logistic} & .521 & \mathbf{(.474)} \\
\end{array}$$
Suppose we choose a model from our hypothesis space by minimizing the expected loss (i.e. what empirical risk minimization tries to do by proxy). As the table shows, minimizing the hinge loss gives the first model (prioritizing accuracy), whereas minimizing the logistic loss gives the second model (prioritizing fit to the underlying distribution).
Notes
Contrary to this example, accuracy and fit to the underlying distribution aren't always opposed. Even when such a conflict exists, the hinge and logistic losses may not necessarily behave as shown above.
For example, the amplitude of model 1's step function matters. It doesn't affect the accuracy (which only depends on the sign), but it does affect the hinge loss. Increasing the amplitude too far (overconfidence) incurs increasing penalties for misclassified points. And, shrinking it too far (underconfidence) penalizes correct predictions, which increasingly fall inside the margin. In both cases, the hinge loss will eventually favor the second model, thereby accepting a decrease in accuracy. This emphasizes that: 1) the hinge loss doesn't always agree with the 0-1 loss (it's only a convex surrogate) and 2) the effects in question depend on the hypothesis space.
In practice, I'd bet that regularization plays an important role too, together with the model selection algorithm. For example, regularization strength is often chosen to maximize validation set accuracy. Even if the logistic loss is used to fit the parameters, using the 0-1 loss for model selection might sacrifice fit to the underlying distribution in favor of accuracy.