text:
Q: how to write review on Amazon market using app? I want to write a review on amazon market from my application.
However I can do this for android market using this code.
Uri marketUri = Uri.parse("market://details?id=" + getPackageName());
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(marketUri);
startActivity(intent);

Than what should I do for doing same thing for Amazon market ?

A: For Amazon App Store check this link https://developer.amazon.com/help/faq.html It has a lot of helpful info. The answer to your question is under "Marketing"
Intent goToAppstore = new Intent(Intent.ACTION_VIEW,
       Uri.parse("http://www.amazon.com/gp/mas/dl/android?p=com.jakar.myapp"));
       goToAppstore.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       context.startActivity(goToAppstore);

That will open the Amazon App store to myapp. (switch "com.jakar.myapp" with your package name of course).
For supporting both Android and Amazon marketplaces with the same APK file see this: How to support Amazon and Android Market (Google Play) links in same APK

A: Just use this code, nothing special:
Uri marketUri = Uri.parse("<link-to-the-amazon-market>");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(marketUri);
startActivity(intent);

This intent will work with any kind of Uri's it recognizes, if there is no special Uri form for the Amazon Market, just redirect the user to market's web page. Hope this helps.


text:
Q: $X = E(Y | \sigma(X)) $ and $Y = E(X | \sigma(Y))$ Suppose $X, Y$ are random variables in $L^2$ such that $$X = E(Y | \sigma(X)) $$ $$Y = E(X | \sigma(Y))$$ Then I want to show that $X=Y$ almost everywhere.
What I've done:

By conditional Jensen $$E(X^2|\sigma(Y)) \geq E(X|\sigma(Y))^2 = Y^2 $$ a.e and thus $||X||_2 \geq ||Y||_2 $. Analogously $||Y||_2 \geq ||X||_2 $ and so $||Y||_2 = ||X||_2$. Moreover $$E(XY|\sigma(Y)) = YE(X|\sigma(Y)) = Y^2 $$ This implies that $$\int_{\Omega}(X-Y)^2 dP = 0 $$ and thus $X=Y$ a.e.

Is it correct ?

A: It is correct. Maybe some details can be added, for example just after the first displayed equation, we could add "and thus, taking the expectation, $\mathbb E\left[X^2\right] \geqslant \mathbb E\left[Y^2\right] $". And there is no need to work with the $\mathbb L^2$-norm as we only consider the square of expectations.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set icon or logo for extension in vscode I've created an extension for vscode (not yet published, only installed localy), how can I set an icon to be seen in the section of the extensions in vscode?

A: You can set the icon in the extension's package.json file, which is also called "extension manifest".
The field in which you set the path to an icon is called "icon". The icon file itself has to be 128x128 pixels. As noted by Philipp Kief in the comments, you should use a PNG file, not an SVG.
Example:
{
    "name": "extension-name",
    "displayName": "Extension Name",
    "description": "...",
    "icon": "images/spellIcon.png",
    "version": "0.0.1",
      ...

More on VS Code's official page.

A: The above answer is legit. But when i added the icon in package.json. It gave me a wired error saying "HTTPS protocol is not specified". I fixed it by using the repository key in it as:
"icon": "assets/images/qs-icon.png",
  "repository": {
    "type": "git",
    "url": "https://github.com/Mubashar-javed/quick-snippets"
  },


text:
Q: Why is font not listed by fc-list after running fc-cache on font Im working on a linux blackbox system, uname -a gives
 Linux 0247 3.3.4-ROMROOT-NT1 #1 Fri Nov 17 14:46:03 JST 2017 armv7l GNU/Linux

There is only one font on the system
 /usr/lib/fonts/ipag.ttf

but fc-list return nothing
So I try to install it properly
[root@0247]# sudo fc-cache -rv /usr/lib/fonts
/usr/lib/fonts: caching, new cache contents: 1 fonts, 0 dirs
/var/cache/fontconfig: cleaning cache directory
/root/.cache/fontconfig: not cleaning non-existent cache directory
/root/.fontconfig: not cleaning non-existent cache directory
fc-cache: succeeded

font seems to be installed, but still fc-list returns nothing, why is that ?


text:
Q: AJAX working locally but not on Server Error i am getting when running on server :
TypeError: Cannot read property 'documentElement' of null

I am using AJAX to retrieve XML from a PHP file and place the response in my HTML div.
Javascript file is for creating the AJAX object and handing server response.
When i run this code locally, everything is working fine.
What is going wrong? I am only uploading the same files to the server so it should work there as well?
PHP Code:
<?php
header('Content-Type: text/xml');

echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';

echo '<response>';

$food      = $_GET['food']; //GET/POST to send the data (code to send data inside js file)
$foodArray = array(
    'tuna',
    'bacon',
    'beef',
    'meat'
);

if (in_array($food, $foodArray))
    echo 'We do have ' . $food;

elseif ($food == '')
    echo "AJAX. Server response will be displayed here";
else
    echo 'Sorry! We don\'t sell ' . $food;
echo '</response>';
?>

Javascript Code:
var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject() {
    var xmlHttp;

    if (window.XMLHttpRequest) {

        xmlHttp = new XMLHttpRequest();

    } else {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xmlHttp;
}

function process() {
    if (xmlHttp) {
        try {
            food = encodeURIComponent(document.getElementById("userInput").value);

            xmlHttp.open("GET", "foodstore.php?food=" + food, true);

            xmlHttp.onreadystatechange = handleServerResponse;

            xmlHttp.send(null);
        } catch (e) {
            alert(e.toString());
        }
    } else {
        setTimeout('process()', 100);
    }
}

function handleServerResponse() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                xmlResponse = xmlHttp.responseXML;
                xmlDocumentElement = xmlResponse.documentElement; // Root element of XML file.
                message = xmlDocumentElement.firstChild.data; //Cox it is the only child in the xml document. Data - Output of XML content. So now, message contains the O/P of php.
                document.getElementById("underInput").innerHTML = message; //Now that we got the echo statement from the server, we want to store it in our div.
                //innerHTML - The html in between the div. The stuff that shows on the web page :)
            } catch (e) {
                alert(e.toString());
            }
            setTimeout('process()', 100);

        } else {
            alert(xmlHttp.statusText);
        }
    }

HTML:

Enter a food item you would like to search: e.g. bacon

<input type="text" id="userInput"/>

A: *

*AJAX requests for XML files should use the application/javascript mime/media type, there is no such thing as "text/xml".
header('Content-Type: application/xml');

*The first element in the AJAX request needs to have an XML namespace...

*You don't send an XML declaration for AJAX requests, just full-page requests.

*Download a copy of Fiddler2, preferably an older version (2.2.9.1 still has the text label on the remove button, newer is not always better) where you can see the HTTP status codes.

*Watch your Apache access log as well to see where requests are going.

*Always alert() yurself to what is going on...

This code is in a REUSABLE AJAX script, pass the parameter 'id_container_pos' to choose HOW XML is AJAX-loaded on to the page...
if (window.XMLHttpRequest) {var xmlhttp = new XMLHttpRequest();}
else if (window.ActiveXObject) {try {xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');} catch (e) {try {xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');} catch (e) {}}}
else {alert('Error: Your browser does not seem to support AJAX.');}
xmlhttp.open('GET',url,true);
xmlhttp.send(null);

xmlhttp.onreadystatechange = function()
{
 if (xmlhttp.readyState=='4')
 {
  //alert(xmlhttp.responseText);
  //If you have an element with a 'body' ID that is all lowercase, this is IE8 versus good browsers...
  if (!document.getElementById('Body') && xmlhttp.responseXML) {var xmlDoc=xmlhttp.responseXML;}
  else {var xmlDoc = xmlhttp.responseText;}

  if (id_container_pos=='after') {id_container_obj.insertBefore(xmlDoc.getElementsByTagName('div')[0],id_container_obj.nextSibling);}
  else if (id_container_pos=='before')
  {
   id_container_obj.parentNode.insertBefore(document.importNode(xmlDoc.getElementsByTagName('div')[0],true),id_container_obj);
   }
  else if (id_container_pos=='inside') {id_container_obj.appendChild(document.importNode(xmlDoc.getElementsByTagName('div')[0],true));}
  else if (id_container_pos=='replace') {var r = id_container_obj.parentNode; r.removeChild(r.getElementsByTagName('div')[0]); r.appendChild(document.importNode(xmlDoc.getElementsByTagName('div')[0],true));}
 }
}


text:
Q: Swift, implement same delegate two times (without multicast) Given a very simple protocol :
protocol TheProtocol {
    func doSomething()
    func doSomethingElse()
    func doThis()
    func doThat()
}

I have a class Base that has a delegate waiting to be set.
// Can't modify this class at all
class Base  {
    public var delegate: TheProtocol?
}

My second class B inherits from this class Base, and implements TheProtocol in order to set the delegate to itself.
class B: Base, TheProtocol {

    override init() {
        super.init()
        self.delegate = self
    }

    func doSomething() {

    }
    func doSomethingElse() {

    }
    ... other methods to implement
}

Now what I want to be able to do, is to have a last class C, that contains an instance of B, and also set the delegate. I want the delegate to work both inside B and C.
The major constraint is that I can't modify the Base class.
class C: TheProtocol {

    var obj = B()

    init() {
        // If I do this it won't fire within B anymore
        obj.delegate = self
    }

    func doSomething() {

    }
    func doSomethingElse() {

    }
    ... other methods to implement
}

A: It is actually possible using a Proxy delegate. However not really recommended.
In Swift, how do I have a UIScrollView subclass that has an internal and external delegate?


text:
Q: Question with conditional probability You ask a neighbor to water a sickly plant while you are on vacation. Without water the plant will die with probability 0.9. With water it will die with probability 0.5. You are 87 % certain the neighbor will remember to water the plant.
When you are on vacation, find the probability that the plant will die.
Ok so for this I was thinking you just multiply.9 x .5 to get .45 from an example I have seen. Why would this be wrong?
You come back from the vacation and the plant is dead. What is the probability the neighbor forgot to water it?
This is what I have done and it keeps coming back wrong. P(neighbor forgets|plant dies w/o water) = (1-.87)(.9) = .117
What do I keep doing wrong?

A: HINT:
The plant dying while you're on vacation happens if either:

*

*The neighbor waters it but it dies

*The neighbors forgets to water and then it dies.

The probabilities for each are different, and they need to be added together.
Edit: For the second bit, recall the formula $$P(A | B) = \frac{P(A \cap B)}{P(B)}$$ So we need to find P(neighbor forgets | plant dies) = P(neighbor forgets and plant dies) / P(plant dies). Can you complete it now?


text:
Q: Browser/postman not wait for @Async Spring MVC Controller Response? I am using SpringMVC with AngularJS. I made one controller which I want to call asynchronously but when I send POST request from Postman for testing it will return immediately without waiting for the response. I also tried Callable, Executor but nothing works. When I remove @Async it works fine. Can any one please help?
@RestController
public class GenServiceController {

@Autowired
private GenService service;

@RequestMapping(value = "/log", method = RequestMethod.POST)
@ExceptionHandler(ForbiddenErrorCodeException.class)
@ResponseBody
@Async
public DeferredResult<CustomResponse> log(@RequestBody TestInfo testInfo,
                            @RequestHeader(value = "Authorization") String accessToken) throws ForbiddenErrorCodeException {

    String decodedAccessToken = null;
    CustomResponse customResponse = null;
    final DeferredResult<LogResponse> deferredResult = new DeferredResult<>();
    if (!Utils.isNullOrTrimEmpty(accessToken)) {
        accessToken = accessToken.replaceFirst("Basic" + " ", "");
        decodedAccessToken = Utils.decodeBase64(accessToken);
        final StringTokenizer tokenizer = new StringTokenizer(decodedAccessToken, ":");
        final String token = tokenizer.nextToken();

        if (!service.isTokenExists(token)) {
            System.out.println("Invalid Token");
        } else {
            response = service.sendMessages(testInfo);
            if (response != null) {
                deferredResult.setResult(response);
            }
        }
    }
    return deferredResult;
}

}

A: You do not need to annotate your method with Async -- it doesn't make sense in your scenario. Just return either a DeferredResult<CustomResponse> or a Callable<CustomResponse>.


text:
Q: java get all possible variants (positive and negative) Lets say I got a row of number "1 2 3 4"
I need to get all possible values
1+2+3+4
1+2+3-4
1+2-3+4
1+2-3-4
...
-1-2-3-4

tried to write a recursion
but it kinda works with "1 2" and "1 2 3"
it should work with 1 2 3 ... n
checkSum(0, list.size(), list);

private void checkSum(int start, int end, List<Long> list) {

    for (int i = start; i < end; i++){
        list.set(i, list.get(i) * (-1L));
        printLine(list);
        checkSum(i+2, end, list);
    }
}

private void printLine(List<Long> list) {
    for (int i = 0; i < list.size(); i++) {
        if (i > 0)
            if (list.get(i) > 0L)
                System.out.print("+");
        System.out.print(String.valueOf(list.get(i)));
    }
    System.out.println();
}

A: I have an approach that can give you some really cool ideas.
I didn't it with recursion, recursion is good, but you need be careful with memory issues when you use it. If you put a big list you can be faced with Stack Overflow errors.
Ok, my solution takes advantage of the binary system.
so, in binary, counting from 0 to 8
    0 0 0 0
    0 0 0 1
    0 0 1 0
    0 0 1 1
    0 1 0 0
    0 1 0 1
    0 1 1 0
    0 1 1 1
    1 0 0 0

Have you got it? you can consider the ones as negative signal. You can apply a mask to get the value.
your mask starts with 1 and goes on like:
0 0 0 1
0 0 1 0
0 1 0 0
1 0 0 0

in this way you can test the values.
So, the code:
    public static void listPermutation(List<Long> l) {
        for (int i = 0; i <= Math.pow(2,l.size()) - 1; i++) {
            List<Long> l2 = new ArrayList<Long>(l);
            applyMask(l2, i);
        }
    }

    public static void applyMask(List<Long> l, long counter) {

        long mask = 1L;
        for (int i = l.size() - 1; counter >= mask; i--) {
            if ((mask & counter) > 0) // here testing if the bit is 1 or 0
                l.set(i, l.get(i) * -1);

            mask <<= 1;
        }
        printLine(l); // System.out.println(l);
    }

Example,
        List<Long> l = new ArrayList<Long>();
        l.add(1l);
        l.add(2l);
        l.add(3l);
        l.add(4l);

        listPermutation(l);

results in,
1+2+3+4
1+2+3-4
1+2-3+4
1+2-3-4
1-2+3+4
1-2+3-4
1-2-3+4
1-2-3-4
-1+2+3+4
-1+2+3-4
-1+2-3+4
-1+2-3-4
-1-2+3+4
-1-2+3-4
-1-2-3+4
-1-2-3-4

At point of speed, it's not bad:
        List<Long> l = new ArrayList<Long>();
        l.addAll(Arrays.asList(new Long[] { 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L }));

        long initTime = System.currentTimeMillis();
        listPermutation(l);
        long finalTime = System.currentTimeMillis();

        System.out.println(finalTime - initTime + " ms");

        2833 ms

Maybe (probably) this is not the best way to do that, but I'm sure that will improve your mind :)

A: One of a billion ways of doing it below...
public class Thingy {

    public static void main(String[] args) {
        printAll(0, 0, Arrays.asList(1L, 2L, 3L, 4L), "TEST1> ");
        printAll(0, 0, Arrays.asList(5L, 6L, 3L, 8L, 9L), "TEST2> ");
    }

    private static void printAll(int i, long accumulator, List<Long> source, String output) {
        if(i >= source.size()) {
            System.out.println(output + " = " + accumulator);
        } else {
            long n = source.get(i);
            printAll(i + 1, accumulator + n, source, output + " + " + n);
            printAll(i + 1, accumulator - n, source, output + " - " + n);
        }
    }
}

Output...
TEST1>  + 1 + 2 + 3 + 4 = 10
TEST1>  + 1 + 2 + 3 - 4 = 2
TEST1>  + 1 + 2 - 3 + 4 = 4
TEST1>  + 1 + 2 - 3 - 4 = -4
TEST1>  + 1 - 2 + 3 + 4 = 6
TEST1>  + 1 - 2 + 3 - 4 = -2
TEST1>  + 1 - 2 - 3 + 4 = 0
TEST1>  + 1 - 2 - 3 - 4 = -8
TEST1>  - 1 + 2 + 3 + 4 = 8
TEST1>  - 1 + 2 + 3 - 4 = 0
TEST1>  - 1 + 2 - 3 + 4 = 2
TEST1>  - 1 + 2 - 3 - 4 = -6
TEST1>  - 1 - 2 + 3 + 4 = 4
TEST1>  - 1 - 2 + 3 - 4 = -4
TEST1>  - 1 - 2 - 3 + 4 = -2
TEST1>  - 1 - 2 - 3 - 4 = -10
TEST2>  + 5 + 6 + 3 + 8 + 9 = 31
TEST2>  + 5 + 6 + 3 + 8 - 9 = 13
TEST2>  + 5 + 6 + 3 - 8 + 9 = 15
TEST2>  + 5 + 6 + 3 - 8 - 9 = -3
TEST2>  + 5 + 6 - 3 + 8 + 9 = 25
TEST2>  + 5 + 6 - 3 + 8 - 9 = 7
TEST2>  + 5 + 6 - 3 - 8 + 9 = 9
TEST2>  + 5 + 6 - 3 - 8 - 9 = -9
TEST2>  + 5 - 6 + 3 + 8 + 9 = 19
TEST2>  + 5 - 6 + 3 + 8 - 9 = 1
TEST2>  + 5 - 6 + 3 - 8 + 9 = 3
TEST2>  + 5 - 6 + 3 - 8 - 9 = -15
TEST2>  + 5 - 6 - 3 + 8 + 9 = 13
TEST2>  + 5 - 6 - 3 + 8 - 9 = -5
TEST2>  + 5 - 6 - 3 - 8 + 9 = -3
TEST2>  + 5 - 6 - 3 - 8 - 9 = -21
TEST2>  - 5 + 6 + 3 + 8 + 9 = 21
TEST2>  - 5 + 6 + 3 + 8 - 9 = 3
TEST2>  - 5 + 6 + 3 - 8 + 9 = 5
TEST2>  - 5 + 6 + 3 - 8 - 9 = -13
TEST2>  - 5 + 6 - 3 + 8 + 9 = 15
TEST2>  - 5 + 6 - 3 + 8 - 9 = -3
TEST2>  - 5 + 6 - 3 - 8 + 9 = -1
TEST2>  - 5 + 6 - 3 - 8 - 9 = -19
TEST2>  - 5 - 6 + 3 + 8 + 9 = 9
TEST2>  - 5 - 6 + 3 + 8 - 9 = -9
TEST2>  - 5 - 6 + 3 - 8 + 9 = -7
TEST2>  - 5 - 6 + 3 - 8 - 9 = -25
TEST2>  - 5 - 6 - 3 + 8 + 9 = 3
TEST2>  - 5 - 6 - 3 + 8 - 9 = -15
TEST2>  - 5 - 6 - 3 - 8 + 9 = -13
TEST2>  - 5 - 6 - 3 - 8 - 9 = -31

A: For your interest, a solution using Java 8 streams and no recursion:
public class ComboCollector {
    private List<String> list = Collections.singletonList("");

    private ComboCollector accept(String n) {
        list = Stream.concat(
                list.stream().map(v -> v + "+" + n), list.stream().map(v -> v + "-" + n))
           .collect(Collectors.toList());
        return this;
    }

    private ComboCollector combine(ComboCollector other) {
        other.list.stream().forEach(this::accept);
        return this;
    }

    public Stream<String> getResult() {
        return list.stream();
    }
}

public static void main(String[] args) {
    IntStream.range(1, 10).mapToObj(Integer::toString)
        .collect(ComboCollector::new, ComboCollector::accept, ComboCollector::combine)
        .getResult().forEach(System.out::println);
}

I'm not necessarily recommending this approach but just wanted to demonstrate a different mechanism than traditional recursion.


text:
Q: Unity AR UI not showing up I have created a simple Unity AR Foundation app which places objects on a plane whenever the screen is touched. I would like to add some UI so the user can press a button rather than anywhere on the screen.
I have followed several different tutorials which seem to be doing mostly the same thing. I right-click the Hierarchy -> UI -> Button. I have scaled it so it should fit my mobile screen and anchored it to the center so it should be easy enough to find.
These are the canvas settings:

Might the UI somehow be hidden behind the camera feed from the AR Session Origin -> AR Camera? Am I missing any steps to anchor the UI to the screen?
As you can probably tell, I am very new to Unity but I feel like I have followed the tutorials for creating a UI, but it simply won't show. If you need more information, please just ask and I will provide.

A: Not sure but sounds like you might need to have that Canvas Scalar to scale with the screen size. Change the UI scale mode to Scale with Screen Size.

A: I was compiling the wrong scene. I had two very similar scenes, so when I compiled I didn't realize there were no changes and that I was inspecting the entirely wrong scene.
Once I changed to the correct scene the setup above worked as expected.


text:
Q: jQuery UI Button doesn't work after disabled/enabled from iframe I have some code for jQuery, see below:
$(function(){
    $('button#submit').button({disabled:true});
    $('button#submit').click(function(){
        console.log('It works!');
    });
    $('a#button-enable').click(function(){
        $('button#submit').button({disabled:false});
    });
});

If the link with id button-enable isn't clicked, the button must be disabled. After that the button must be enabled and If I click on it, in the console must be outputed the text It works!. Why is it not happening?
It happens when I enabled the button from the iframe.

A: Try
$(function(){
    $('button#submit').button("option", "disabled", true );
    $('a#button-enable').click(function(){
        $('button#submit').button("option", "disabled", false);
        $('button#submit').click(function(){
            alert('It works!');
        });
    });
});

This is from http://jqueryui.com/demos/button/#option-disabled
Here is a jsfiddle: http://jsfiddle.net/tmx8t/

A: I've cleaned up your code a bit and made it work like you described.
$(function() {
    var button = $('#submit').button({
        disabled: true
    }).click(function() {
        alert('It Works');
    });
    $('#button-enable').click(function() {
        button.button('enable');
    });
});

Check out the fiddle here

A: Thank you all for your answers. I solved the problem in the following way:
parent.html
$(function{
    $('button, input[type="submit"]').button();
    $('button#submit').button('disable');
    $(document).bind('enableButton',function(){
        $('button#submit').button('enable');
    });
    $('button#submit').click(function(){
        //...
    });
});

iframe.html
$(function(){
    //...
    parent.$(parent.document).trigger('enableButton');
});


text:
Q: Dual monitors dual OS's? Quick and painless, I have a partitioned SSD with win 7 and Linux back box on it and I just bought a second monitor. I was wondering if one monitor could display win7 and the other back box off the same drive? Thanks in advance.

A: If you're dual booting, no. Only one OS can be running at a time.
What you could do is virtualize the second OS. e.g. boot into Windows and use a program like VirtualBox or VMware Player to run a virtual machine on which you install Black Box.
You can then have the console for the Virtual Machine on the other screen, possibly full screen depending on which software you use, and interact with them at the same time.


text:
Q: Question Simplifying Summation $$ \sum\limits_{i=0}^{\infty} p(i) = \sum\limits_{i=0}^{n} \binom nip^i(1-p)^{n-i} = [\ p + (1-p)]^n = 1 $$
I don't understand how ni turns into p. If you multiply pi to (1-p)n-i it become (1-p)n but what happens to the ni and where does the p at the beginning come from.


text:
Q: Cannot connect to Ubuntu Server via SSH over wireless LAN I installed Ubuntu Server 18.04 in my Raspberry Pi 3B Plus. I configured everything and successfully log in to my account via SSH Private Key on ethernet. However, when it comes to wireless connection, PuTTY stucks while connection time out appears. Configuration was done here:
/etc/ssh/sshd_config
Everything seems pretty well. When I checked built-in wlan0, it gets IP address. I don't find out where it is wrong. Any help would be great.
$ netstat tlnp
State    Recv-Q    Send-Q        Local Address:Port        Peer Address:Port
LISTEN   0         128           127.0.0.53%lo:53               0.0.0.0:*
LISTEN   0         128                 0.0.0.0:35600            0.0.0.0:*
LISTEN   0         128                    [::]:35600               [::]:*

$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether XX:XX:XX:XX:XX:XX brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.103/24 brd 192.168.1.255 scope global dynamic eth0
       valid_lft 2402sec preferred_lft 2402sec
    inet6 XXXX::XXXX:XXXX:XXXX:XXXX/64 scope link
       valid_lft forever preferred_lft forever
3: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether XX:XX:XX:XX:XX:XX brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.105/24 brd 192.168.1.255 scope global dynamic wlan0
       valid_lft 2405sec preferred_lft 2405sec
    inet6 XXXX::XXXX:XXXX:XXXX:XXXX/64 scope link
       valid_lft forever preferred_lft forever

A: Most probably, It is not a configuration issue.
It is the issue of ip.
type ifconfig and get the ip of wifi connection and use it to connect to the server via ssh. That's it.
If not working, reply with your ssh config in comment.


text:
Q: DELETE-OUTPUT-INTO performance At first I would like to place two code samples
Sample 1
INSERT INTO TableB
SELECT *
FROM
 TableA AS A
WHERE
 A.SomeColumn = @someValue

DELETE A
FROM
  TableA AS A
WHERE
  A.SomeColumn = @someValue

Sample 2
DELETE A
FROM
  TableA As A
OUTPUT
  DELETED.*
INTO
  TableB
WHERE
  A.SomeColumn = @someValue

Here, two codes satisfy the same goal. We are actually moving some rows from TableA to TableB.
Which code sample should perform better? Does the performance of DELETE-OUTPUT-INTO clause depend on the amount of deleted rows?


text:
Q: Cast int to void* and void* to int for TMemoryStream->WriteBuffer (C++Builder XE7) I use TMemoryStream class and its WriteBuffer method for writing data to stream. I need to write and read int variable.
void __fastcall WriteBuffer(const void *Buffer, int Count)
void __fastcall ReadBuffer(void *Buffer, int Count)

Is following code correct or no?
writing:
int i = 5;
stream->WriteBuffer((void*)&i, sizeof(int));

reading:
stream->ReadBuffer((void*)&i, sizeof(int));

A:
Is following code correct or no?

Yes.  Though the type-cast is not necessary as any pointer can be passed to a void* (taking const-correctness into account, of course):
int i = 5;
stream->WriteBuffer(&i, sizeof(int));

int i;
stream->ReadBuffer(&i, sizeof(int));


text:
Q: Lambert Function Question Given $y$, for the Lambert $W$ function $y=xe^x\implies W(y)=x$, can you determine $x$? Specifically, how would you evaluate $e^{W(-1/3)}$ without a calculator?

A: Numerical methods are the only way if you don't have access to Lambert function. Newton  iterative schemes converge quite fast.
Suppose that you want to solve $x e^x= k$. Provided a guess $x$, it will be updated by $$\frac{k e^{-x}+x^2}{x+1}$$ if you use Newton method.
For illustration purposes, let me consider the case where $k=100$ and admit that I am so lazy that I start iterating at $x=2$.
For Newton method, the successive iterates will then be $5.84451$, $5.03292$, $4.30675$, $3.74915$, $3.45533$, $3.38852$, $3.38564$, $3.38563$ which the solution.
However, if you write the equation as $x +\log x=\log k$, the updating formula will be $$\frac{x (\log (k)-\log (x)+1)}{x+1}$$ For the same example as before, the successive iterates will then be $3.27468$, $3.38520$, $3.38563$ which the solution.

A: $$x\cdot\exp(x)=a\iff x=a\cdot\exp(-x)\iff x=a\cdot\exp(-a\cdot\exp(-a\cdot\exp(\ldots)))$$


text:
Q: CSS for Button shine effect with an Input element I want a shine effect on my button which originally is an html input element (I don't want to change that). I have made a bootply but don't know how to get it the right way.

/* CSS used here will be applied after bootstrap.css */
body{
    background: #888;
}

span.button {
    width: 100%;
    height: 50px;
    /*background: #333;*/
    display: block;
    position: relative;
    margin: 50px auto 0;
    overflow: hidden;
    /*border: 1px solid #333333;*/
    /*color: white;*/
    text-decoration: none;

    -webkit-box-shadow: inset 0px 1px 1px 0px rgba(255,255,255,.4);
    -moz-box-shadow: inset 0px 1px 1px 0px rgba(255,255,255,.4);
    box-shadow: inset 0px 1px 1px 0px rgba(255,255,255,.4);

    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;

    -webkit-transition: all 0.2s ease;
    -moz-transition: all 0.2s ease;
    -ms-transition: all 0.2s ease;
    -o-transition: all 0.2s ease;
    transition: all 0.2s ease;

    background-color: hsl(131, 100%, 5%) !important;
    background-repeat: repeat-x;
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#3CCC77", endColorstr="#00190B");
    background-image: -khtml-gradient(linear, left top, left bottom, from(#3CCC77), to(#00190B));
    background-image: -moz-linear-gradient(top, #3CCC77, #00190B);
    background-image: -ms-linear-gradient(top, #3CCC77, #00190B);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #3CCC77), color-stop(100%, #00190B));
    background-image: -webkit-linear-gradient(top, #3CCC77, #00190B);
    background-image: -o-linear-gradient(top, #3CCC77, #00190B);
    background-image: linear-gradient(#3CCC77, #00190B);
    border-color: #00190B #00190B hsl(131, 100%, -10%);
    color: #fff !important;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.99);
    -webkit-font-smoothing: antialiased;
}

span.button span.text {
    position: absolute;
    top: 16px;
    left: 65px;
    font: 15px Arial;
}

span.button span.shine {
    content: '';
    position: absolute;
    height: 1000px;
    width: 5px;
    background: white;
    top: -500px;
    left: -80px;
    display: block;
    opacity: 0.8;

    -webkit-box-shadow: 0px 0px 20px 10px white;
    -moz-box-shadow: 0px 0px 20px 10px white;
    box-shadow: 0px 0px 20px 10px white;

    -webkit-transform: rotate(-45deg);
    -moz-transform: rotate(-45deg);
    -ms-transform: rotate(-45deg);
    -o-transform: rotate(-45deg);
    transform: rotate(-45deg);

    -webkit-transition: all 1s ease;
    -moz-transition: all 1s ease;
    -ms-transition: all 1s ease;
    -o-transition: all 1s ease;
    transition: all 1s ease;
}

span.button:hover {
    -webkit-box-shadow: inset 0px 1px 10px 0px rgba(255,255,255,.4), 0px 3px 3px 0px rgba(0,0,0,0.4);
    -moz-box-shadow: inset 0px 1px 10px 0px rgba(255,255,255,.4), 0px 3px 3px 0px rgba(0,0,0,0.4);
    box-shadow: inset 0px 1px 10px 0px rgba(255,255,255,.4), 0px 3px 3px 0px rgba(0,0,0,0.4);
}

span.button:active {
    -webkit-box-shadow: inset 0px 1px 15px 0px rgba(0,0,0,.4), inset 0px 1px 1px 1px rgba(0,0,0,.2), 0px 1px 1px 0 rgba(255,255,255,.5);
    -moz-box-shadow: inset 0px 1px 15px 0px rgba(0,0,0,.4), inset 0px 1px 1px 1px rgba(0,0,0,.2), 0px 1px 1px 0 rgba(255,255,255,.5);
    box-shadow: inset 0px 1px 15px 0px rgba(0,0,0,.4), inset 0px 1px 1px 1px rgba(0,0,0,.2), 0px 1px 1px 0 rgba(255,255,255,.5);
}

span.button:hover span.shine {
    left: 2000px;
    top: -300px;
}

    <input class="btn btn-block" type="submit" name="submit" value="YES - YES - YES" />

Bootply
Colors and everything is right already. And the effect is working fine. But the Input element should be one with the button as a whole. I have tried to reposition the html input element anywhere else within the button span, but that only makes everything worse.
Any help is highly appreciated. Many thanks.

A: From what i see, you just need to add that css to the input itself, otherwise remove the background style from the input and make it's width and height 100% to fit the parent that is styled.


text:
Q: xtype tool doesn't have methode getType() extjs6 I've read Extjs 6 documentation  that Ext.panel.Tool have getType() method but when I try, it turns error

Uncaught TypeError: Object [object Object] has no method 'getType'

Why this error? Thank you

A: I looked in the sources, and there is no getType method for panel tools. I guess that is a documentation issue. You can always access the type directly.


text:
Q: How can I detect pogrammatically whether a Google Map was actually loaded on Android with API v2 (e.g. when network is not available)? I have the Google Map API v2 working fine on Android using a SupportMapFragment in a FragmentActivity.
However, when there is no network connection (and no cached information), obviously, no map can be shown. LogCat gives me an error message confirming this ("Google Maps Android API: Failed to load map. Could not connect to Google servers"), but this is not thrown.
How can I detect this case programmatically, because I would like to forward to a different Activity in this case? The docs claim that if no map could be loaded getMap() called on the SupportMapFragment would return null, but this does not seem to be the case.
I've been searching around for almost two days for a solution, but was not able to find anything. Am I totally overlooking something or is it really not possible to find out whether something was actualy loaded? Any help is greatly appreciated.
Edit:
Here is my current code, the error message appears on the logs after the setContentView is executed (checked with debugger), but it still says that ConnectionResult == SUCESS.
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    SupportMapFragment smf = ((SupportMapFragment)
    getSupportFragmentManager().findFragmentById(R.id.map));
    map = smf.getMap();

    if (map != null && GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) ==
                                        ConnectionResult.SUCCESS) {
        // doSomething with the map
    } else {
        Toast.makeText(this, "Google Maps not working", Toast.LENGTH_SHORT).show();
        System.out.println(GooglePlayServicesUtil.isGooglePlayServicesAvailable(this));
        // forward to another activity
    }
}

A: GooglePlayServicesUtil.isGooglePlayServicesAvailable is related to GooglePlayServices.APK available on your device. API will not give you any indication of when tiles are loaded.
You have the options to:

*

*check if any tiles are cached by trying (hackish, simplified): new File(getExternalCacheDir(), "cache_vts_your.package.name.0").exists()

*check internet availability with your own code

*parse logcat to find the error
Edit:
Note point 3 is deprecated because applications are not allowed to read logs anymore due to security reasons


text:
Q: MySQL REGEXP to match the whole word only How can I match the whole word in mysql?
For instance, if I type in 'lau', I don't want to match 'laura' or 'laurance'.
Below is my working query that matches 'lau' with 'laura'
SELECT *
FROM
(
    SELECT

        p.page_id,
        p.page_url AS url,
        p.page_title AS title,
        SUBSTRING_INDEX(p.page_content_1, ' ', 500) AS content,
        EXTRACT(DAY FROM p.page_backdate) AS date,
        EXTRACT(MONTH FROM p.page_backdate) AS month,
        EXTRACT(YEAR FROM p.page_backdate) AS year

    FROM root_pages AS p

    WHERE p.page_hide != '1'
    AND p.page_url != 'cms'
    AND p.page_url != 'search'

    ORDER BY p.page_created DESC
) x
WHERE x.content REGEXP  '>[^<]*lau'

Any idea to fix my REGEXP?
The reason I use REGEXP '>[^<]*searchtext' is that my contents have html tags, such as,

About us

The team

Introduction to gt

Simon x

Cathrin xe

Patrick x

Laurence x

Tessa x
>

I don't want to search the word may fall inside the tags such as .

A: Let's break down your current regexp:
>[^<]*lau

>      match the character '>'
[^<]*  match 0 or more non-'<' characters
lau    match 'lau'

So this would match the following:
>bbblau
>bbb<lau
>lau
><lau

I assume what you want is to match the following:
>lau

But not:
>laubbb
><lau
>bbb<lau

In that case, the following regexp would work:
>lau( |<|$)

Edit: using the method shown by andrewsi might be cleaner:
>lau[[:>:]]

A: Does this work?
REGEXP '[^<]*lau[[:>:]]'
According to the documentation, [[:>:]] will match a word boundary at the end of a word

A: andrewsi code didn't work for me, but this REGEXP solved my problem.
m_city REGEXP '[[:<:]]YOUR_CITY[[:>:]]'


text:
Q: Portfolio Returns in Panel Data with R I have a Panel Data set of different portfolios with prices and I want to track the performance of each over a period of 10 years. I already calculated the returns with:
returnfun <- function(x) c(NA, diff(x) / head(x, -1))
Portfolio10pd=returns=transform(Portfolio10pd, Returns = ave(prccm, GVKEY, FUN = returnfun))

When the GVKEY changes it produces 1 "Na" because there is no old price as reference. So I cleaned the NA return columns with
P10=subset(NaRV.omit(Portfolio10pd))

 head(P1, 10)
   GVKEY datadate  prccm       Returns
2      1 20100228 292.00 -0.0009921653
3      1 20100331 299.13  0.0244178082
4      1 20100430 317.82  0.0624811955
5      1 20100531 324.37  0.0206091498
6      1 20100630 302.92 -0.0661281869
7      1 20100731 334.17  0.1031625512
8      1 20100831 304.55 -0.0886375198
9      1 20100930 315.78  0.0368740765
10     1 20101031 375.84  0.1901957059

> tail(P1,10)
      GVKEY datadate prccm      Returns
20322   144 20200331 32.74 -0.238781679
20323   144 20200430 32.62 -0.003665241
20324   144 20200531 30.38 -0.068669528
20325   144 20200630 32.27  0.062211982
20326   144 20200731 30.71 -0.048342113
20327   144 20200831 28.02 -0.087593618
20328   144 20200930 26.58 -0.051391863
20329   144 20201031 24.75 -0.068848758
20330   144 20201130 31.20  0.260606061
20331   144 20201231 31.68  0.015384615

I have 144 Firms with monthly returns from February 2010 until December 2020. I would like to calculate the monthly returns of the equally weighted Portfolio to track the performance over time. I cannot use Return.portfolio() function of the performance analytics package because the returns are not in the right format. Has somebody a hint for me or a solution for that problem? I am new to R, so thank u very much!

A: Does it really have to be that format? It is typically more efficient to merge the series on the timestamps and then compute the returns of a strategy. An example, for which I first create a small data set.
library("PMwR")
library("zoo")

data <- read.table(header = TRUE, sep = ",", text =
"GVKEY, datadate,  prccm
     1, 20100228, 292.00
     1, 20100331, 299.13
     1, 20100430, 317.82
     1, 20100531, 324.37
     1, 20100630, 302.92
     2, 20100228,  28.02
     2, 20100331,  26.58
     2, 20100430,  24.75
     2, 20100531,  31.20
     2, 20100630,  31.68")

z <- by(data, data$GVKEY, function(x) zoo(x$prccm, x$datadate))
prices <- do.call(merge, z)
##               1     2
## 20100228 292.00 28.02
## 20100331 299.13 26.58
## 20100430 317.82 24.75
## 20100531 324.37 31.20
## 20100630 302.92 31.68

returns(prices,
        weights = c(0.5, 0.5),
        rebalance.when = 20100228)
##      20100331      20100430      20100531      20100630
## -0.0134870274 -0.0006607329  0.1281236339 -0.0253235197

A: Good Morning,
thanks for your help. I started formating everything new:
dput(x)
structure(list(GVKEY = c("002222", "002237", "002402", "002990",
"003691", "004130", "005336", "005902", "006130", "006185", "007183",
"007192", "007389", "007694", "009330", "010476", "011751", "012252",
"012711", "012713", "012717", "012731", "012744", "012942", "013472",

So I have a vector of gvkeys and a matrix of gvkeys and monthly dates of 10 years and monthly prices.
> head(Preise)
# A tibble: 6 x 3
  GVKEY  datadate prccm
  <chr>     <dbl> <dbl>
1 001003 20100131  0.02
2 001003 20100228  0.02
3 001003 20100331  0.02
4 001003 20100430  0.02
5 001003 20100531  0.02
6 001003 20100630  0.02

It looks like this. When I merged this it looks like the matrix I posted in my solutions. But I want to merge it and bring this to the format you suggest. What I need is a function which looks for the gvkeys of my list and compares them to the gvkeys in the matrix and merges them. So I have the wanted gvkeys with the monthly prices and I would like your the gvkeys as row names and the different dates as column names. So I can work with perfomance analytics to measure the performance.
Thank you very much!


text:
Q: Use https with only http supporting node-xmpp-bosh Intro
I use converse.js for as XMPP webclient. Therefore I need a bosh server that handles the bidirectional communication.
As such a server acts node-xmpp-bosh. Since my site is SSL/TLS encrypted and it's only available through https, it's only allowed to connect to the bosh server by encrypted communication.
Unfortunately node-xmpp-bosh doesn't support SSL/TLS.
Question
Can I circumvent this, by forwarding the traffic somehow? Or am I lost and need to search another bosh server?

A: Some hours later...again happy :)
The solution to my problem is to proxy the traffic to the bosh server. To do this on Apache I use now (or at least at the moment) this VirtualHost config:
<VirtualHost *:443>
    ServerName bosh.domain.tld
    ServerAlias www.bosh.domain.tld

    ServerAdmin admin@domain.tld

    <Proxy *>
        Order allow,deny
        Allow from all
    </Proxy>

    ProxyPass / http://127.0.0.1:5280/http-bind/
    ProxyPassReverse / http://127.0.0.1:5280/http-bind/

    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/domain.tld/cert.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/domain.tld/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/domain.tld/chain.pem
    SSLVerifyClient None
    # HSTS (mod_headers is required) (15768000 seconds = 6 months)
    Header always set Strict-Transport-Security "max-age=15768000"
</VirtualHost>


text:
Q: Problema ao criar projeto Maven no Eclipse Mars Estava utilizando o o Maven no Eclipse Luna normalmente, resolvi testar a nova versão do Eclipse e quando crio um projeto Maven algumas exceções são lançadas:

Description   Resource    Path    Location    Type Failure to transfer
  org.apache.maven:maven-core:jar:2.0.6 from
  https://repo.maven.apache.org/maven2 was cached in the local
  repository, resolution will not be reattempted until the update
  interval of central has elapsed or updates are forced. Original error:
  Could not transfer artifact org.apache.maven:maven-core:jar:2.0.6
  from/to central (https://repo.maven.apache.org/maven2): connect timed
  out   pom.xml /Testando   line 1  Maven Configuration Problem

Como posso resolver esse problema?

A: Eu tentaria um mvn clean install -U.
Caso não funcione, tente apagar as dependências na pasta .m2 do seu usuário e execute mvn clean install novamente.

A: Resolvi o problema alterando as configurações de proxy do arquivo settings.xml que fica na pasta do Maven.


text:
Q: getStreamVolume giving null pointer exception I have used the same command in 5 different applications without problem (as part of my SoundManager):
float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

but now it's giving me a null point exception based on my log commands. Why??????
The only things that have changed are the sounds. I have used log commands to see what sound it is trying to play and checked if the sounds are in the sound manager and they are but does that even matter as all this command does is try to get the phones set play volume?

A: Thanks Wesley, That was it. I added:
SoundManager.initSounds(getApplicationContext());
SoundManager.loadSounds();

and it's working fine now.


text:
Q: What is purpose of App in Userpool in AWS Cognito I am new to AWS Cognito. Based on description,  Userpool is used for authentication.  If I am a user in the userpool, I can use this user name and password to authenticate my identity.  Why do I need to add App to userpool?
Thanks for help in advance,

A: AWS Cognito allows you to create a number of apps to integrate with your user pool. On each app, you can custom the Authentication flow, Access/Refresh token expiration, attribute read and write permissions, hostUI...
Use case: you use the same user pool for both apps but there are some custom like:

*

*App A: just allow authentication via the ALLOW_USER_PASSWORD_AUTH and access token expiration is 5 minutes.

*App B: just allow authentication via the ALLOW_USER_SRP_AUTH and access token expiration is 30 minutes.

Hope that's clear.


text:
Q: Shapely parallel_offset returning an empty list I have a LineString and when I try to create a right parallel line with parallel_offset I get an empty list. What am I doing wrong?  The code is as follow:
Line_ = LineString([Point(-131241, 5700864), Point(-130215, 5700016.609604769), Point(-129200, 5699155), Point(-128256, 5698218), Point(-127481, 5697139), Point(-126943, 5695927), Point(-126662, 5694629), Point(-126617, 5693300), Point(-126815, 5691987), Point(-127147, 5690699)])
print(Line_.parallel_offset(15000, 'right'))
LINESTRING EMPTY

While if I use parallel_offset to calculate the left parallel line of the same LineString I get the expected result:
Line_ = LineString([Point(-131241, 5700864), Point(-130215, 5700016.609604769), Point(-129200, 5699155), Point(-128256, 5698218), Point(-127481, 5697139), Point(-126943, 5695927), Point(-126662, 5694629), Point(-126617, 5693300), Point(-126815, 5691987), Point(-127147, 5690699)])
print(Line_.parallel_offset(15000, 'left'))
LINESTRING (-121688.949663129 5712429.393826493, -120662.949663129 5711582.003431262, -120507.734800415 5711452.037115139, -119492.734800415 5710590.42751037, -118632.9431239474 5709800.999670218, -117688.9431239474 5708863.999670218, -116841.5246323321 5707949.893550635, -116072.9273087647 5706968.585111869, -115297.9273087647 5705889.585111869, -114466.0962164286 5704596.364112364, -113771.0294072872 5703224.779025478, -113233.0294072872 5702012.779025478, -112683.2909290381 5700581.105414742, -112282.6077144392 5699100.782921605, -112001.6077144392 5697802.782921605, -111776.287252372 5696477.122289002, -111670.5913831028 5695136.609772582, -111625.5913831028 5693807.609772582, -111642.1468335366 5692431.799192087, -111784.6992899678 5691063.293571526, -111982.6992899678 5689750.293571526, -112289.7845017582 5688242.922713186, -112621.7845017582 5686954.922713186)

A: You're not doing anything wrong. Left and right are determined by following the direction of the line. This method may sometimes return EMPTY geometry for curved lines if offset value is huge. If you use distance values less than ~9650 for this line, you will understand clearly what I mean.

Review samples in Documentation.


text:
Q: Retrieve if my own process have SeDebugPrivilege enabled How can I determine if my own process have SeDebugPrivilege enabled?

A: Here is the solution if somebody more need it.
type
  TPrivilegesArray = array [0..1024] of TLuidAndAttributes;
  PPrivilegesArray = ^TPrivilegesArray;
var
  luid          : TLargeInteger;
  LuidSDP       : TLargeInteger;
  hToken        : THandle;

  Size          : Cardinal;
  Privileges    : PTokenPrivileges;
  I             : Integer;

  Name          : string;
  Attr          : Longword;

  function AttrToString: string;
  begin
    Result := 'Disabled';
    if (Attr and SE_PRIVILEGE_ENABLED) <> 0 then Result := 'Enabled';
    if (Attr and SE_PRIVILEGE_ENABLED_BY_DEFAULT) <> 0 then Result := 'Enabled By Default';

    Result := Result;
  end;
begin
  OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, hToken);

  GetTokenInformation(hToken, TokenPrivileges, nil, 0, Size);
  Privileges := AllocMem(Size);
  GetTokenInformation(hToken, TokenPrivileges, Privileges, Size, Size);
  LookupPrivilegeValue(nil, 'SeDebugPrivilege', LuidSDP);

  for I := 0 to Privileges.PrivilegeCount - 1 do
  begin
    if LuidSDP <> PPrivilegesArray(@Privileges^.Privileges)^[I].Luid then Continue;

    Luid := PPrivilegesArray(@Privileges^.Privileges)^[I].Luid;
    Attr := PPrivilegesArray(@Privileges^.Privileges)^[I].Attributes;
    Size := 0;

    LookupPrivilegeName(nil, Luid, nil, Size);
    SetLength(Name, Size);
    LookupPrivilegeName(nil, Luid, PChar(Name), Size);

    Form1.Memo2.Lines.Add(Format('[%d][%s][%s]', [Luid, PChar(Name), AttrToString]));
  end;

  FreeMem(Privileges);
  CloseHandle(hToken);

This code list all privileges and if are disabled, enabled by default or enabled.
After some search and modifications this code are working perfectly.
if need list all privileges just comment the line
if LuidSDP <> PPrivilegesArray(@Privileges^.Privileges)^[I].Luid then Continue;


text:
Q: Ordering the terms of a differential equation, individual output form I am trying to change the output format of a second order differential equation. Mathematica puts the x[t] terms and its derivatives in an ascending order like
m*g*h == x[t] + x'[t] + x''[t]
how can I reverse it and get the following output?
x''[t] + x'[t] + x[t] == m*g*h


text:
Q: How to open a link in Safari rather than the in app browser I'm struggling with solution to open instagram stories swipe up links opens into safari browser. I know that is possible because some stories contain links into safari instead of Instagram app Webview.
There is example: https://www.instagram.com/stories/highlights/17893042882461992/
Try to open link with Instagram app.
Solution to open links in browser for Android devices is:
https://medium.com/@sasan.salem/opening-of-your-website-in-the-viewers-external-browser-automatically-instead-of-instagram-s-8aca5ee7e22f


text:
Q: Place minified files into jar I will use the maven dependency com.samaxes.maven#minify-maven-plugin to minify my frontend project. This frontend- project is packaged into a jar (java archive) - so I have no war file because I use Spring boot.
With the configuration at the bottom *.min.js and *.min.css files are generated but they are not pacakged into jar file. I have read some threads and I have tried something but with no success: in the JAR file there are still the unminified css and js files.
Does anyone have any hint what I can do. I have a lot of css and js files in my project in different folder structures and the minified files should be placed in the same place like the unminified files are.
<build>
<plugins>
  <plugin>
    <groupId>com.samaxes.maven</groupId>
    <artifactId>minify-maven-plugin</artifactId>
    <version>1.7.4</version>
    <executions>
      <execution>
        <id>default-minify</id>
        <phase>package</phase>
        <configuration>
          <charset>UTF-8</charset>
          <skipMerge>true</skipMerge>
          <nosuffix>true</nosuffix>
          <closureCompilationLevel>WHITESPACE_ONLY</closureCompilationLevel>
          <webappSourceDir>src/main/resources</webappSourceDir>
          <cssSourceDir>./</cssSourceDir>
          <cssTargetDir>./minified</cssTargetDir>
          <cssSourceIncludes>
            <cssSourceInclude>**/*.css</cssSourceInclude>
          </cssSourceIncludes>
          <cssSourceExcludes>
            <cssSourceExclude>**/*.min.css</cssSourceExclude>
          </cssSourceExcludes>
          <jsSourceIncludes>
            <jsSourceInclude>**/*.js</jsSourceInclude>
          </jsSourceIncludes>
          <jsSourceExcludes>
            <jsSourceExclude>**/*.min.js</jsSourceExclude>
          </jsSourceExcludes>
          <jsEngine>CLOSURE</jsEngine>
        </configuration>
        <goals>
          <goal>minify</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</plugins>

[EDIT]
I have edit the Maven plugin in this way.
I really have to use src/main/recoures - it a specification at our project.
My problem now is that the files in the different folders unter the under the main folder path public/app are minified BUT the folders with the minified files are at same level than my public folder is.
So I would need something like this:
<webappTargetDir>**public/app/**${project.build.outputDirectory}</webappTargetDir>

Is there a possibility to do it like this?
<build>
<plugins>
  <plugin>
    <groupId>com.samaxes.maven</groupId>
    <artifactId>minify-maven-plugin</artifactId>
    <version>1.7.4</version>
    <executions>
      <execution>
        <id>default-minify</id>
        <phase>prepare-package</phase><!-- When omitted defaults to 'process-resources' -->
        <configuration>
          <charset>UTF-8</charset>
          <skipMerge>true</skipMerge>
          <closureCompilationLevel>WHITESPACE_ONLY</closureCompilationLevel>
          <webappSourceDir>src/main/resources/public/app</webappSourceDir>
          <webappTargetDir>${project.build.outputDirectory}</webappTargetDir>
          <cssSourceDir>./</cssSourceDir>
          <cssSourceIncludes>
            <cssSourceInclude>**/*.css</cssSourceInclude>
          </cssSourceIncludes>
          <jsSourceDir>./</jsSourceDir>
          <jsSourceIncludes>
            <jsSourceInclude>**/*.js</jsSourceInclude>
          </jsSourceIncludes>
          <jsEngine>CLOSURE</jsEngine>
        </configuration>
        <goals>
          <goal>minify</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

With the minify-maven-plugin configuration above I get the following folder structure at the left side but I would need the folder structure at the rigth side. Is there any possibility to do that?

A: The files are copied relatively from webappSourceDir to webappTargetDir. So if you want the structure to match, you should use similar patterns for those. Meaning, it should be
<webappSourceDir>src/main/resources</webappSourceDir>
<webappTargetDir>${project.build.outputDirectory}</webappTargetDir>

or
<webappSourceDir>src/main/resources/public/app</webappSourceDir>
<webappTargetDir>${project.build.outputDirectory}/public/app</webappTargetDir>

I've commited the working example here


text:
Q: Meteor.js reactive html5 geolocation position.coords I'm a meteor.js nuub, but I did spend quite a bit of time trying to figure this one out.
I'm trying to reactively update my UI based on the HTML5 geolocation API callback passed into getCurrentPosition.  However, the UI is not updating with my current code.
Can you offer suggestions and/or a solution?  Here are the details:
Basics: meteor server is running, serving other data to/from mongo via collections successfully
I have a main page (main.html):

  <title>Geolocation</title>

      Geolocation

    {{> location}}

that references a template (location.js):
<template name="location">

    Lat: {{lat}}

    Lon: {{lon}}

</template>

that has this associated helper (location.js):
_lat = {
  current: 0,
  dep: new Deps.Dependency,
  get: function(){
    this.dep.depend();

    if(this.current === 0){
      getLocation();
    }

    return this.current;
  },
  set: function(value){
    this.current = value;
    this.dep.changed();
    Deps.flush();
    return this.current;
  }
};

_lon = {
  current: 0,
  dep: new Deps.Dependency,
  get: function(){
    this.dep.depend();

    if(this.current === 0){
      getLocation();
    }

    return this.current;
  },
  set: function(value){
    this.current = value;
    this.dep.changed();
    Deps.flush();
    return this.current;
  }
};

function getLocation(){
  if (navigator.geolocation)
  {
    navigator.geolocation.getCurrentPosition(showPosition, showError);
  }
  else{
    console.log("Geolocation is not supported by this browser.");
  }
}

function showPosition(position)
{
  _lat.set(position.coords.latitude);
  _lon.set(position.coords.longitude);
}

function showError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      console.log("User denied the request for Geolocation.");
      break;
    case error.POSITION_UNAVAILABLE:
      console.log("Location information is unavailable.");
      break;
    case error.TIMEOUT:
      console.log("The request to get user location timed out.");
      break;
    case error.UNKNOWN_ERROR:
      console.log("An unknown error occurred.");
      break;
  }
}

Template.location.helpers({
  lat: _lat.get(),
  lon: _lon.get()
});

A: As far as I know navigator.geolocation is not a reactive data source. So this won't work without some explicit polling. Another thing that you've got wrong is that your helpers are not functions, so they couldn't be called repeatedly.
This might work (not tested):
Meteor.setInterval(function() {
    navigator.geolocation.getCurrentPosition(function(position) {
        Session.set('lat', position.coords.latitude);
        Session.set('lon', position.coords.longitude);
    });
}, 5000);

Template.location.helpers({
  lat: function() { return Session.get('lat'); },
  lon: function() { return Session.get('lon'); }
});

A: To get geolocation to work in Meteor apps compiled as native iOS apps, I needed to add the geolocation package available at https://atmospherejs.com/mdg/geolocation


text:
Q: Issues calling Oracle stored procedure from C# This is the first time that I have ever had to call an Oracle stored procedure from C# and I don't know why my code is not working. All that I am trying to do is return a datatable. My stored procedure compiles just fine - here is some pseudocode describing it:
CREATE OR REPLACE PROCEDURE SPROC_ONLINE
( Year IN NUMBER DEFAULT NULL
, Name IN VARCHAR2 DEFAULT NULL
, ID IN VARCHAR2 DEFAULT NULL
, refCursor OUT SYS_REFCURSOR
)
AS
BEGIN
OPEN refCursor FOR
SELECT *
FROM TABLE
WHERE Field_Year = Year
  AND Field_Name = Name
  AND Field_ID = ID;
END SPROC_ONLINE;

Here is some pseudocode describing my C#:
public static DataTable search(int? Year, string Name, string ID)
    {
        try
        {
            OracleConnection conn = getConnectionString();
            OracleCommand cmd = new OracleCommand();
            cmd.Connection = conn;
            cmd.CommandText = "SPROC_ONLINE";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("Year", OracleDbType.Int32).Value = Year;
            cmd.Parameters.Add("Name", OracleDbType.Varchar2).Value = Name;
            cmd.Parameters.Add("ID", OracleDbType.Varchar2).Value = ID;
            cmd.Parameters.Add("Output", OracleDbType.RefCursor).Direction = ParameterDirection.Output;

            DataTable dt = new DataTable();
            OracleDataAdapter da = new OracleDataAdapter(cmd);
            getConnectionString().Open();
            cmd.ExecuteNonQuery();
            da.Fill(dt);

            return dt;
        }
        catch (Exception e) { throw new Exception("Error: " + e.Message); }
        finally { getConnectionString().Close(); }
    }

No errors are being thrown; it's just that the datatable that is returned is null when it should not be (the parameters that I am testing with should be returning something).
What am I doing wrong here?

A: I think you may need to use OracleDataReader.
using(OracleCommand cmd = new OracleCommand("SPROC_ONLINE", TheConnection))
{
    using(OracleDataReader reader = new OracleDataReader())
    {
        while(reader.Read())
        {
            // Extract the values
            var a = reader["Year"];
            var b = reader["Name"];
            var c = reader["ID"];
            ... etc ...
        }
    }
}

A: My issue ended up being two-fold; here is the code-behind that I ended up with:
public static DataTable search(int? Year, string Name, string ID)
{
    try
    {
        using (var cmd = new OracleCommand("SPROC_ONLINE", getConnectionString()))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            var da = new OracleDataAdapter(cmd);
            cmd.Parameters.Add("Year", OracleDbType.Int32).Value = Year;
            cmd.Parameters.Add("Name", OracleDbType.Varchar2).Value = Name;
            cmd.Parameters.Add("ID", OracleDbType.Varchar2).Value = ID;
            cmd.Parameters.Add("Output", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt;
        }
    }
    catch (Exception e) {throw new Exception("Error: " + e); }
    finally {}
}

My other issue was that I did not realize that string comparisons in Oracle were case-sensitive. Apparently between compiling my stored procedure in SQL Developer and trying to test it in Visual Studio, I was not consistently entering the "Name" parameter; this explains why a null datatable would be returned. I adjusted the WHERE clause of my stored procedure as follows:
WHERE Field_Year = Year
  AND UPPER(Field_Name) = UPPER(Name)
  AND Field_ID = ID;

Everything works fine now.


text:
Q: PowerPivot DAX formula if then for dates I have a column named ExpireDate in my PowerPivot table (not PowerBI) and want to make another column based on the value of Today's Date - ExpireDate with a DAX formula like below:
=if(Format([ExpireDate] -today(), "General Number") <= 90, "Less than 3 months",
 if(90 < Format( [ExpireDate] -today() ,"General Number") <= 180, " 3 to 6 months",
 if([Format (ExpireDate]-today() ,"General Number") > 180, "More than 6 months","Other"))

But this formula keeps showing error messages, saying it needs a proper formula.  Anybody knows how to deal with this problem? Thanks a lot.

A: Assuming you are using Excel 2016, and your table name is "Table":
=
VAR Expiration = Table[ExpireDate] - TODAY ()
RETURN
    SWITCH (
        TRUE (),
        Expiration <= 90, "Less than 3 months",
        Expiration <= 180, " 3 to 6 months",
        Expiration > 180, "More than 6 months",
        "Other"
    )


text:
Q: How to create a data history in a dimension without using slowly changing dimension? I'm working on my fact table and I want to create history table for each dimension without using slowly changing dimension because my data flows are bulky and it will take too much time to finish the process of feeding the fact table ? Generally, slowly changing dimension works with dataset having less than 1000 records.

A: I've used SCDs with 100s of thousands of elements and even millions. You'll need to optimise your table, create indexes, etc, but there's no reason not to use them.


text:
Q: Does Spring's "forward" prefix change anything about the client-server relationship? Unlike the "redirect" prefix, which seems pretty clear to me, the "forward" prefix leaves a few questions open for me.
Does the forward go through the web layer? Does the server "request from itself"?
My specific problem:
My Spring based backend has the default spring health actuator under /actuator/health.
Our Grafana and the monitoring of our hoster expect the healthcheck under /health.
So we have this little endpoint to forward the healthcheck:
@GetMapping("/health") public String forwardHealthEndpoint() { return "forward:/actuator/health"; }
Every now and then our Grafana shows red and the backend logs contain messages about "broken pipe" and "connection reset by peer".
Is it even possible that the "broken pipe" happens during the forwarding?
This problem is not reproducable and happens very sporadically so I was not able to verify that the backend really is unreachable when this error occurs or if Grafana just reports that because of a forwarding hiccup.
I checked the Grafana server logs for any potential error messages due to receiving an unparsable, partial response and such, but did not see any error messages there.
I do not have access to the logs of our hoster's monitoring tool.
Just trying to eliminate some options here.


text:
Q: Running MS Access saved query from c# Found very strange behavior of MS Access database when running queries from c#. It appears that if query in MS Access contains "like" statement it will not return its result to Oledb. If anyone knows how to solve this I'll be very grateful. c# code:
DataTable GetAccessData(string FileName, string Password)
    {
        Query = "select * from [qry_1]";
        DataTable DT = access2dt
            (
            FileName,Password,Query);

        MessageBox.Show(Query);
        if (DT == null || DT.Rows.Count <= 1) throw new Exception("Data not found");
        else return DT;
    }

public static DataTable access2dt(string filename, string password, string query)
{
    string conString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Jet OLEDB:Database Password=" + password;
    OleDbConnection mycon;
    mycon = new OleDbConnection(conString);

    if (mycon.State == ConnectionState.Closed)
    {
        mycon.Open();
    }
    try
    {
        OleDbCommand accessCommand = new OleDbCommand();
        System.Data.DataTable dt = new System.Data.DataTable();
        accessCommand = new OleDbCommand(query, mycon);

        using (OleDbDataReader myReader = accessCommand.ExecuteReader())
        {
            DataTable myTable = new DataTable();
            myTable.Load(myReader);
            return myTable;
        }
    }
    finally
    {
        mycon.Close();
    }

}

And query [qry_1] saved in MS Access database looks like this:
SELECT tbl_MAPPING_GICM_AoA.[Type of expense]
FROM tbl_USGAAP_ALL_TRANS, tbl_MAPPING_GICM_AoA
WHERE tbl_USGAAP_ALL_TRANS.[Account]=[tbl_MAPPING_GICM_AoA].[Natural Account]
AND tbl_USGAAP_ALL_TRANS.[Created By] NOT IN (SELECT [Created by / User ID] FROM tbl_GICM_AoA_EXCL_FACTOR1)
AND tbl_USGAAP_ALL_TRANS.[Je Source] NOT IN (SELECT [JE SOURCE] FROM tbl_GICM_AoA_EXCL_FACTOR2)
AND tbl_USGAAP_ALL_TRANS.[Je Category] NOT IN (SELECT [JE CATEGORY] FROM tbl_GICM_AoA_EXCL_FACTOR3)
AND (tbl_USGAAP_ALL_TRANS.[Account] LIKE '4*' OR tbl_USGAAP_ALL_TRANS.[Account] LIKE '5*'  OR tbl_USGAAP_ALL_TRANS.[Account] LIKE '6*' )

So when i run it in Access it works just fine but when i call this query from c# i get "Data not found" exception. If I remove the last string (with LIKE) in query everything starts working

A: Try replacing the wildcard character. Access uses '*', but using OLEDB you will need to use '%' as the wildcard.


text:
Q: NavDropdown not opening after child item selected on mobile/tablet devices I have a dropdown menu built using react-bootstrap. Current it doesn't open the second time after an option has been selected from the dropdown. The user needs to click off the menu somewhere for it to work again. It seems the menu is retaining a state from the initial click that mean it doesn't work second time round.
This only applies to mobile devices, it works fine on non-mobile devices.
See the code for the menu below:
            <NavDropdown
          onToggle={this.onToggle}
          onMouseEnter = { () => this.setState({ isOpen: true }) }
          onMouseLeave = { () => this.setState({ isOpen: false })  }
          open={ this.state.isOpen }
          noCaret
          eventKey={3}
          title="Account"
          id="nav-mega-dropdown"
        >
            <LinkContainer to="/app/account" onClick={() => this.setState({ isOpen: false })}><NavItem eventKey={3.1}>Public Profile</NavItem></LinkContainer>
            { this.props.isSupplier ? <LinkContainer to="/app/account/business" onClick={() => this.setState({ isOpen: false })}><NavItem eventKey={3.2}>Business Details</NavItem></LinkContainer> : null }

            <LinkContainer to="/app/account/schedule" onClick={() => this.setState({ isOpen: false })}><NavItem eventKey={3.3}>Schedule</NavItem></LinkContainer>
            { this.props.isSupplier ? <LinkContainer to="/app/account/users" onClick={() => this.setState({ isOpen: false })}><NavItem eventKey={3.4}>Users</NavItem></LinkContainer> : null }

            <LinkContainer to="/app/account/sessions" onClick={() => this.setState({ isOpen: false })}><NavItem eventKey={3.5}>Sessions</NavItem></LinkContainer>
            { this.props.isSupplier ? <LinkContainer to="/app/account/subscription" onClick={() => this.setState({ isOpen: false })}><NavItem eventKey={3.6}>Subscription</NavItem></LinkContainer> : null }

            <LinkContainer to="/app/account/locations" onClick={() => this.setState({ isOpen: false })}><NavItem eventKey={3.7}>Locations</NavItem></LinkContainer>
            <LinkContainer to="/app/account/settings" onClick={() => this.setState({ isOpen: false })}><NavItem eventKey={3.8}>Password</NavItem></LinkContainer>

            <LinkContainer to="/app/account/holidays" onClick={() => this.setState({ isOpen: false })}><NavItem eventKey={3.9}>Holidays</NavItem></LinkContainer>
            { this.props.isSupplier ? <LinkContainer to="/app/account/visibility" onClick={() => this.setState({ isOpen: false })}><NavItem eventKey={3.10}>Visibility</NavItem></LinkContainer> : null }

        </NavDropdown>


text:
Q: Anylogic queue priority I have 4 agents in my queue. I have assigned a priority to each agent in the queue
e.g. children.priority = 1;
e.g. adult.priority = 2;
However when I run it I get an error. Is there a better way of doing this?

A: my guess is that instead of children.priority or adult.priority, you should write agent.priority
Or if you have in your queue agents of multiple types you could do:
if(agent instanceof Children)
    agent.priority=1;
else if(agent instanceof Adult)
    agent.priority=2;

Try that and maybe it works... I'm just guessing considering the extremely low quality of the question.


text:
Q: Typescript Generic Type and polymorphism I'm trying to enforce to pass an object with properties existing in a derived class in the following way:

class Observable<Event> {    // A simple implementation of the observer pattern
    notify( p: Event ) {
        this.callback(p)
    }

    callback: ( p: Event ) => void
}

// the event will be an object with keys on the Observable class
type ChangeEvent<T> = {
    [ P in keyof T ]?: T[P]
}

class Base {
    changeAndNotify<P extends keyof this>( key: P, value: this[P]) {
        this[key] = value
        this.observable.notify({ [key]: value })   // this works
    }

    observable: Observable<ChangeEvent<Base>>  // I tried this instead of Base but does not work
}

class Derived extends Base {
    doSomething() {
        this.changeAndNotify( 'name', 'Jane' )    // this works
        this.observable.notify({ name: 'Jane' })  // this produces an error
    }

    name: string
}

I want the Derived class properties to be accepted by the notify method but only properties from Base class ara valid.
Any sugestion?


text:
Q: Is there ever a reason to use asm volatile for PTX with no side-effects? The CUDA documentation on inline PTX, section 1.2.3 Incorrect optimization, says:

The compiler assumes that an asm() statement has no side effects except to change the output operands. To ensure that the asm is not deleted or moved during generation of PTX, you should use the volatile keyword, e.g.:
asm volatile ("mov.u32 %0, %%clock;" : "=r"(x));

If my inline PTX does indeed have no side-effects outside of registers, should I just never use volatile or are there cases in which I might still want to have it?

A: Assuming the rules are the same as "regular" (non-CUDA) GNU C inline assembly which uses the same constraint syntax:

If you want it to re-run the instruction(s) every time the source executes the statement, use volatile.  (This is probably what you want to re-read the %clock every time).
If you want to let the compiler hoist it out of a loop, or just CSE between two results of this statement before and after a block, then don't use volatile.
GNU C non-volatile extended-asm statements are treated as pure functions of their inputs.  (Having no outputs implicitly makes a statement volatile.)  This includes the case of a pure function with no inputs: by omitting volatile you're telling the compiler it produces the same output every time.
This could be appropriate for reading a CPU control register that you aren't planning to modify, or for loading a value from a memory location you haven't told the compiler about.  It's definitely not what you want for reading a clock.
I.e. reading something that isn't the same every time counts as a side-effect.


text:
Q: Flutter riverpod Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe error I am getting this error in my code -> Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
I am using riverpod in my flutter project and doing some api call and the data which i am getting from api adding it to respective object through StateNotifierProvider and i am doing it in init state of the code.
When i swtich my screen in bottom navigation bar it is throwing this error.
Thanks in advance !!!
@override
void initState() {
checkPermission();

WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
  ref.read(adminRepositoryProvider).getAllBooking().then((value) {
    ref.read(bookingListProvider.notifier).changeData(value);
  });
});

super.initState();
 }

Whenever i switch my screen from one screen to another through bottom navigation bar it throws this error
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
E/flutter (10366): At this point the state of the widget's element tree is no longer stable.
E/flutter (10366): To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.


text:
Q: SQLAlchemy: An "all-inclusive" in_ In the usual Customer -> Orders example schema, if we want to get all the Customers that made an Order with order_category_id set to 12 or 13, we would tell SQLAlchemy to...
for customer in db.query(Customer)\
        .join(Order, Customer.id = Order.cst_id)\
        .filter(Order.order_category_id.in_([12,13]):
    # do something with customer
    ...

But what if we wanted to get all the Customers, that have made Orders with both 12 and 13 order_category_ids? In SQL, I'd write it as:
select *
from Customer
where
   exists (select 1 from Order
    where Customer.id = Order.cst_id and Order.order_category_id = 12)
   and exists (select 1 from Order
    where Customer.id = Order.cst_id and Order.order_category_id = 13)

How do I trigger SQLAlchemy to generate this kind of query? i.e. one returning Customer entities that are associated with Order rows for both 12 and 13 category_ids?

A: Something like this:
subq1 = (
    Customer.query
    .join(Order, Customer.id = Order.cst_id)
    .filter(Order.order_category_id == 12)
).subquery()

final_query = (
    query(subq1)
    .join(Order, Customer.id = Order.cst_id)
    .filter(Order.order_category_id == 13)
)

I haven't tested this, but I think it should work.


text:
Q: SignalR/CoffeeScript Hub callback issue This works fine
class Window.AppViewModel
    message : ko.observable("")
    chatMessages : ko.observableArray()
    canSendMessage : ko.observable(false)
    Window.sHub.addMsg = (data) =>
        @::chatMessages.push(data)

whereas this
class Window.AppViewModel
    constructor : ->
        @message = ko.observable("")
        @chatMessages = ko.observableArray()
        @canSendMessage = ko.observable(false)
        Window.sHub.addMsg = (data) =>
            @chatMessages.push(data)

Results in my server side hub recieving server messages but it can't make any callbacks.
What am I missing here???  This is driving me up the wall.  Obviously the prototype based solution will work because it's making everything "static" but I'm crippled because I can't write nicely separated code at the moment.
Is there any way to see what the hub is trying to invoke??  The SignalR documentation talks about tracing/logging but never explains how.

A: All wired client events can be found by adding a small snippet to the "On" anonymous function in jquery.SignalR in the hubProxy prototype
So now it looks something like this
   on: function (eventName, callback) {
            /// <summary>Wires up a callback to be invoked when a invocation request is received from the server hub.</summary>
            /// <param name="eventName" type="String">The name of the hub event to register the callback for.</param>
            /// <param name="callback" type="Function">The callback to be invoked.</param>
            var self = this;

            // Normalize the event name to lowercase
            eventName = eventName.toLowerCase();
            console.log(eventName + " callback was registered on the client");
            $(self).bind(eventNamespace + eventName, function (e, data) {
                callback.apply(self, data);
            });
            self.subscribed = true;
            return self;
        }

And gives you nice output of what client methods can be called back from the server
Also, I learned that CreateHubProxies (reflects through the callbacks you add) is only called once for an entire hub.Start()--So all methods must be added to the hub proxy before you start.
This should definitely be on the github wiki.  It makes sense but it isn't obvious.
Edit : It would make sense to allow you to call CreateHubProxies multiple times.  People are accustom to writing Knockout.js code in a way where they delay allocating a viewmodel until a certain event happens--if your viewmodel has any SignalR callbacks, this isn't impossible.  Having to create all of your viewmodels upfront is a bit of a kludge.  You could even keep it pretty lean by keeping a list of proxy members already generated and excluding them.


text:
Q: Can't get my Tomcat to connect using port 443 (https) for the past two days I've been trying to do one thing, be able to access my webapp (localhost:8080/evop) as www.gestao.com.br and furthermore enable https on my web server so that https://www.gestao.com.br also works.

Summary
I need to have a localhost web application showing the https in front of it's URL (not the crossed red https).
PS: Using Tomcat as the web server and Windows and the host OS.

Explanation
We install Tomcat on each client so they can run our webapp locally at their companies, after sometime we started receiving some complaints that the connection is not secure, even though they are locally, so in order to please our client we decided to enable SSL on their Tomcat servers locally.
Using the keytool provided with JDK it was quite easy to enable https on the server, however the https was crossed by a read line because it was self-signed. At this point I knew a CA was needed to sign the certificate, but since this was all done locally and there were no real domains bought, using a CA like LetsEncrypt was not possible.
So enough of a background story, basically I have a Tomcat server on a Windows 10 machine and it needs to have a signed SSL certificate so the applications hosted on that server have https in front of their urls (not the crossed https)

What I did
In order to do that I found out I was gonna have to be my own CA. Here are my steps:
1. Being able to access my webapp using only a local domain www.gestao.com.br

*

*My webapp url was localhost:8080/evop; However, I changed C:\Windows\System32\drivers\etc\hosts by adding 127.0.0.1 www.gestao.com.br to the end of the file, so I could access it using www.gestao.com.br:8080/evop

*I solved the port in the URL problem by editing the server.xml on Tomcat conf folder and adding:

<Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000" />

*

*With that I was able to access it using www.gestao.com.br/evop

*Last step was to change the folder called evop on Tomcat's webapps folder to ROOT and I was able to load my application with wwww.gestao.com.br
2. Becoming my own CA

*

*Created a private key with:

openssl genrsa -des3 -out rootSSL.key 2048

*

*Created the root certificate file:

openssl req -x509 -new -nodes -key rootSSL.key -sha256 -days 1024 -out rootSSL.pem

*

*Added my new created root certificate to Microsoft Management Console (MMC) so Windows knows it can trust certificates signed by me.

3. Creating and signing a certificate for my own application

*

*Created a private key for the new local domain with:

openssl req -new -sha256 -nodes -out gestao.csr -newkey rsa:2048 -keyout gestao.key -subj "/C=BR/ST=MS/L=Campo Grande/O=Evop/OU=Dev/CN=www.gestao.com.br/emailAddress=dev@evop.com.br"

*

*Issue the certificate with:

openssl x509 -req -in gestao.csr -CA rootSSL.pem -CAkey rootSSL.key -CAcreateserial -out gestao.crt -days 500 -sha256 -extensions "authorityKeyIdentifier=keyid,issuer\n basicConstraints=CA:FALSE\n keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment\n  subjectAltName=DNS:www.gestao.com.br"

4. Configure Tomcat to use the certificate

*

*I tried this two ways, first I opened a powershell on Tomcat conf folder to use rootSSL.pem to create a keystore using JDK's keytool with:

keytool -import -alias root -keystore tomcat.jks -trustcacerts -file rootSSL.pem

*

*Then I also added the local domain certificate with:

keytool -import -alias tomcat -keystore tomcat.jks -file gestao.crt

*

*After that I configured a connector on server.xml like so:

<Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="443" />

<Connector port="443" protocol="HTTP/1.1" maxThreads="150" SSLEnabled="true" compression="on" scheme="https" secure="true" keystoreFile="conf/tomcat.jks" keyAlias="tomcat" keystorePass="password" clientAuth="false" SSLVerifyClient="none" sslProtocol="TLSv1.2" />

*

*However I was only able to access Tomcat using the 8080 port, if I tried to access it using port 443 I got a connection refused error.

*Secondly I tried not using the keytool and setting the local domain certificate and key directly into the conector, like so:

<Connector port="443" protocol="org.apache.coyote.http11.Http11AprProtocol"
 maxThreads="150" SSLEnabled="true" >
    <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
    <SSLHostConfig>
        <Certificate certificateKeyFile="conf/gestao.key" certificateFile="conf/gestao.crt" type="RSA" />
    </SSLHostConfig>
</Connector>

*

*However, that also did not let me connect using the 443 port.

References

*

*Wil Brown's article - Be your own certificate authority (CA) and issue certificates for your local development environment and get HTTPS working in Windows 10.

*How to install an SSL certificate on a Tomcat server


text:
Q: How to add ggplot legend of two different lines R? I need to add a legend of the two lines (best fit line and 45 degree line) on TOP of my two plots. Sorry I don't know how to add plots! Please please please help me, I really appreciate it!!!!
Here is an example
type=factor(rep(c("A","B","C"),5))
xvariable=seq(1,15)
yvariable=2*xvariable+rnorm(15,0,2)
newdata=data.frame(type,xvariable,yvariable)
p = ggplot(newdata,aes(x=xvariable,y=yvariable))
p+geom_point(size=3)+ facet_wrap(~ type) +
  geom_abline(intercept =0, slope =1,color="red",size=1)+
  stat_smooth(method="lm", se=FALSE,size=1)

A: Here is another approach which uses aesthetic mapping to string constants to identify different groups and create a legend.
First an alternate way to create your test data (and naming it DF instead of newdata)
DF <- data.frame(type = factor(rep(c("A", "B", "C"), 5)),
                 xvariable = 1:15,
                 yvariable = 2 * (1:15) + rnorm(15, 0, 2))

Now the ggplot code. Note that for both geom_abline and stat_smooth, the colour is set inside and aes call which means each of the two values used will be mapped to a different color and a guide (legend) will be created for that mapping.
ggplot(DF, aes(x = xvariable, y = yvariable)) +
  geom_point(size = 3) +
  geom_abline(aes(colour="one-to-one"), intercept =0, slope = 1, size = 1) +
  stat_smooth(aes(colour="best fit"), method = "lm", se = FALSE, size = 1) +
  facet_wrap(~ type) +
  scale_colour_discrete("")

A: Try this:
# original data
type <- factor(rep(c("A", "B", "C"), 5))
x <- 1:15
y <- 2 * x + rnorm(15, 0, 2)

df <- data.frame(type, x, y)

# create a copy of original data, but set y = x
# this data will be used for the one-to-one line
df2 <- data.frame(type, x, y = x)

# bind original and 'one-to-one data' together
df3 <- rbind.data.frame(df, df2)

# create a grouping variable to separate stat_smoothers based on original and one-to-one data
df3$grp <- as.factor(rep(1:2, each = nrow(df)))

# plot
# use original data for points
# use 'double data' for abline and one-to-one line, set colours by group
ggplot(df, aes(x = x, y = y)) +
  geom_point(size = 3) +
  facet_wrap(~ type) +
  stat_smooth(data = df3, aes(colour = grp), method = "lm", se = FALSE, size = 1) +
  scale_colour_manual(values = c("red","blue"),
                      labels = c("abline", "one-to-one"),
                      name = "") +
  theme(legend.position = "top")

# If you rather want to stack the two keys in the legend you can add:
# guide = guide_legend(direction = "vertical")
#...as argument in scale_colour_manual

Please note that this solution does not extrapolate the one-to-one line outside the range of your data, which seemed to be the case for the original geom_abline.


text:
Q: Is there a way to change the GTK theme for applications run as superuser on KDE? When I run GTK applications on KDE, they use the QtCurve theme that matches my color and font scheme as configured in the KDE System Settings application.
However GTK applications run as superuser use the old default GNOME, regardless of whether I run them with kdesudo, gksudo, or sudo on a terminal.  For example, here's gedit run as superuser on top, and under my normal user account on the bottom:

Strangely, Qt applications run with kdesudo display the default Oxygen styling but use my settings when run with sudo on a terminal.
Is there any way to configure the stying GTK applications use when run as superuser on KDE?

A: Try this.
Create a ~root/.gtkrc-2.0 with contents:
gtk-theme-name = "QtCurve"


text:
Q: VSCode extension works in development but fails when installed I created an extension for adding test files in Ruby on Rails - https://github.com/SimonBo/rails-go-to-test. It works when I test it locally (press F5 from VSCode with the extension code open) but when I package the extension and install it i get =>  "command 'extension.goToTest' not found". The problem is probably with runtime dependencies but not sure how to fix this.

A: It might be that the version of VSCode you have on your computer is older than the version specified in your package.json.
    "engines": {
        "vscode": "^1.45.0"
    },

If you're certain that your extension will work with an older version like "^1.32.0" , update the engines key in your package.json as well as the version of @types/vscode, etc. in your devDependencies.
If this doesn't work, make sure that all the paths in your package.json are specified correctly.

A: Turns out I was using mkdirp but it wasnt specified in dependencies in package.json, adding the following line fixed everything:
"dependencies": {
    "mkdirp": "^0.5.1"
  }


text:
Q: If case for publist biblatex options (for .cls file) I have this if case I run for deciding some options for publist. I tried to use the \ExecutePublistOptions{ } to change the publist options, but it seems this doesn't work in the .cls file/ preamble. I could import biblatex differently for every document class option, but this seems ineficcient as most of the options are the same.
I would like to modify publist options without importing biblatex every time. Is this possible? (the solution must work in preamble/ .cls file)
Here is the MWE:
\documentclass{article}

\usepackage{xcolor}
\definecolor{soft}{rgb}{0.45,0.45,0.45}
\newcommand{\softbullet}{\textcolor{soft}{\small\textbullet}\hspace{0.5em}}

\makeatletter
\newif\if@displayvon
%\DeclareOption{vonname=true}{\@displayvontrue}

\newif\if@publistnormal
%\DeclareOption{bib=normal}{\@publistnormaltrue}

\newif\if@publisthighlight
%\DeclareOption{bib=highlightname}{\@publisthighlighttrue}

\newif\if@publisthideonly
%\DeclareOption{bib=hidenameonly}{\@publisthideonlytrue}

\newcommand{\firstname}[1]{\def\@firstname{#1}}
\newcommand{\vonname}[1]{\def\@vonname{#1}}
\newcommand{\lastname}[1]{\def\@lastname{#1}}

\@publisthideonlytrue

\if@publistnormal
    \RequirePackage[%
            backend=biber,
            %bibstyle=publist,
            style=authoryear,
            hyperref=auto
        ]{biblatex}
    \AtEveryBibitem{\makebox[\bibhang][l]{\softbullet}}
\else
    \RequirePackage[%
            backend=biber,
            bibstyle=publist,
            labeldateparts=false,
            hyperref=auto
        ]{biblatex}
    \defbibenvironment{bibliography}
      {\list
         {\labelitemfont\softbullet}
         {\setlength{\leftmargin}{\bibhang}%
          \setlength{\itemsep}{\bibitemsep}%
          \setlength{\parsep}{\bibparsep}%
          \def\makelabel##1{\hss\llap{##1}}}}%
      {\endlist}
      {\item}
    \if@displayvon
        \plauthorname[\@firstname][\@vonname]{\@lastname}
    \else
        \plauthorname[\@firstname]{\@lastname}
    \fi
    \if@publisthideonly
        \ExecutePublistOptions{hlyear=false}
    \else\fi
    \if@publisthighlight
        \ExecutePublistOptions{plauthorhandling=highlight}
    \else\fi
\fi
\makeatother

\begin{filecontents}[overwrite]{sample.bib}
@book{dirac,
    title = {The Principles of Quantum Mechanics},
    author = {Paul Adrien Maurice Dirac},
    isbn = {9780198520115},
    series = {International series of monographs on physics},
    year = {1981},
    publisher = {Clarendon Press},
}
\end{filecontents}
\addbibresource{sample.bib}

\firstname{Paul Adrien Maurice}
\lastname{Dirac}

\begin{document}
Hello

\nocite{*}
\printbibliography

\end{document}

This is the currently best I can do with the if cases (that works):
Edit: seems like putting \defbibenvironment .. at the end of the publistnormal ifcase: \if@publistnormal ... \else ... \defbibenvironment \fi did not work. So this is what I have:
\if@publistnormal
    \RequirePackage[%
            backend=biber,
            %bibstyle=publist,
            style=authoryear,
            hyperref=auto
        ]{biblatex}
    \AtEveryBibitem{\makebox[\bibhang][l]{\softbullet}}
\else
    \if@publisthideonly
        \RequirePackage[%
                hlyear=false, %
                backend=biber,
                bibstyle=publist,
                labeldateparts=false,
                hyperref=auto
            ]{biblatex}
        \defbibenvironment{bibliography}
          {\list
             {\labelitemfont\softbullet}
             {\setlength{\leftmargin}{\bibhang}%
              \setlength{\itemsep}{\bibitemsep}%
              \setlength{\parsep}{\bibparsep}%
              \def\makelabel##1{\hss\llap{##1}}}}%
          {\endlist}
          {\item}
    \else
        \if@publisthighlight
            \RequirePackage[%
                    plauthorhandling=highlight, %
                    backend=biber,
                    bibstyle=publist,
                    labeldateparts=false,
                    hyperref=auto
                ]{biblatex}
            \defbibenvironment{bibliography}
              {\list
                 {\labelitemfont\softbullet}
                 {\setlength{\leftmargin}{\bibhang}%
                  \setlength{\itemsep}{\bibitemsep}%
                  \setlength{\parsep}{\bibparsep}%
                  \def\makelabel##1{\hss\llap{##1}}}}%
              {\endlist}
              {\item}
        \else
            \RequirePackage[%
                    backend=biber,
                    bibstyle=publist,
                    labeldateparts=false,
                    hyperref=auto
                ]{biblatex}
            \defbibenvironment{bibliography}
              {\list
                 {\labelitemfont\softbullet}
                 {\setlength{\leftmargin}{\bibhang}%
                  \setlength{\itemsep}{\bibitemsep}%
                  \setlength{\parsep}{\bibparsep}%
                  \def\makelabel##1{\hss\llap{##1}}}}%
              {\endlist}
              {\item}
        \fi
    \if@displayvon
        \plauthorname[\@firstname][\@vonname]{\@lastname}
    \else
        \plauthorname[\@firstname]{\@lastname}
    \fi
    \fi
\fi

It feels like there should be some simpler way to do this. Maybe it is possible to pass the optional directly to biblatex in \DeclareOption somehow?
It may very well also be that there is no better way to do it, in which case I'll accept it and just use what I have.
To clairify: all \if@publisthighlight is doing is including hlyear=false when importing biblatex, and \if@publisthideonly includes plauthorhandling=highlight.

A: \ExecutePublistOptions does work in the preamble, but only after publist has been loaded (as the command is defined there).
So something like this (untested) should actually work:
    \if@publistnormal
        \RequirePackage[%
                backend=biber,
                %bibstyle=publist,
                style=authoryear,
                hyperref=auto
            ]{biblatex}
        \AtEveryBibitem{\makebox[\bibhang][l]{\softbullet}}
    \else
       \RequirePackage[%
                    backend=biber,
                    style=publist,
                    labeldateparts=false,
                    hyperref=auto
                ]{biblatex}
    \fi
    \if@publisthideonly
        \ExecutePublistOptions{hlyear=false}
         \defbibenvironment{bibliography}
              {\list
                 {\labelitemfont\softbullet}
                 {\setlength{\leftmargin}{\bibhang}%
                  \setlength{\itemsep}{\bibitemsep}%
                  \setlength{\parsep}{\bibparsep}%
                  \def\makelabel##1{\hss\llap{##1}}}}%
              {\endlist}
              {\item}
      \else
          \if@publisthighlight
               \ExecutePublistOptions{plauthorhandling=highlight}
                \defbibenvironment{bibliography}
                  {\list
                     {\labelitemfont\softbullet}
                     {\setlength{\leftmargin}{\bibhang}%
                      \setlength{\itemsep}{\bibitemsep}%
                      \setlength{\parsep}{\bibparsep}%
                      \def\makelabel##1{\hss\llap{##1}}}}%
                  {\endlist}
                  {\item}
            \else
                \defbibenvironment{bibliography}
                  {\list
                     {\labelitemfont\softbullet}
                     {\setlength{\leftmargin}{\bibhang}%
                      \setlength{\itemsep}{\bibitemsep}%
                      \setlength{\parsep}{\bibparsep}%
                      \def\makelabel##1{\hss\llap{##1}}}}%
                  {\endlist}
                  {\item}
            \fi
        \if@displayvon
            \plauthorname[\@firstname][\@vonname]{\@lastname}
        \else
            \plauthorname[\@firstname]{\@lastname}
        \fi
        \fi
    \fi


text:
Q: onclick how to toggle the limitTo value using AngularJS? On click of my anchor link I want to toggle the list value which is by default initiated as 5 to 500.
that by default I want to show my list values only 5, on click on my link "more" I want to show all other list items, now the text of more will change as "less" kind of accordion, if we click on less now we need to show only 5 list item.
basically how to toggle the value of "limitTo" on click ? now I have 500 on on-click it needs to toggle as 5 when click second time, vs verse...

             5" ng-click="listLimit=500">more

test values

A: I have put together a fiddle for you that does what I think you are after. The key is to keep track of the listLimit inside a controller, which changes upon clicking on the more/less text.
Fiddle is here
HTML:

        This is item {{$index}}

{{totalItems === 5 ? 'more' : 'less'}}

js:
var module = angular.module("MyModule", []);
module.controller("MyController", function($scope) {
    // create the dummy list items
    $scope.list = [];
    for(var i=0; i<100; i++){
        $scope.list.push({
            value: i
        });
    }

    // set the initial item length
    $scope.totalItems = 5;

    // more/less clicked on
    $scope.more = function(){
        if($scope.totalItems === 5){
            $scope.totalItems = $scope.list.length;
        }else{
            $scope.totalItems = 5;
        }
    };
});


text:
Q: Processor affinity on Linux using taskset I have the following code in a bash script:
echo "bash pid => $$";
echo "processor affinity before => $(taskset -p $$)"
taskset -cp ${AN_INTEGER} $$
echo "processor affinity after => $(taskset -p $$)"

I get this output:
processor affinity before => pid 5047's current affinity mask: ff
pid 5047's current affinity list: 0-7
pid 5047's new affinity list: 1
processor affinity after => pid 5047's current affinity mask: 2

does anyone know what this means?
The reason I started messing with processor affinity is because I would launch multiple bash child processes, and all the bash child process affinities had the value "ff" so it seemed like they were all targeting the same CPU.

A: The affinity mask controls the set of processors that a process may run on - not a single specific processor. Bits that are a 1 in this mask mean represent a processor that the process can run on. Since you specified that you want this process run on only CPU 1, the affinity mask is now 0b00000010, or 2.


text:
Q: Running a batch file as an admin Is it possible to run a batch script as an administer?  We need this to be done without any user interaction, so there can't be any password prompt or UAC popups - is this possible?

A: Assuming batch means some sort of windows then you could use the task scheduler to do this.

A: You can use a Joeware tool - CPAU.exe  to accomplish this:
cpau.exe -u machinename\administrator -p secret_password -ex "path_to_a_program.exe" -lwop

This tool makes easy work of running a program in a privileged context on demand.

A: Assuming batch is refering to the UNIX command, you can issue batch commands as root user, too.