text:
Q: Passing a virtual class reference as an argument to constructor I have defined an abstract class Algorithm1 in the .h file. I want this abstract class, Algorithm1 to hold the references to some other abstract classes, and to be able to decide exact which ones during the runtime. So my Algorithm1 holds those references, and I want to be able to pass the exact implementations via the constructor. One exact implementation of Algorithm1 is class Algorithm1A So here is how that looks.
Algorithm1.h
#include "Interval.h"
#include "OrderedAlphabet.hpp"
#include "Rank.h"

//! Algorithm1 interface
class Algorithm1 {

protected:
    Rank &rank;
    OrderedAlphabet &alphabet;
    std::map<symbol_type, occurence_type> &C;

public:
    Algorithm1(Rank &r,
               OrderedAlphabet &a,
               std::map<symbol_type, occurence_type> &c):
                rank(r), alphabet(a), C(c) {
    }

};

#endif /* Algorithm1_h */

Algorithm1A
#include "Algorithm1.h"

class Algorithm1A : Algorithm1 {

    std::string uniqueCharsInInterval(int i, int j) {
        rank.rank() // dome something with ABSTRACT rank
    }

    std::vector<Interval> getIntervals(int i, int j) {
        alphabet.getSize() // do something with alphabet - not abstract
        C.find('x') // do something with C - not abstract
    }
};

Besides that, my Rank class is also an abstract class, but is implemented by the class WTRank, NTRank and so on. So what I really want is to be able to pass WTRank object, but as a Rank reference to the constructor of Algorithm1.
Rank.h
#ifndef Rank_h
#define Rank_h

#include "DataTypes.h"

//! Rank interface
class Rank {
public:
    virtual unsigned long long rank(int index, symbol_type symbol)=0;
};

#endif /* Rank_h */

And my WTRank class is divided into a .h and .cpp file.
WTRank.h
#ifndef WTRank_h
#define WTRank_h

#include "Rank.h"
#include <sdsl/wavelet_trees.hpp>

using namespace sdsl;

//! Rank based on Wavelet Tree
class WTRank: public Rank {

private:
    wt_huff<> wt;

public:
    WTRank(wt_huff<> w_tree) {
        this->wt = w_tree;
    }
    ~WTRank();

    unsigned long long rank(int index, symbol_type symbol);
};

#endif /* WTRank_h */

WTRank.cpp
#include "WTRank.h"

unsigned long long WTRank::rank(int index, symbol_type symbol) {
    return wt.rank(index, symbol);
}

Now if I want to create an Algorithm1A object that implements Algorithm1 abstract class, and I want to give its constructor needed arguments, I am doing something like this - and getting "No matching constructor error."
wt_huff<> wt;
construct_im(wt, str, 1);

OrderedAlphabet alphabet(10);
std::map<symbol_type, occurence_type> C = calculateC(wt, alphabet);
WTRank wtrank = *new WTRank(wt);

Algorithm1A alg = new Algorithm1A(wtrank, &alphabet, &C); // ERROR!!

How should this be done in order to have it working?

A: Constructors are not inherited by default in C++.  If you have C++11, you can explicitly forward your base class constructors to the derived class:
class Algorithm1A : Algorithm1 {
public:
  using Algorithm1::Algorithm1;
  ...
};

A: Constructors are not inherited. You need to define a constructor on Algorithm1A which takes the appropriate arguments.
Algorithm1A::Algorithm1A(Rank &r,
                         OrderedAlphabet &a,
                         std::map<symbol_type, occurence_type> &c):
  Algorithm1(r, a, c)
{}


text:
Q: Switching to developer mode breaks site in Magento 2 (ReflectionException) Basically fresh install of Magento 2.2.5. Whenever I switch to developer mode, my site completely breaks with:
ReflectionException: Class Magento\Framework\App\Http\Interceptor does not exist in /home/200582.cloudwaysapps.com/dyxjcgvyzs/public_html/vendor/magento/framework/Code/Reader/ClassReader.php:19 Stack trace: #0 /home/200582.cloudwaysapps.com/dyxjcgvyzs/public_html/vendor/magento/framework/Code/Reader/ClassReader.php(19): ReflectionClass->__construct('Magento\\Framewo...') #1 /home/200582.cloudwaysapps.com/dyxjcgvyzs/public_html/vendor/magento/framework/ObjectManager/Definition/Runtime.php(44): Magento\Framework\Code\Reader\ClassReader->getConstructor('Magento\\Framewo...') #2 /home/200582.cloudwaysapps.com/dyxjcgvyzs/public_html/vendor/magento/framework/ObjectManager/Factory/Dynamic/Developer.php(48): Magento\Framework\ObjectManager\Definition\Runtime->getParameters('Magento\\Framewo...') #3 /home/200582.cloudwaysapps.com/dyxjcgvyzs/public_html/vendor/magento/framework/ObjectManager/ObjectManager.php(56): Magento\Framework\ObjectManager\Factory\Dynamic\Developer->create('Magento\\Framewo...', Array) #4 /home/200582.cloudwaysapps.com/dyxjcgvyzs/public_html/vendor/magento/framework/App/Bootstrap.php(232): Magento\Framework\ObjectManager\ObjectManager->create('Magento\\Framewo...', Array) #5 /home/200582.cloudwaysapps.com/dyxjcgvyzs/public_html/pub/index.php(36): Magento\Framework\App\Bootstrap->createApplication('Magento\\Framewo...') #6 {main}

After this, I do all kinds of things like resetting permissions, clearing cache, switching back and forth from production to developer, rm -rf var/cache/* var/page_cache/* var/generation/* and find var generated pub/static pub/media app/etc -type f -exec chmod g+w {} \; && find var generated pub/static pub/media app/etc -type d -exec chmod g+ws {} \;, restarting services, and so on. I cannot find a pattern or cause for what is going on. Sometimes I clear the cache, and it comes back. Sometimes I reset permissions, and it works. But sometimes not. But switching to developer mode always breaks it.

A: Turns out this had to do with missing classes that was caused by me running this recommended Magento optimization:
composer dump-autoload -o --apcu

To revert this, I first tried deleting the vendor/composer directory completely, doing composer update, and magento setup:upgrade. This might help others, but I am not 100% sure b/c I then ran into unrelated redirect issues - but I no longer received the ReflectionException error.
When I restored to a backup before doing the dump-autoload, this fixed my Magento 2 install, and I checked the vendor/composer directory to be sure the autoloader files there were the ones installed by default.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How with bootstrap-colorpicker to get selected color only in format "#ffffff"? In my laravel 5.8 / "bootstrap": "^4.0.0" app I use
I use bootstrap-colorpicker with sample :
https://itsjavi.com/bootstrap-colorpicker/tutorial-p02_Advanced_Examples.html
and I want selecting color from picker always to get selected color in format "#ffffff".
But the problem is that periodically got value in rgb format : https://prnt.sc/rwqlqj
Looks like it happens when I click on outer block selection.
Are there some options to get selected color only in format "#ffffff" ?
I tried the example in link above like :
$('#cp_color').colorpicker({
    popover: false,
    inline: false,
    container: true,
})

    .on('colorpickerChange colorpickerCreate', function (e) {
        var colors = e.color.generate('tetrad');

        colors.forEach(function (color, i) {
            var colorStr = color.string(),
                swatch = e.colorpicker.picker
                    .find('.colorpicker-swatch[data-name="tetrad' + (i + 1) + '"]');

            swatch
                .attr('data-value', colorStr)
                .attr('title', colorStr)
                .find('> i')
                .css('background-color', colorStr);
        });
    })
;

But failed and peridically I goy invalid rgb value.
How to get selected color only in format "#ffffff" ?
Thanks!

A: The decision is in additive format parameter :
$('#cp_color').colorpicker({
    inline: false,
    container: true,
    format: 'hex',


text:
Q: Why don't the firebase rules work when I do a kreait / firebase-php operation with the service account? sorry for being naive. I'm a little confused about authentication with kreait/firebase-php package. I defined some rules at firebase console, like:
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
     match /{document=**} {
      allow create,delete:if request.auth.uid == true;
    }

  }
}

The problem is that, even if I change the rule, the behavior of the services(CRUD) will work the same way. It appears that the JSON document (service account downloaded from google) has all permissions or does not require firebase rules.
In my case, I want to restrict access and database operations to users where they don't have authentication and permissions.
I am currently checking the email / password. If the request is true, the method will return a token. After that, I persist the token in CACHE and delete it when the user logs out. With each request, the middleware checks whether the token exists in CACHE. That way, it will only help me to restrict the user's access pages. How do I restrict the operation of the database (CRUD)? Thank you all!

A: This behavior is expected.  Access to Firestore coming from code initialized with a service account will always bypass security rules.  Security rules only apply to access from the web and mobile client SDKs, and the REST API when provided with a Firebase Authentication token.


text:
Q: How to extend django auth user page in the admin site I know how to extend the change_form.html for my app's models. For instance, I have an app called 'sales' - to modify the admin change form I have a template in
[PROJECTDIR]/templates/admin/sales/customer/change_form.html

and I do what I need overriding the various blocks as necessary. This works well.
What I can't figure out, however, is how to modify the admin page for User objects in the same way. I've tried a variety of directory naming structures but none work:
[PROJECTDIR]/templates/admin/auth/user/change_form.html
[PROJECTDIR]/templates/admin/contrib/auth/user/change_form.html
[PROJECTDIR]/templates/admin/django/contrib/auth/user/change_form.html
[PROJECTDIR]/templates/admin/django.contrib.auth/user/change_form.html

I'm likely missing something really simple, but I can't find any docs and my Google-fu is failing to find anything.

A: You might want to check what is going on in ModelAdmin.render_change_form method:
https://github.com/django/django/blob/master/django/contrib/admin/options.py#L1034
You are interested in value of "app_label" variable. In my env it is "auth". So your first option works ok - templates/admin/auth/user/change_form.html


text:
Q: How do you move the cursor(s) to the next occurence of a character in Sublime Text? Let's say we have a file containing this:
name, job, age
Mark, Specialist, 24
Bob Guy, Manager, 43
Susan Third, Data Generation, 30

What I want to do is navigate around the fields. Move to the next field, select a field, etc. This is easily done in VIM by looking for commas (and assuming there are no escaped commas); is it also possible in Sublime Text? And in a way that works with multiple cursors, say one at the beginning of each line?
Bonus points if you can extend it to moving to the next substring or regex match.

A: In your particular use case, a good search to perform to isolate each value would be \w[^,\n]+ - make sure to click the regex button or hit Alt+R (Windows) / Cmd+Option+R (Mac) in the search field.
To navigate to the next match, use F3 (Windows) / Cmd+G (Mac).  Shift+F3 / Cmd+Shift+G will navigate to the previous match.  You can continue doing this after hitting Esc to dismiss the search field, and this will allow you to immediately edit the selected match.
Unfortunately, it doesn't appear that find-next can coexist with multiple selections - it ends up highlighting the first match in the last selection.  You could highlight multiple lines, then split the selection into lines, then use Ctrl (Windows) / Cmd (Mac) + ← or → arrows to some degree, but that will obviously fall apart when some values have spaces.

A: One way to do this is to use vintage mode.
Edit your preferences (e.g. Settings - User) to not ignore the vintage package (which it is in the default preferences).
{
    "ignored_packages": []
}

When you have multiple cursors use the vim command f followed by a character to move all the cursors to the next find of this character. (see https://stackoverflow.com/questions/12495442/what-do-the-f-and-t-commands-do-in-vim)
Unfortunately these only move to characters on the same line and cursors on lines without this character are left where they previously were located. The search command / forgets your multiple cursors.

A: *

*CTRL+A => select all file

*CTRL+SHIFT+L => split selection into lines

*Home => move all selections to the start of the line

*ESC => enter command mode

*f, , => find and move cursors on each line to the first semicolon (repeat until you are on the one you are looking for)

*i => enter insert mode

Job done :)


text:
Q: How to quickly create editor fold? When I was editing GUI class I've found editor fold.
// <editor-fold defaultstate="collapsed" desc="Generated Code">
...
// </editor-fold>

I've started using it for my own purposes, but it's couple of words to write. So I'm looking for any faster way.

A: The previous solutions didn't work for me (maybe because I'm on a mac) so here's how I did it:

*

*Go to IntelliJ IDEA > Preferences > Editor > Live templates

*Click the + button on the top right, enter your template name and the following code:

// <editor-fold defaultstate="collapsed" desc="$DESCRIPTION$">
$SELECTION$$END$
// </editor-fold>

*In the description tab, enter "Code folding", click "Define" (next to "No applicable context yet") and select "Java" (or you can be more specific if you want), check the "Reformat according to style" checkbox and click Ok
Now, if you select multiple lines of text in the editor, press ⌥+⌘+T (CTRL+ALT+T in Windows) and select the "Code folding" template, enter a description and you're done.

A: In Netbeans, you can type 'fcom' and press 'TAB'.
More shortcuts here

A: It is now the default behavior in Netbeans 7.3.1.
Just select the lines and click Surround with ... as below snapshoot.

A: I've found it and it's simple :)
http://wiki.netbeans.org/SurroundWithCodeFolding


text:
Q: How to multi-split a string (WHERE IN query) I am passing a string as param (via massivejs) into my query. The string is formatted as: param = 'red, blue, green'. The param itself does not have a fixed length (',' being the delimiter) as it is populated through what the user sends in (but is maxed out at 10 elements).
How would I break the string down into individual strings inside my query?
Eg of what I am trying to do:
SELECT * FROM table
WHERE name IN (param);

I know this works but is very very crude:
SELECT * FROM table
WHERE name IN (split_part(param, ',', 1), split_part(param, ',', 2) .......)) -- keep going.

Essentially I want to have ('red', 'blue', 'green' ....) inside the IN parenthesis. Is there a nicer way of accomplishing this?

A: You could use the string_to_array function to split the string to an array  and then use the any function to check if your element is contained in it:
SELECT *
FROM   mytable
WHERE  name = ANY(STRING_TO_ARRAY(param, ','));


text:
Q: ModuleNotFoundError: No module named 'tensorflow' Vs code I am running on windows 10. I am having problems with importing TensorFlow. I am in Vs code. I installed tensorflow using pip3. And here is the error:
Traceback (most recent call last):
  File "c:/Users/USER/PycharmProjects/tt/main.py", line 1, in <module>
    import tensorflow as tf
ModuleNotFoundError: No module named 'tensorflow'

I created my project in pycharm.
I am using python 3.7.5 and TensorFlow 2.0.0. This is how I installed TF:
pip3 install tensorflow==2.0.0

please help I was having this problem for a week.
Thanks , In Advance

A: For your work/project, please try to create a new virtual environment and then install all your required packages.
Like this:
$ python3 -m venv env

Activate it:
$ source env/bin/activate

and then install the tensorflow package inside your virtual environment:
pip3 install tensorflow

A: I think you need to create environment separate
and then install tensorflow..
for more information regarding envirnoment Link

A: Do you have several different python environments on your pc? Which python interpreter are you using when you install tensorflow?
The Status Bar will show you the current interpreter in the lower left corner. Check whether it is the same with the one you use when you install tensorflow.
enter image description here

A: I was getting your exact error, but this worked for me:

*

*File->settings

*Workspace tab

*Search for "interpreter"

*Put the complete path to the python.exe you want to execute under "default interpreter path"

It seems VSCode either found (or included) an older version of python that couldn't find the things I installed with pip.
I am a bit of a python newb and I'm guessing the venv approach is superior, but I couldn't get that cooperating with VSCode on windows.


text:
Q: unique solution of system ordinary differential equations Let
$\dot x(t)=x^2(t)+x(t)y(t)$
$\dot y(t)=-x(t)y(t)$
Under the hypotheses $|x(t)|<a(t), |y(t)|<b(t)$, for some $a,b \in C_0$, initial conditions $x(0), y(0)$ bounded by $a,b$, the Picard Lindelof theorem condition is satisfied , since the derivative matrix of the right hand-side column is continuous and, thus, system has a unique solution. How could we find a unique solution? Is there a way to calculate solutions under constraints in mathematica?


text:
Q: QMediaPlayer displays audio only for certain videos I'm using QMediaPlayer according to the example in the docs.
Here's my code:
from PySide2 import QtWidgets
from PySide2 import QtCore
from PySide2.QtMultimedia import QMediaPlayer
from PySide2.QtMultimediaWidgets import QVideoWidget

class App(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.player = QMediaPlayer()
        self.video = QVideoWidget(self)
        self.player.setMedia(QtCore.QUrl.fromLocalFile("D:/path/to/file.webm"))
        self.player.setVideoOutput(self.video)
        self.video.show()
        self.player.play()

    def closeEvent(self, event):
        self.player.stop()
        event.accept()

if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    window = App()
    window.show()
    app.exec_()

Overriding closeEvent was necessary to stop the program hanging on close.
My test videos:

*

*Worked fine:

*

*1080p 60fps vp9/opus webm

*1080p 30fps vp9/opus webm

*480p 30fps vp9/opus webm

*Played audio only (blank window appears):

*

*1080p 30fps H.264/aac mp4

*480p 30fps H.264/aac mp4

*1080p 23.98fps H.264/ac3 mp4

*1080p 23.98fps H.264/ac3 mkv

*1080p 23.98fps vp9/opus webm

*720x404 23.98fps vp9/opus webm

I'm using qt5 on windows and have installed the appropriate codecs (the K-Lite Codec Pack) to play these files (they play in windows media player fine).
Edit:
I've connected to the mediaStatusChanged, videoAvailableChanged and error signals as suggested by @ekhumoro. I get video available as True and mediaStatus as BufferedMedia as soon as I run the program, regardless of whether it is actually displaying the video. The error signal handler is never being triggered.
During these further tests, videos in the "worked fine" section have been occassionaly failing to display video or, even more weirdly, displaying fine but at the minimum window size:

Resizing the window doesn't increase the video's size. No videos in the "played audio only" section of my original tests have ever displayed video so far.
Edit 2:
After a restart (and updated graphics drivers), the first run with a video that didn't originally display video at all displayed in the weird small window. Subsequent runs (I've done 10 or so) have reverted to no video. Similarly a video that originally worked fine had no video on it's first run but is now consistantly small. A different video that originally worked is still playing normally.

A: The problem was to do with sizing as @ekhumoro suggested.
When the QWidget I had inherited tried to work out its size it asked the QVideoWidget that was its only child for its size. Sometimes the QVideoWidget had loaded its video and so provided the correct size but other times it hadn't and so gave a sizeHint of (-1, -1). Because the QVideoWidget wasn't in a layout it wasn't able to resize itself and was stuck too small.
Additionally, the window itself isn't resized by layouts automatically once created (only by the user, or explicitly with adjustSize) so the window stays at its original size even with the QVideoWidget in a layout. The solution is to register a signal handler for the mediaStatusChanged and call updateGeometry and adjustSize.
Finally the other issue with the program hanging on exit was because I hadn't parented the QMediaPlayer on my window.
My modified class:
class App(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.player = QMediaPlayer(self)
        self.video = QVideoWidget(self)
        self.player.setMedia(QtCore.QUrl.fromLocalFile("D:/path/to/video.webm"))
        self.player.setVideoOutput(self.video)
        self.player.mediaStatusChanged.connect(self.video_available_changed)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.video)
        self.player.play()

    def video_available_changed(self, available):
        if available:
            self.video.updateGeometry()
            self.video.adjustSize()
            self.adjustSize()


text:
Q: Preprocessing PHP $_GET variables I've inherited a large and extremely buggy PHP codebase. It needs a thorough review and cleanup, but I'm in need of a stopgap fix in the meantime. In the long run it needs proper user input sanitisation, e.g. as per What's the best method for sanitizing user input with PHP?. However, this just isn't practical in the short term. It's a codebase of thousands of files comprising hundreds of thousands of lines of code and I need some way of blocking the majority of errors as soon as possible.
Many of the scripts use $_GET['id'] as an unsanitised parameter for database lookups. Is there any way of getting PHP to automatically preprocess the $_GET array along these lines:
if( isset( $_GET['id'] ) )
    $_GET['id'] = (int) $_GET['id'];

I'm well aware that:

*

*This isn't a proper fix, just a kludge.

*I could use some kind of find and replace to put this at the top of every file.

*There are almost certainly other unsanitised SQL input problems.

*The code should be using prepared statements.

However, it would block 99% of the problems, and gain me some much needed breathing room. If at all possible I would much prefer to do it globally in the PHP config or the like. Many thanks for any suggestions.
EDIT: Below is some code I've knocked together to include via auto prepend, in case it is useful to others. You'll need to replace the database username, password, and possibly the charset too. In addition to $_GET and $_POST, you might also want to sanitise the $_REQUEST, $_SESSION and $_COOKIE superglobals. Debugging code is included for testing purposes. Note that this is intended as a stopgap, not as a substitute for proper input sanitisation! Thanks again to all who offered advice.
<?php
$debug = false;
if( $debug ) ini_set( 'display_errors', 1 );

if( !function_exists( '_sanitise' ) )
{
    function _sanitise( $input )
    {
        return htmlspecialchars( $input, ENT_QUOTES, 'UTF-8' );
    }
}

if( !function_exists( '_sanitise_sql' ) )
{
    function _sanitise_sql( $input )
    {
        $mysqli = new mysqli( 'localhost', 'username', 'password', 'database' );
        /*if( mysqli_connect_error() )
        {
            echo 'Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error();
        }*/
        $mysqli->set_charset( 'utf8mb4' );
        if( is_array( $input ) )
        {
            $result = array();
            foreach( $input as $key => $value )
            {
                $result[$key] = _sanitise_sql( $value );
            }
            return $result;
        }
        else return $mysqli->real_escape_string( $input );
    }
}

if( !isset( $_GET['_sanitised'] ) )
{
    foreach( $_GET as $key => &$value )
    {
        if( mb_strtolower( $key ) === 'id' ) $value = (int) $value;
        elseif( substr( mb_strtolower( $key ), -3 ) === '_id' ) $value = (int) $value;
        else $value = _sanitise_sql( $value );
    }
    $_GET['_sanitised'] = true;
}

if( !isset( $_POST['_sanitised'] ) )
{
    foreach( $_POST as $key => &$value )
    {
        if( mb_strtolower( $key ) === 'id' ) $value = (int) $value;
        elseif( substr( mb_strtolower( $key ), -3 ) === '_id' ) $value = (int) $value;
        else $value = _sanitise_sql( $value );
    }
    $_POST['_sanitised'] = true;
}

if( $debug )
{
    echo '<pre>$_GET:' . PHP_EOL;
    echo _sanitise( print_r( $_GET, true ) );
    echo PHP_EOL . '$_POST:' . PHP_EOL;
    echo _sanitise( print_r( $_POST, true ) );
    echo '</pre>';
}

A: You can prepend a file for each request with auto-prepend-file in your php.ini
auto_prepend_file = /path/of/your/file.php

and here do every sanitization that you want.

Specifies the name of a file that is automatically parsed before the
  main file. The file is included as if it was called with the require
  function, so include_path is used.


text:
Q: how to count bits using INNER JOIN I have 1 field Participation that have a return type as a bit, in my database i would like to sum all the bits and make a new column. at the moment it  works but i am getting wrong data.
SELECT ID, Participation......,SUM(CASE WHEN NoOfParticipation = 1 THEN 1 ELSE 0 END)
AS NoOfParticipation1, SUM(CASE WHEN NoOfParticipation = 0 THEN 1 ELSE 0 END)
AS NoOfParticipation0 from table1 INNER JOIN table2 on ID=ID
group by ID, Participation ......;

These are the records in my database:
    ID||Participation
    1   0
    1   0
    1   0

I am looking for something like this:
ID||Participation||NoOfParticipation1 ||NoOfParticipation0
 1   0              0                    3

But currently I am getting:
   ID||Participation||NoOfParticipation1 ||NoOfParticipation0
   1   0              0                    1 - this should be 3
   . - further down the list i have records with the same ID
   .
   1   0              0                    1
   1   0              0                    1

A: When you only want one row per ID you shouldn't group by additional columns:
SELECT id,
       Sum(CASE
             WHEN participation = 1 THEN 1
             ELSE 0
           END) AS NoOfParticipation1,
       Sum(CASE
            WHEN participation = 0 THEN 1
             ELSE 0
           END) AS NoOfParticipation0
FROM   table1
       INNER JOIN table2
               ON id = id
GROUP  BY id

A: You should not include Participation in the GROUP BY, instead using an aggregate function like SUM, MAX, or MIN for it. Yo did not state in your question which one you want, I just will use MAX:
SELECT ID,
       MAX(Participation) as Participation,
       SUM(CASE WHEN NoOfParticipation = 1 THEN 1 ELSE 0 END) AS NoOfParticipation1,
       SUM(CASE WHEN NoOfParticipation = 0 THEN 1 ELSE 0 END) AS NoOfParticipation0
 from table1 INNER JOIN table2 on table1.ID = table2.ID
group by ID;

If you use ID and Participation in the group by, you will get different rows per different ID and Participation value combination. I understand your question in a way that you want to have one row in the result per ID. Hence this must be the only column in the GROUP BY, and you must use an aggregation function for all other columns.


text:
Q: Elements below Expandble listview in android I am using an ExpandableListView in my android application.The problem I am facing is that if I have some elements such as a textview below the expandablelistview, it is hidden when a group is clicked and its children are displayed.This happends when I use LinearLayout.Following is my code:
<LinearLayout
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
 >
<ExpandableListView
    android:id="@android:id/list"
    style="@style/listStyle"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:groupIndicator="@drawable/group_indicator"

    />
   <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="TextView below ExpandableListView"
/>
</LinearLayout>

If I replace LinearLayout with RelativeLayout, the reverse happens. The textview is not hidden but either the chidren of the open group or the lower groups in the list are hidden below the textview.How can I solve this probem?

A: Add this line to code :
 android:layout_weight="1"

It will be as follow :
  <LinearLayout
     android:orientation="vertical"
     android:layout_height="fill_parent"
     android:layout_width="fill_parent"    >
 <ExpandableListView
     android:id="@android:id/list"
     style="@style/listStyle"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:layout_weight="1"
     android:groupIndicator="@drawable/group_indicator"          />
  <TextView
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="TextView below ExpandableListView"   />
</LinearLayout>

Hope this help .


text:
Q: How do I return specific list of items via AngularFire $asObject or $asArray I am trying to learn Firebase AngularFire, using the new methods  $asObject or $asArray, along with a data structure recommended in the blog post Denormalizing Your Data is Normal .
Let's say I have data of Lists and Items, and I want to return all the Items contained on a specific List.
FIREBASE ROOT: has two locations: 1) lists, 2) items
    {
  "items" : {
    "itemid1" : {
      "isonlist" : {
        "listid3" : true
      },
      "itemname" : "itemA"
    },
    "itemid2" : {
      "isonlist" : {
        "listid3" : true
      },
      "itemname" : "itemB"
    },
    "itemid3" : {
      "itemname" : "itemC"
    },
    "itemid4" : {
      "itemname" : "itemD"
    }
  },
  "lists" : {
    "listid1" : {
      "listtitle" : "ListA"
    },
    "listid2" : {
      "listtitle" : "ListB"
    },
    "listid3" : {
      "listitems" : {
        "itemid1" : true,
        "itemid2" : true
      },
      "listtitle" : "ListC"
    },
    "listid4" : {
      "listtitle" : "ListD"
    }
  }
}

Here is my code:

Lists of Items

Write out the title of this list:

{{list.listtitle}}

Write each of the itemids for this list - (isonlist):

{{lid}} | {{li}}

Write the itemname for each of the items for this list:

{{iid}} | {{i.$id}} | {{i.itemname}}

This code renders:
Lists of Items
Write out the title of this list:
ListC
Write each of the itemids for this list - (isonlist):
itemid1 | true
itemid2 | true
Write the itemname for each of the items for this list:
0 | itemid1 | itemA
1 | itemid2 | itemB
2 | itemid3 | itemC
3 | itemid4 | itemD
===========================================
ISSUE: $scope.items = arrayItems  returns ALL THE ITEMS in the "items" location.
QUESTION: How do write out the "itemname" for the items only contained on "listid3"
EXCEPTED RESULT (Write out the item name of each of the items on the list "listid3"):
0 | itemid1 | itemA
1 | itemid2 | itemB

A: You are trying to JOIN two data locations: lists and items.
There is no built in support for such JOINs in Firebase, not is there an array that returns a subset in AngularFire.
You will have to write your own (using once for example to retrieve each item in a list) or use join from Kato's Firebase-util library: https://github.com/firebase/firebase-util/tree/master/src/join.
Also see "How to filter a synchronized array?", which covers the same topic.


text:
Q: ASP.NET default regular expression for users' passwords What is the default regular expression used by asp.net create user wizard?
According to the MSDN documentation, it should be something like this:
Regular Expression: @\"(?:.{7,})(?=(.*\d){1,})(?=(.*\W){1,})
Validation Message: Your password must be 7 characters long, and contain at least one number and one special character.
However, it does not work as it does not accept something like 3edc£edc, which is actually accepted when using the default create user wizard.
Any idea about how can I get this regular expression?

A: The error is in the ?: in (?:.{7,})(?=(.*\d){1,})(?=(.*\W){1,}) that is "consuming" the fist seven characters or more characters. It should be ?= OR you can invert the order: (?=(.*\d){1,})(?=(.*\W){1,})(?:.{7,})

A: Just change the order
^(?=(.*\d))(?=(.*\W)).{7,}

I additionally removed the {1,} and anchored it to the start of the string and you don't need a group around the last part
See it here on Regexr


text:
Q: Why are console.log calls showing up in a different order than they are written? I'm new to Node.js and I think I don't understand how it's supposed to work. I'm using steam-tradeoffers, and in my mind, this should first go through one trade offer, then for each item I am going to receive, it loads their inventory and compares it to their inventory until it finds the matching item and prints it. However, it loads all the offers first, then loads all their inventories.
steam.on('webSessionID', function (sessionID) {
    steam.webLogOn(function (newCookie) {
        offers.setup({
            sessionID: sessionID,
            webCookie: newCookie
        }, function (err) {
            if (err) {
                throw err;
            }
            offers.getOffers({
                get_received_offers: 1,
                active_only: 1,
            }, function (error, body) {
                if (body.response.trade_offers_received) {
                    body.response.trade_offers_received.forEach(function (offer) {
                        console.log('TRADE OFFER')
                        offer.items_to_receive.forEach(function (offerItem) {
                            offers.loadPartnerInventory({
                                contextId: 2,
                                partnerSteamId: offer.steamid_other,
                                tradeOfferId: offer.tradeofferid,
                                appId: 730
                            }, function (err, items) {
                                var item;
                                // Load tradable items in inventory
                                for (var i = 0; i < items.length; i++) {
                                    if (items[i].tradable) {
                                        item = items[i];
                                        //if item matches item from their inventory we can get the market name
                                        if (item.id == offerItem.assetid){
                                            console.log(item.market_name)
                                        }
                                    }
                                }
                            });
                        });
                    });
                }
            });
        });

    });
});

Output:
TRADE OFFER
TRADE OFFER
TRADE OFFER
Sticker Capsule 2
Sticker Capsule 2
Sticker Capsule 2

What I expect:
TRADE OFFER
Sticker Capsule 2
TRADE OFFER
Sticker Capsule 2
TRADE OFFER
Sticker Capsule 2

Could someone explain to me what is happening?
e: Example of this being annoying
                        for (var i = 0; i < items.length; i++) {
                            if (items[i].tradable) {
                                item = items[i];
                                //if item matches item from their inventory we can get the market name
                                if (item.id == offerItem.assetid){
                                    // Configure the request
                                    console.log(item.market_name)
                                    var options = {
                                        url: 'http://steamcommunity.com/market/priceoverview/?country=US&currency=1&appid=730&market_hash_name=' + item.market_name,
                                        method: 'GET',
                                        headers: headers
                                    }
                                    // Start the request
                                    request(options, function (error, response, body) {
                                        result = JSON.parse(body)
                                        if (result['success'] == true) {
                                            console.log(item.market_name + " valued at " + result['median_price'])
                                        }
                                    })
                                }
                            }
                        }

output:
429313829
Sticker Capsule 2
429316197
Sticker Capsule 2
429315519
Sticker Capsule 2
Nova | Predator (Field-Tested) valued at $0.09
Nova | Predator (Field-Tested) valued at $0.09
Nova | Predator (Field-Tested) valued at $0.09

As you see, the item should be Sticker Capsule 2, not the nova predator

A: To get them to run in series like you expect, you need to account for the asynchronous nature of node's callbacks.
body.response.trade_offers_received.forEach(function (offer) {
could be replaced with something like this using the fantastic async library.
require('async').series(body.response.trade_offers_received, function(offer, callback){
  //process the offer variable
  callback(); // <- call this to tell async that this item is done being processed.
});

Also though, you will definitely need/want error handling at some point, and maybe want to collect the results of all your actions in the final callback.
require('async').series(body.response.trade_offers_received, function(offer, callback){
  loadPartnerInventoryAsyncCall({offer: offer}, function(err, someOtherResult){
    if (err) {
      return callback(err);
    }

    //process the offer variable
    callback(null, someOtherResults); // <- call this to tell async that this item is done being processed.
  });
}, function(err, allResults){
  if (err){
    console.log('one of my series functions had an error', err);
  }

  //do something with allResults, if you want
});

To try to clarify asynchronous requests with a simple example:
['google.com','yahoo.com','bing.com'].forEach(function(url){
  require('request').get(url, function(err, result){
    console.log(result);
  });
});

because of network delays, I don't know which page result is going to get logged first! They could come out in any order!


text:
Q: Use here-document in a one-liner? I have a simple script that executes commands on remote host using ssh and a here-document.
I was trying to do it with a one-liner at command line but I couldn't figure out how to do the here-document outside of a script. Is it possible? I spent some time googling and reading documentation about here-documents, but it wasn't coming to me.
This script works fine - I needed the here-document section in order to run awk remotely via ssh but I usually like to do one-liners for simple stuff:
#!/bin/bash
# it looks up all my hosts with 'db' in the name
# then gets the PID of any rsyncs running as user 'research'
# and pumps them into xargs

getHosts=(`curl --silent "http://assetts.lab/all_hosts" | grep -v ^# | awk -F" " '{print$1}'|grep db`)
for BOX in ${getHosts[@]};do
    echo "$BOX: "
    ssh -T sshUser@$BOX <<"EOF"
ps -ef | egrep "rsync|iasync" | awk -F" " '{if ($1 ~ "research") print $2}'|sudo xargs -i ps -fp '{}'
#ps -ef | egrep "rsync|iasync" | awk -F" " '{if ($1 ~ "research") print $2}'|sudo xargs -i kill '{}'
EOF
    echo
done

I'm probably missing something simple...
Anyway thanks for any suggestions :)

A: I don't really see a need to do anything about the use of a here-document, but I do see that you can simplify other things in your script quite a bit (which in turn makes the here-document obsolete).
First of all, the pipeline to populate your getHosts array may be simplified (there is seldom a reason to pipe grep into awk), and the whole array can be removed:
curl -s 'http://assetts.lab/all_hosts' |
awk -F ' ' '!/^#/ && $1 ~ /db/ { print $1 }' |
while IFS= read -r remote; do
   # rest of code
done

Here I have combined your grep+awk+grep command into a single awk command.  I've also let the awk command feed the hostnames directly into the loop instead of storing them in an intermediate variable.
Inside the loop, it looks as if you're wanting to get information about a rsync or iasync process belonging to a research user.
This is best done with pgrep:
pgrep -l -U research 'rsync|iasync'

To signal these processes, use pkill in place of pgrep and drop the -l option.
The full script the becomes:
#!/bin/sh

curl -s 'http://assetts.lab/all_hosts' |
awk -F ' ' '!/^#/ && $1 ~ /db/ { print $1 }' |
while IFS= read -r remote; do
   printf 'Processing host "%s"\n' "$remote"
   ssh "$remote" 'pgrep -l -U research "rsync|iasync"'
done

Or, using xargs:
#!/bin/sh

curl -s 'http://assetts.lab/all_hosts' |
awk -F ' ' '!/^#/ && $1 ~ /db/ { print $1 }' |
xargs -I {} sh -c '
   printf "Processing host \"%s\"\n" "$1"
   ssh "$1" "pgrep -l -U research \"rsync|iasync\""' sh {}

If your xargs supports it, this could be made to run several sh -c processes at once with -P n, where n is the number of concurrent sh -c command that xargs should keep running.

A: The EOF bash feature is basically for use as you do in your example, ie in order to send multiple lines of text to another command.
If you want this as a one-liner, the EOF has to go.
In order to execute a command on a remote host using ssh, all you need to do is:
ssh host command

For example:
ssh host "ls -alh"

will run the command on host and return the output on the console.
Your example code could be rewritten in a one line if you take note of how you use the quotation marks, something like this:
ssh host "ps -ef | egrep 'rsync|iasync' | awk -F' ' '{if (\$1 ~ \"research\") print \$2}'"

This double-quoted string puts the arguments to individual commands in single-quotes.  When more double-quotes are needed (the "research" pattern), they have to be escaped with a \, and so do the $ characters.


text:
Q: The filling of form fields is not supported(Firefox only) I have an editable PDF in which I want to bind some fields in my controller. It was working fine in chrome but firefox shows below message.
"This PDF document contains forms. The filling of form fields is not supported. Open with different Viewer."

A: Not implemented in Firefox's built-in PDF player.  If you're opening a PDF with FireFox's built-in PDF player, you will not be able to use it as a fill-able form. Adobe pdf plugins are no longer supported. Open in Adobe Reader.
I found this link:
https://support.mozilla.org/bm/questions/1160095

A: It seems that FF v81 is going to have this feature.
Here is the ghacks announce.

A: Latest update :
V81 has it.
This feature is disabled by default, To enable it

Enter about:config in the URL bar and check the pdfjs.renderInteractiveForms preference. It is False by default, change it to True

Mozilla support page


text:
Q: Am installing Xampp, the apache service in xampp is not getting installed properly Am installing Xampp, the apache service in xampp is not getting installed properly because of an error " port 80 or 443 is already in use". I dont have IIS or skype in my system. The process running at 443 is svchost, and i cant stop it and unable to fix the issue...pls help me

A: probadly port 80 is used by SQL server reporting services, you should disable it, Run>services.msc> search for SQL server reporting services (MSSQLSERVER) and disable it, then restart your Xampp, hope this help! :)


text:
Q: Why does my v-select not have any default values even though I am assigning v-model a string I am editing a vue for a project that I am working on. Below is my code
<tr v-for="(program, index) in selectedGantryLocation.pickPrograms">
                    <v-select :items="program"
                              :v-model="selectedGantryLocation.pickProgramValues[index]">
                    </v-select>
 </tr>

The selectedGantryLocation.pickPrograms is a list of a list of strings. So each "program" that is being used in the iteration is an array of strings, it is nothing more and nothing less. The array generally looks like ["Program1","Program2","Program3" etc.]. The :items are being populated correctly and are displayed correctly in the dropdown.
Now because in this vue each dropdown will already have a previously selected value that I am grabbing from the backend, I need each dropdown to show the already selected value. selectedGantryLocation.pickProgramValues[index] is indexing a list of strings, each being the default value of each v-select that is created.
For some reason the v-model is not showing any default values. I have verified that the selectedGantryLocation.pickProgramValues is indeed populated and filled with strings. Is there an issue with assigning v-model to a string? If that is the case then I do not know how to go about fixing this issue as I have no more properties to reference because I am only working with lists of strings.
I also know that this won't work if the v-model value does not exist in the :items but I have also verified that it does exist here so that should not be an issue.
If anyone has any ideas of why my v-selects do not have any default values I would appreciate your feedback, thank you!


text:
Q: How to process a set of attributes from an xml document I am working on a xml processing project. The goal of the project is to take a list of keyterms and descriptions from a document written like so:
<?xml version="1.0" encoding="utf-8"?>
<wordmatch>
    <exercise>
        <key>
        <keyterm>Loop Body</keyterm>
        <decription>is the part of the body that contains the statements to be repeated</decription>
        </key>
        <key>
        <keyterm>Iteration</keyterm>
        <decription>is one time execution of the loop body.</decription>
        </key>
        <key>
        <keyterm>Loop Condition</keyterm>
        <decription>Description</decription>
        </key>
        <key>
        <keyterm>Infinite Loop</keyterm>
        <decription>Description</decription>
        </key>
        <key>
        <keyterm>Sentinel Value</keyterm>
        <decription>Description</decription>
        </key>
        <key>
        <keyterm>Off-by-one</keyterm>
        <decription>is an error in the program that causes the loop body to be executed one more or less time.</decription>
        </key>
        <key>
        <keyterm>Input Redirection</keyterm>
        <decription>is to redirect the output to a data file rather to the console. The file is specified at the command line after the symbol >.</decription>
        </key>
        <!-- <key>
        <keyterm>Output Redirection</keyterm>
        <decription>is to redirect the input from a data file rather from the keyboard. The file is specified at the command line after the symbol <.</decription>
        </key> -->
    </exercise>
    <filename>Section5_2.html</filename>
</wordmatch>

Then process the keyterms and descriptions into respective arrays. I've written the following method for parsing the xml document
private static InputStream readXmlFileIntoInputStream(final String fileName) {
        System.out.println("processing:" + fileName);
        return Main.class.getClassLoader().getResourceAsStream(fileName);
    }

    public static Document readXML(String fileName) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        // This is used to prevent xml injection attacks
        try(InputStream inputStream = new FileInputStream(fileName)){
            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(inputStream);
            doc.getDocumentElement().normalize();
        }
        catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }
            return doc;
    }

The method for processing the xml document takes the doc as an argument
public static void processKeyTermsAndDescriptions(Document doc) {
        System.out.println(doc.getDocumentElement().getNodeName());

        //TODO: add keyterms to array.

        //TODO: add descriptions to array.

    }

A minimal reproducible example is the following:
private static final String FILENAME = "./src/resources/exercise.xml";
    private static Document doc;
    private static ArrayList<String> keyterms;
    private static ArrayList<String> descriptions;

    public static void main(String args[]) {
        System.out.println("Step 1 read xml document");
        Document doc = readXML(FILENAME);

        System.out.println("Step 2 for each key add keyterm and description to respective arrays");
        processKeyTermsAndDescriptions(doc);

        System.out.println("Step 3 print header");
        String header = printHeader();

        System.out.println("Step 4 print body w/ keyterms and descriptions");
        String body = printBodyWithKeyTermsAndDescriptions(keyterms,descriptions);

        System.out.println("Step 5 print footer");
        String footer = printFooter(keyterms,descriptions);

        System.out.println(header);
        System.out.println(body);
        System.out.println(footer);

        // Instantiate the Factory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    }

I would like to figure out how to loop over the elements in the xml document to process keyterms and descriptions into respective arrays.


text:
Q: Error Caused by: java.lang.ClassCastException: enter image description here
I am creating a chat in android studio, when I run the program everything comes up with green chekes, but in the log I get the following error and send me to correct the problem in the Main Activity, in the emoludar opens the application and closes it.
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: mensajeria.chatappsistema, PID: 11008
    java.lang.RuntimeException: Unable to start activity ComponentInfo{mensajeria.chatappsistema/mensajeria.chatappsistema.MainActivity}: java.lang.ClassCastException: android.support.v7.app.AlertController$RecycleListView cannot be cast to android.support.v7.widget.RecyclerView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.ClassCastException: android.support.v7.app.AlertController$RecycleListView cannot be cast to android.support.v7.widget.RecyclerView
        at mensajeria.chatappsistema.MainActivity.onCreate(MainActivity.java:38)
        at android.app.Activity.performCreate(Activity.java:7009)
        at android.app.Activity.performCreate(Activity.java:7000)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
E/FirebaseInstanceId: Token retrieval failed: SERVICE_NOT_AVAILABLE
E/FirebaseInstanceId: Token retrieval failed: SERVICE_NOT_AVAILABLE
E/FirebaseInstanceId: Token retrieval failed: SERVICE_NOT_AVAILABLE
Application terminated.

A: In XML file you are using different recyclerview and java you are casting different recyclerview that's why the error is coming. Use the same type of recyclerview in both XML and java file.


text:
Q: Quadratic form inequality? I'm working on a problem, and to finish it I need to show that
$$\mu^T (I-X(X^TX)^{-1}X^T)\mu \geq 0$$
But I'm stuck at showing this.
My first thought was to write this as trace
$$tr(\mu^T\mu) \geq tr(\mu^T X(X^TX)^{-1}X^T \mu)$$
and try to use the idempotence of $X(X^TX)^{-1}X^T$ and the fact its rank is $r(X) \leq n$. However I don't really see how that helps here.
Alternatively, I thought I could use the formula for the expected value of a quadratic form, which involves terms like the traces involved. But again, not much luck.
Any advice?

A: The matrix $X(X^TX)^{-1}X^T$ is not only idempotent but also symmetric, hence an orthogonal projection. The same is true for $I -X(X^TX)^{-1}X^T$: it is symmetric and idempotent. Then
$$
\mu^T( I -X(X^TX)^{-1}X^T)\mu = \mu^T( I -X(X^TX)^{-1}X^T)^2\mu
= \|( I -X(X^TX)^{-1}X^T)\mu\|^2 \ge0.
$$


text:
Q: What does 'symbol-keyed' mean in `JSON.stringify` There is a Object generated by Node.js, it looks like this when I use console.log:
{ dataValues: { a: 1, b: 2 }, fn1: function(){}, fn2: function(){} }

when I use JSON.stringify, it return this string:
{"a":1,"b":1}

I checked the mozilla developer center and found this:

All symbol-keyed properties will be completely ignored, even when using the replacer function.

I think the 'dataValues' must be the 'symbol-keyed' property, but what does 'symbol-keyed' mean?
btw, I use the sequelizejs ORM lib to generate this object.

A: I found the reason finally in the same page:

If an object being stringified has a property named toJSON whose value is a function, then the toJSON method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON method when called will be serialized.

It runs on browser normally.
    Here is the jsfiddle to run it like I asked.
Code:
function test(data) {
    for(var key in data){
        this[key] = data[key];
    }
}

test.prototype.toJSON = function(){
    return this.dataValues;
}

var a = new test({dataValues: {a:1, b:2}});

console.log(a);//the instance
console.log(JSON.stringify(a));//{"a":1,"b":1}

A: Nah, the relevant part to your issue is this blurb:

If undefined, a function, or a symbol is encountered during conversion
  it is either omitted (when it is found in an object) or censored to
  null (when it is found in an array).

So in other words, if your JSON object contains functions, they are omitted during the JSON.stringify process.
"symbol-keyed" refers to a new primitive type introduced in ecmascript6. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof for more info.
This is an example of a "symbol-keyed" property:
{[Symbol("foo")]: "foo"}

Reference for JavaScript Symbol: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol


text:
Q: I want maximum keys count from json data in postgres I have this data:
 invid |            contents
-------+---------------------------------
   109 | {"49": {"22000.00": "10.00"}}
   108 | {"49": {"22000.00": "312.00"}}
   106 | {"48": {"50000.00": "20.00"}}
   103 | {"50": {"1020000.00": "20.00"}}
   102 | {"48": {"50500.00": "20.00"}}
   101 | {"52": {"30060000.00": "0.00"}}
    89 | {"50": {"1020000.00": "2.00"}}
    88 | {"48": {"50000.00": "20.00"}}
    87 | {"50": {"1020000.00": "1.00"}}
    86 | {"50": {"10020000.00": "3.00"}}
    83 | {"48": {"50000.00": "30.00"}}
    82 | {"50": {"1020000.00": "4.00"}}
    81 | {"47": {"20000.00": "40.00"}}
    80 | {"48": {"50000.00": "200.00"}}
    79 | {"50": {"1020000.00": "20.00"}}

I want result:
[{50:5,48:4,49:3,52:1,47:1}]

or
[{'50':5,'48':4,'49':3,'52':1,'47':1}]

in descending order.

A: You need to extract all keys and the group the result:
select ky, count(*) as numkeys
from data
   cross join lateral jsonb_object_keys(contents) as t(ky)
group by ky
order by ky;

If you want a single JSON array with the result you can use jsonb_object_agg():
select jsonb_object_agg(ky, numkeys)
from (
  select ky, count(*) as numkeys
  from data
    cross join lateral jsonb_object_keys(contents) as t(ky)
  group by ky
  order by ky
) t;

Online example: https://rextester.com/HDB83302


text:
Q: Groovy extract list of XML nodes in another file I have xml file which contains thousands of xml nodes. In my groovy code I want to extract N of them and push into another file. How I can do this with groovy?
Some sample listing:
def ibr = new File('/Users/alex/Downloads/temp.xml');
def ibrParser = new XmlParser().parseText(ibr.getText());

def groups = [];
int current = 0;

ibrParser.each { group ->
    if (current <= 100) {
        groups<<group
    }
    current++
}
//how to store groups as xml into another file?

A: Following code helped me:
int current = 0;

def nodeToSerialize;

ibrParser.each { renewalQuote ->
    if (current <= 100) {
        if (nodeToSerialize == null) {
            nodeToSerialize = renewalQuote;
        } else {
            nodeToSerialize.append(renewalQuote)
        }
    }
    current++
}

XmlUtil.serialize(nodeToSerialize, new FileOutputStream("/Users/alex/Downloads/100Cases.xml"))


text:
Q: Regex match issue with \d* and | I have two regex to parse some information  in python

*

*(block|tower|building|wing)\s*[-]*\s*(\d* |[A-Za-z]{1,3})

*(block|tower|building|wing)\s*[-]*\s*(\d*|[A-Za-z]{1,3})
Notice the missing space after \d* . The first one matches the string block A but the second  one does not. I am not able to understand what is wrong in the second one ?


text:
Q: meteor: add some value to nested documents I'm trying to add a value to a nested schema:
groups = new SimpleSchema({
    title:      { type: String, optional: true },
    element:    { type: [elements], optional: true }
});

elements = new SimpleSchema({
    description:{ type: String, optional: true },
    anything:    { type: String, optional: true }
});

MongoDB.attachSchema(new SimpleSchema({
    title:      { type: String },
    slug:       { type: String, unique: true },
    language:   { type: String, defaultValue: "en" },
    group:      { type: [groups], optional: true },
}));

Now I want to add just a new element-description to an existing entry in the DB. I tried this, but it doesn't work.
Uncaught Error: When the modifier option is true, validation object must have at least one operator
var newElement = {
  description: 'insert this as a new element description'
};
MongoDB.update({ _id: Id }, { $push: { 'group.element': newElement }}, function(error) { if(error) console.warn(error); });

Is it correct to use 'group.element' as a $push-parameter?
Update
I forgot the index of group: $push: { 'group.0.element': newElement }
Also I have to define elements before groups in the schema.


text:
Q: Create an API within existing web application or separate? I've read through a few questions related to this topic ( Jersey REST API as a separate web app, Should web service be separate from web site?), but I still struggle to understand which design practice would work best for an existing application.
I inherited a java web application built on spring and hibernate JPA. It's currently in production with new features being developed.
Concurrently, I will need to design a REST API that will have some form of authentication/user tracking. The web application has its own user authentication system that is likely going to be different than the API implementation (i.e. username/pw vs api keys (?)).
Given this situation, I think it'd be best to develop them separately, but I feel like in the beginning, there will be a lot of code duplication (as a result of all the jpa implementation in the web application). Ideally, once I have the rest api in place, I would switch the web application to use the API as well and remove most of the backend code that currently handles the data retrieval.
Before I start down this route though, I was wondering, is there a better way to do this?

A: you can use Spring Security and create a custom AuthenticationProvider . You can use a JNDI lookup to get the authservice directly from the Container it self.
Example:
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
     @Autowired
     private AuthService authService;

public Authentication authenticate(Authentication authentication)
  throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();

    // use the credentials to try to authenticate against the third party system
    if (authService(name, password)) {
        List<GrantedAuthority> grantedAuths = new ArrayList<>();
        return new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
    } else {
        throw new AuthenticationException("Unable to auth against third party systems");
    }
}

@Override
public boolean supports(Class<?> authentication) {
    return authentication.equals(UsernamePasswordAuthenticationToken.class);
}

Also, read more about RESTful apis using Spring here:
http://www.baeldung.com/rest-with-spring-series/


text:
Q: What is MSBuild and it's purpose
Possible Duplicate:
MSBuild: What is it, and when do I need it?

I`ve never used MSBuild and have no idea what is the purpose of MSBuild. It would be nice if anyone describe briefly that in what kind of situation people use MSBuild.

A: Basically MsBuild is for building your project/solution. You can use msbuild commandline prompt to build your project rather than right click and build. MsBuild is very useful when it comes to automated build servers where you build projects once somebody checkin any new code.
Another advantage of msbuild is, it's capable to build your project without having VS IDE. You don't need VS IDE to build your project in automated build servers.
Below are few sites that provide good information for you.
http://msdn2.microsoft.com/en-us/library/wea2sca5.aspx  MSDN MSBuild Documentation
http://channel9.msdn.com/wiki/default.aspx/MSBuild.HomePage  MSBuild Wikki
http://msdn2.microsoft.com/en-us/library/0k6kkbsd.aspx MSBuild Reference
http://blogs.msdn.com/msbuild/default.aspx MSBuild Team Blog

A: MSBuild is a build utility from Microsoft, similar to ANT in Java world. It provides a way to define your build requirements, dependency, order etc, by editing xml files. You can use existing tasks, or create custom tasks as per your need and utilize them in the process of build.
ex: you can define a build solution, and set order of projects to build, where to fetch latest data, where to put binaries, where to deploy, whom to inform by sending mail, what to do in the case of errors etc. (Almost everything is a task, and each task may have pre and post conditions)
refer: http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx


text:
Q: How can I use word2vec to train a classifier? The code is used to generate word2vec and use it to train the naive Bayes classifier.
I am able to generate word2vec and use the similarity functions successfully.As a next step I would want to use the word2vec to train the naive bayes classifier. Currently the code given an error when I am trying to slit the data in test and training. How do i convert word2vec model into the array so that it can be used as training data.
# Importing the libraries
    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    import gensim
# Importing the dataset
dataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter = '\t', quoting = 3)

# Cleaning the texts
import re
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
corpus = []
for i in range(0, 1000):
    review = re.sub('[^a-zA-Z]', ' ', dataset['Review'][i])
    review = review.lower()
    review = review.split()
    ps = PorterStemmer()
    review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]
#    for word2vec we want an array of vectors

    corpus.append(review)

#print(corpus)
X = gensim.models.Word2Vec(corpus, min_count=1,size=1000)
#print (X.most_similar("love"))

#embedding_matrix = np.zeros(len(X.wv.vocab), dtype='float32')
#for i in range(len(X.wv.vocab)):
#    embedding_vector = X.wv[X.wv.index2word[i]]
#    if embedding_vector is not None:
#        embedding_matrix[i] = embedding_vector

# Creating the Bag of Words model
#from sklearn.feature_extraction.text import CountVectorizer
#cv = CountVectorizer(max_features = 1500)
#X = cv.fit_transform(corpus).toarray()
y = dataset.iloc[:, 1].values

# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)

# Fitting Naive Bayes to the Training set
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(X_train, y_train)

# Predicting the Test set results
y_pred = classifier.predict(X_test)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

It gives an error on line -
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)
TypeError: Expected sequence or array-like, got <class 'gensim.models.word2vec.Word2Vec'>

A: Word2Vec provides word embeddings only. If you want to characterize documents by embeddings, you'll need to perform an averaging/summing/max operation on embeddings of all words from each document to have a D-dimensional vector that can be used for classification. See here and there for further information on this.
Otherwise, you can use Doc2Vec model to directly produce document embeddings, for which gensim also gives a very good provider.

A: You have vectors for each word, now you have two approaches to move forward, one could be simply take average of all the words in a sentence to find the sentence vector, another could be to use tfidf.
I implemented the average approach in one of my ongoing projects and i am sharing the github link, please go to the heading "text vectorization(word2vec)" and you will find the code their.
https://github.com/abhibhargav29/SentimentAnalysis/blob/master/SentimentAnalysis.ipynb. I would however suggest you to read data cleaning before as well to understand it in a better way.
One important advice: Do not split the data into train, cv, test after vectorization, do it before vectorization or you will overfit the model.


text:
Q: Pandas: remove group from the data when a value in the group contains similar value df = pd.DataFrame({"name":["A", "A", "B" ,"B", "C", "C"],
                   "nickname":["X","Y","X","Z","Y", "Y"]})

How can I group df by "name" and drop those groups that contains only 'Y'?
In my case 'C' should be dropped.
I am using below code but it is not working:
df_new = df.groupby('name').filter(lambda x: all(x['nickname'] != 'Y'))

In case, Y occurs in any other 'name' with some other nickname then that name should be retained. Kindly help.

A: Here groupby is not necessary. You can use boolean indexing:
df = df[df['name'].isin(df.loc[df['nickname'].ne('Y'), 'name'].unique())]
print (df)
  name nickname
0    A        X
1    A        Y
2    B        X
3    B        Z

Explanation:
First compare by ne for not equal values:
print (df['nickname'].ne('Y'))
0     True
1    False
2     True
3     True
4    False
5    False
Name: nickname, dtype: bool

Then select column name bu boolean mask:
print (df.loc[df['nickname'].ne('Y'), 'name'])
0    A
2    B
3    B
Name: name, dtype: object

For better performance get unique values:
print(df.loc[df['nickname'].ne('Y'), 'name'].unique())
['A' 'B']

And filter by isin for final mask:
print (df['name'].isin(df.loc[df['nickname'].ne('Y'), 'name'].unique()))
0     True
1     True
2     True
3     True
4    False
5    False
Name: name, dtype: bool

Performance:
Depends of number of rows, number of unique groups and number of matched values - best test in your real data:
np.random.seed(123)
N = 100000

df = pd.DataFrame({'name': np.random.randint(1000,size=N).astype(str),
                   'nickname':np.random.randint(200,size=N).astype(str)})
#print (df)

In [152]: %timeit df[df.nickname.ne('Y').groupby(df.name).transform('sum').astype(bool)]
27.6 ms ± 292 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [153]: %timeit df[~df.nickname.eq('Y').groupby(df.name).transform('all')]
27.3 ms ± 162 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [154]: %timeit df[df['name'].isin(df.loc[df['nickname'].ne('Y'), 'name'].unique())]
28.9 ms ± 189 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [155]: %timeit df[~df.assign(mask=df.nickname.eq('Y')).groupby('name').mask.transform('all')]
30.3 ms ± 469 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [156]: %timeit df[df.groupby('name')['nickname'].transform('unique').astype(str) !="['Y']"]
15.6 s ± 233 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [157]: %timeit df.groupby('name').filter(lambda x: any(x['nickname'] != 'Y'))
408 ms ± 29.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

A: You probably want groupby and transform, or some derivative of the same thing.
df[~df.nickname.eq('Y').groupby(df.name).transform('all')]
# Or,
# df[~df.assign(mask=df.nickname.eq('Y')).groupby('name').mask.transform('all')]

  name nickname
0    A        X
1    A        Y
2    B        X
3    B        Z

An even faster groupby-related solution involves... counting!
df[df.nickname.ne('Y').groupby(df.name).transform('sum').astype(bool)]

  name nickname
0    A        X
1    A        Y
2    B        X
3    B        Z

A: simply use this,
temp= df.groupby('name')['nickname'].transform('unique').astype(str)
df=df[temp!="['Y']"]
print df

O/P
  name nickname
0    A        X
1    A        Y
2    B        X
3    B        Z

A: I think that maybe you needed in your solution any instead of all:
df_new = df.groupby('name').filter(lambda x: any(x['nickname'] != 'Y'))

Output:
  name nickname
0    A        X
1    A        Y
2    B        X
3    B        Z


text:
Q: ILSpy decompile a delegate ILSpy can decompile assemblies. Can it decompile a delegate? I would imagine a CSharpDecompiler constructor overload accepting a Func or an Action as an argument instead of a "string fileName". Is it technically feasible, are there any future plans to support this? Any suggested work-arounds?
Example of what I had in mind....
Action<int> myAction = i =>
{
    // body to be decompiled
};
var decompiler = new CSharpDecompiler(myAction, new DecompilerSettings());
decompiler.DecompileAsString();

A: An official ILSpy member has answered in the project's discussion section:
"It's not possible, because the decompiler requires a full PE image containing IL code and .NET metadata tables"
https://github.com/icsharpcode/ILSpy/discussions/2581


text:
Q: GridSearchCV best_score_ different from cross_val_score of best_estimator_ The best result given by GridSearchCV is different to the cross_val_score of the best_estimator_: GridSearchCV best estimator score: 2.890
np.random.seed(42)
kf1 = KFold(n_splits=5, random_state=7425, shuffle=True)
grid_search=GridSearchCV(forest_reg,param_grid,cv=kf1, scoring='neg_mean_squared_error', return_train_score=True)
grid_search.fit(DATA_prepared,DATA_labels)
BestGSCDV_score=np.sqrt(-grid_search.best_score_)

Gives a different result than crossval: 2.941
np.random.seed(42)
kf1 = KFold(n_splits=5, random_state=7425, shuffle=True)
RFR_scores2=cross_val_score(grid_search.best_estimator_, DATA_prepared, DATA_labels, scoring='neg_mean_squared_error', cv=kf1)
cvscore=np.sqrt(-RFR_scores2.mean())

I'm wondering what is causing this since the random state and even the random seed should ensure the splits of kf1 are identical over each call.


text:
Q: Java equivalent of Python's __eq__ and __bool__ I'd like to perform equivalency and boolean tests quickly on my Java instances.  How I do the equivalent of the Python3 code in Java?  (notice that there is no reference to any attribute - just the instance itself)
test.py
class Number:
    def __init__(self,n):
        self.n = n
    def __eq__(self, num):
        return self.n == num
    def __bool__(self):
        return True

def main():
    t = Number(10)
    if t == 10:
        print("Equivalency")
    if t:
        print("Boolean")

if __name__ == "__main__":
    main()

Output
$ python3 test.py
Equivalency
Boolean

A: You cannot override ==, nor can you implement a __bool__ equivalent. However, you most definitely should override equals() (and probably hashCode() as well). This equals method will be used by everything to compare object equality. The only time you would use == is if you wanted to see if two variables were pointing to the same object in memory.
@Override
public boolean equals(Object other) {
    ...
}


text:
Q: Can we integrate iFrame in PHP file? Can we integrate iframes in PHP files ?
If so, can anyone please provide an example.
Thanks in advance.
Merci,
Serenity.

A: You are misunderstanding what PHP does. PHP is used to generate HTML (among other things). Seeing as you can have an iFrame in a HTML file, I guess the answer to your question is "yes".
You are probably better off describing what you want to do to get more detailed advice.

A: Surely, you would just use
print '<iframe></iframe>';

Is that what you mean?
It's important to note that you don't need to use this method. You can write HTML directly in the source, you don't need to print it using PHP.


text:
Q: How to find all files with certain extension on Android? I'm using a fileBrowser to find the files on the phone, but I wanted to show all files that my app can open to the user, and then the user chooses one. Like the Music Player, that show all songs on phone, on the sdcard and in the internal memory, not only the ones in the folder where the user is.

A: Use file name filters while listing out the files. The below sample lists out all mp3 files in a given root directory (Note - The below code doesn't do it recursively for all folders under root) -
String files[] = root.list(audioFilter);

FilenameFilter audioFilter = new FilenameFilter() {
    File f;
    public boolean accept(File dir, String name) {
    if(name.endsWith(".mp3") || name.endsWith(".MP3")) {
            return true;
        }
        f = new File(dir.getAbsolutePath()+"/"+name);

        return f.isDirectory();
    }
};

A: I don't know what FileBrowser implementation you are using but a good one should accept a FileFilter. You can implement your own filter providing code for public abstract boolean accept (File pathname)


text:
Q: Poor convergence for first order PDE using FEM (Laplace's equation in a disk) Consider Laplace's eqn in the unit disk, r^2 D[u[r, t], {r, 2}] + r D[u[r, t], {r, 1}] + D[u[r, t], {t, 2}] == 0.  The general analytic solution is easy to work out, and we can target the n=1 solution (i.e. u = r Cos[t]) using Dirichlet boundary conditions.  The problem is easily solved with the finite element method:
uf1 = NDSolveValue[{r^2 D[u[r, t], {r, 2}] + r D[u[r, t], {r, 1}] +
  D[u[r, t], {t, 2}] == 0,
DirichletCondition[u[r, t] == Cos[t], r == 1 && t != 2 Pi],
PeriodicBoundaryCondition[u[r, t], t == 2 \[Pi],
 Function[x, x - {0, 2 \[Pi]}]]}, u, {r, 0, 1}, {t, 0, 2 Pi}];

Now let's try an alternative way to solve the same problem, using a first order PDE, D[u[r, t], r] == -I/r D[u[r, t], t], for a complex scalar field u.  By separating u into its real and imaginary components, one can show that each satisfy the above Laplace's equation.  We attempt to solve the PDE numerically, matching the Dirichlet condition above (for the real part):
uf2 = NDSolveValue[{D[u[r, t], r] == -I/r D[u[r, t], t],
DirichletCondition[u[r, t] == Exp[I t], r == 1 && t != 2 Pi],
PeriodicBoundaryCondition[u[r, t], t == 2 \[Pi],
 Function[x, x - {0, 2 \[Pi]}]]}, u, {r, 0, 1}, {t, 0, 2 Pi}];

First things look OK: both solutions seem to approximate the exact target solution:
uA[r_, t_] = r Cos[t];
{Plot3D[Re[uf1[r, t]] - uA[r, t], {r, 0, 1}, {t, 0, 2 Pi}], Plot3D[Re[uf2[r, t]] - uA[r, t], {r, 0, 1}, {t, 0, 2 Pi}]}

but the conventional method is much better.
The question is: why does the 1st order method perform so poorly compared with the conventional (2nd order) method?
For the first order problem, Mathematica issues the usual warning about the equation being convection dominated, but can't we ignore this because we know the solutions are nice and smooth?  (Btw, artificial diffusion doesn't help.)  Is there an issue with applying FEM to first order PDEs, even if they are known to be elliptic?
A scan over MaxCellMeasure shows how serious the problem is:
errList1 = {}; errList2 = {};
For[n = 3, n <= 10, n++,
  mcm = 1./2^n;
  mesh = ToElementMesh[FullRegion[2], {{0, 1}, {0, 2 Pi}},
    MaxCellMeasure -> mcm];
  Quiet[
   uf1 = NDSolveValue[{r^2 D[u[r, t], {r, 2}] + r D[u[r, t], {r, 1}] +
         D[u[r, t], {t, 2}] == 0,
      DirichletCondition[u[r, t] == Cos[t], r == 1 && t != 2 Pi],
      PeriodicBoundaryCondition[u[r, t], t == 2 \[Pi],
       Function[x, x - {0, 2 \[Pi]}]]}, u, {r, t} \[Element] mesh];
   uf2 = NDSolveValue[{D[u[r, t], r] == -I/r D[u[r, t], t],
      DirichletCondition[u[r, t] == Exp[I t], r == 1 && t != 2 Pi],
      PeriodicBoundaryCondition[u[r, t], t == 2 \[Pi],
       Function[x, x - {0, 2 \[Pi]}]]}, u, {r, t} \[Element] mesh];
  ];
  err1 = Sqrt[
    Mean[Table[{ri, ti} = c; (Re[uf1[ri, ti]] - uA[ri, ti])^2, {c,
       mesh["Coordinates"]}]]];
  err2 = Sqrt[
    Mean[Table[{ri, ti} = c; (Re[uf2[ri, ti]] - uA[ri, ti])^2, {c,
       mesh["Coordinates"]}]]];
  AppendTo[errList1, {mcm, err1}];
  AppendTo[errList2, {mcm, err2}];
  ];
ListLogLogPlot[{errList2, errList1}]

Although the error of the first solution goes clearly as mcm^2, the error of the second solution does not even convincingly go to zero with mcm.
A final motivating comment:  Although the above problem is easily evaded (though not understood) by using the usual second order formulation, one may be faced with a first order PDE that cannot be easily transformed into the standard 2nd order form.  It would be useful to know how reliably solve an elliptic first order system.

A: I can offer a partial answer to this.  There are two issues I found.
(1) The polar coordinates were problematic at high resolution (I suppose the coordinate singularity at the origin might have been causing a problem), which did not allow me to go to very small mesh measure.  By changing to cartesian coordinates, I was able to push to very small resolution and get more convincing convergence with the first order PDE:
m = 3; uA[x_, y_] = (x + I y)^m;
errList = {};

For[n = 5, n <= 14, n++,
  mcm = 1./2^n;
  meshxy = ToElementMesh[Disk[], MaxCellMeasure -> mcm];
  Quiet[
   uf = NDSolveValue[{(x - I y) D[u[x, y], x] + (y + I x) D[u[x, y],
           y] == 0,
       DirichletCondition[u[x, y] == uA[x, y], x^2 + y^2 == 1]}, u,
      Element[{x, y}, meshxy]];
   ];
  err = Sqrt[
    Mean[Table[{xi, yi} = c; (Norm[uf[xi, yi] - uA[xi, yi]])^2, {c,
       meshxy["Coordinates"]}]]];
  AppendTo[errList, {mcm, err}];
  ];
ListLogLogPlot[errList]

The scaling of the error is only first order in the cell measure, but it is more convincing now.
(2) Poking around in FEM references, I noticed that first order PDEs have a reputation for being poorly handled by "standard" finite element methods, and some texts recommended a "least squares" approach (e.g. Ern, Guermond. Theory and Practice of Finite Elements (2004) chapter 5).  This is equivalent to solving a related higher order PDE, but the format follows rather intuitively from the original PDE:
b = {x - I y, y + I x}; bs = {x + I y, y - I x};
PDE = -Div[bs b.Grad[u[x, y], {x, y}], {x, y}] == 0;

Now we do the error scan as before:
errList = {};
For[m = 5, m <= 14, m++, mcm = 1./2^m;
  meshxy = ToElementMesh[Disk[], MaxCellMeasure -> mcm];
  uf = NDSolveValue[{PDE,
     DirichletCondition[u[x, y] == uA[x, y], x^2 + y^2 == 1]}, u,
    Element[{x, y}, meshxy]];
  err = Sqrt[
    Mean[Table[{xi, yi} = c; (Norm[uf[xi, yi] - uA[xi, yi]])^2, {c,
       meshxy["Coordinates"]}]]];
  AppendTo[errList, {mcm, err}];
  ];
ListLogLogPlot[errList]

This error seems to scale as mcm^1.5.
EDIT
It may be possible to replicate the above performance, using FEM programming and post-processing, instead of solving the second order equation.  Below is one idea that gives a slight improvement over the naive solution of the first order PDE (but does not do as well as solving the second order equation):
GetSystemMatricesLS[PDE_, iVars_, dVars_, mesh_] := Module[{nr, sd, vd, state, femdata, initBCs, initCoeffs, methodData, discretePDE, stiffness, load, LSstiffness, LSload, discreteBCs},
  nr = ToNumericalRegion[mesh];
  sd = NDSolve`SolutionData[{"Space" -> nr}];
  vd = NDSolve`VariableData[{"DependentVariables" -> dVars,
     "Space" -> iVars}];
  methodData = InitializePDEMethodData[vd, sd];
  Quiet[{state} =
    NDSolve`ProcessEquations[PDE, dVars, iVars \[Element] mesh,
     Method -> {"FiniteElement"}]];
  femdata = state["FiniteElementData"];
  initBCs = femdata["BoundaryConditionData"];
  initCoeffs = femdata["PDECoefficientData"];
  discretePDE = DiscretizePDE[initCoeffs, methodData, sd];
  stiffness = discretePDE["StiffnessMatrix"];
  load = discretePDE["LoadVector"];
  discreteBCs =
   DiscretizeBoundaryConditions[initBCs, methodData, sd];
  LSstiffness = ConjugateTranspose[stiffness].stiffness;
  LSload = ConjugateTranspose[stiffness].load;
  DeployBoundaryConditions[{LSload, LSstiffness}, discreteBCs];
  {LSstiffness, LSload}
  ]

Note how the transformation to a symmetrized stiffness matrix is performed before deploying the boundary conditions.
k = 3; uA[x_, y_] = (x + I y)^k;

errList = {};
For[n = 5, n <= 14, n++,
  mcm = 1./2^n;
  PrintTemporary["n: ", n];
  meshxy = ToElementMesh[Disk[], MaxCellMeasure -> mcm];
  {stiffness, load} =
   GetSystemMatricesLS[{(x - I y) D[u[x, y], x] + (y + I x) D[u[x, y],
         y] == 0, DirichletCondition[u[x, y] == uA[x, y], True]}, {x,
     y}, {u}, meshxy];
  solution = LinearSolve[stiffness, load];
  uf = ElementMeshInterpolation[meshxy, solution];
  err = Sqrt[
    Mean[Table[{xi, yi} = c; (Norm[uf[xi, yi] - uA[xi, yi]])^2, {c,
       meshxy["Coordinates"]}]]];
  AppendTo[errList, {mcm, err}];];
ListLogLogPlot[errList]


text:
Q: Html.ActionLink creating unexpected host address in Razor Page Creating an AnchorTag in a Razor page table. The table cell with the OrderNbr needs to be a link to the website (e.g. https://host/main?OrderNbr=012345) with the order using the routevalue of the OrderNbr.
Using asp-host tag helper and getting unexpected results:
@Html.ActionLink(item.OrderNbr, null, null, "https", "host/main", null, Model.routeValues, new Dictionary<string, string> {{"target","_blank"}} )
I'm using ActionLink to create the anchor tag in a cshtml razor page table.
expected result:
Order Number Value

actual result:
Order Number Value

My issue is that if creates it fine EXCEPT that it appends the page route to the host address specified which I didn't expect? The docs do not show this so is this a bug?
Thanks for any insights and assistance.


text:
Q: PsychToolbox keeps crashing a few trials into experiment. Error on line 117 with using screen This is an experiment with 32 trials. A circle and a smiley face appear on the screen. If the participants clicks the smiley face, a video plays. If they click the circle, it skips to the next trial. I am getting an error on line 117
[moviePtr movieDur]= Screen('OpenMovie', window, fullMovieName);
for screen about 8 trials in every time, even when I purposefully select the circle and no video plays.
%ITI setup
ITIlist=[1 1 3 5];
ITItmp=[repmat(ITIlist,[1,nTR/numel(ITIlist)])];
ITI=ITItmp(randperm(numel(ITItmp)));

% %     %get images
stimImg(1,:,:,:)=imread(sprintf('Stim/circle.png'));
stimImgTexture(1)=Screen('MakeTexture',window,squeeze(stimImg(1,:,:,:)),[],[],0);

stimImg(2,:,:,:)=imread(sprintf('Stim/smiley.png'));
stimImgTexture(2)=Screen('MakeTexture',window,squeeze(stimImg(2,:,:,:)),[],[],0);

  %get movies
        MovieIndex=randperm(numel(MovieList));
        stimMovie=MovieList(MovieIndex(1)).name;
        %     stimPath=stimulusList(tr).folder;
        %     stimPath=sprintf('%s\',stimulusList(1).folder);
        MoviePath='G:\My Drive\ABCLab\Alexis\ECITT\VidList\';
        fullMovieName=sprintf('%s%s',MoviePath,stimMovie);
        Screen('FillRect', window, grey, wholeScreenRect);
        Screen('Flip',window);
%         WaitSecs(pretrialduration);
MovieList=dir('VidList/*mp4');
%randomize movies
% MovieIndex=randperm(numel(MovieList));

trialCounter=0;
ntestcards=2;
goodSeq=0;
if condition==1
    domLoc=1;
    stimorder=[repmat([1 2],[8 1]); repmat([2 1],[24 1])];
elseif condition==2
    domLoc=2;
    stimorder=[repmat([1 2],[24 1]); repmat([2 1],[8 1])];
end
while goodSeq==0
    randorder=randperm(size(stimorder,1));
    stimorderTmp=stimorder(randorder,:);
    seqstoreDom=0;
    seqstoreNonDom=0;
    seqstoretmp=0;
    for ix=2:numel(randorder)
        if stimorderTmp(ix-1,1)==domLoc
            if stimorderTmp(ix-1,1)==stimorderTmp(ix,1)
                seqstoretmp=seqstoretmp+1;
            else
                seqstoreDom=[seqstoreDom seqstoretmp];
                seqstoretmp=0;
            end
        else
            if stimorderTmp(ix-1,1)==stimorderTmp(ix,1)
                seqstoretmp=seqstoretmp+1;
            else
                seqstoreNonDom=[seqstoreNonDom seqstoretmp];
                seqstoretmp=0;
            end
        end
    end
    if max(seqstoreDom)<6 & max(seqstoreNonDom)<4
        goodSeq=1;
    end
end
stimorder=stimorderTmp;
for tr=1: nTR
    trialCounter=trialCounter+1;

    fixPoint=Screen('DrawDots',window, [xCenter , yCenter],20,black,[],2);
    Screen('Flip',window);

    %card angles

    stimXY=[(xCenter) (yCenter+400);(xCenter) (yCenter-400)]; %%can adjust if you don't like the location
    stimCoords=[(xCenter-100) (yCenter+400-100) (xCenter+100) (yCenter+400+100);(xCenter-100) (yCenter-400-100) (xCenter+100) (yCenter-400+100) ];

    initWait=1;
    while initWait
        [keyIsDown,secs, keyCode]=KbCheck;
        if keyCode(escKey)
            sca
            return
        elseif keyCode(initKey)
            initWait=0;
        end
        preloadsecs=1;
        pixelFormat=[];
        maxThreads=[];
        [moviePtr movieDur]= Screen('OpenMovie', window, fullMovieName);
        Screen('PlayMovie', moviePtr, 1, 1, 1);
        tStart=GetSecs;

        ListenChar(0); %allows keypresses again
    end

    for arrayInd=1:ntestcards
        Screen('DrawTexture',window,stimImgTexture(1,arrayInd),[],stimCoords(orientation(arrayInd),:));
    end

    Screen('Flip',window);
    tStart = GetSecs;

    %    stim marks
    cw_ser = serial('com4'); %
    set(cw_ser,'BaudRate',9600,'DataBits',8,'Parity','none','StopBits',1,'FlowControl','none','Terminator',13);
    fopen(cw_ser);
    fprintf(cw_ser,'1'); %send a "1" to the interface to active BNC connector#1 to TTL High
    pause(0.15); %Must wait ~120 - 150 ms to allow CW6 to capture
    fprintf(cw_ser,'0'); %send a "0" to the interface to all BNC connectors to TTL Low
    fclose(cw_ser);

    %get clicks
    respWait=1;
    xClick=[];
    yClick=[];
    buttons=[];
    clickDist=[];
    SetMouse(1,1);
    while respWait
        %         [clicks, xClick, yClick, whichbutton] = GetClicks;
        %         [xClick,yClick,buttons] = GetMouseTransient(window,1);
        %         clickXY=[xClick yClick];

        [xClick,yClick,buttons] = GetMouse(window,1);
        clickXY=[xClick yClick];

        clickDist=sqrt( (clickXY(1)-stimXY(:,1)).^2 + (clickXY(2)-stimXY(:,2)).^2);

        %         if any(buttons)
        if min(clickDist)<100  %Might need to adjust
            respLoc=find(clickDist==min(clickDist));
            rtTime=GetSecs;
            respWait=0;
        end
        %         end
    end

    acc = respLoc == orientation(2);

    if acc==1

        Screen('Flip',window);

        while GetSecs<tStart+movieDur

            texture = Screen('GetMovieImage', window, moviePtr);
            if texture ==0
                WaitSecs('YieldSecs',.005);
                continue;
            end
            Screen('DrawTexture', window, texture);
            Screen('Flip', window);
            Screen('Close',texture);

        end
        Screen('CloseMovie',moviePtr);
        Screen('FillRect', window, grey, wholeScreenRect);
        Screen('Flip',window);
        tEnd = GetSecs;
        rt = rtTime - tStart;

        Screen('Clear')
        Screen('FillRect', window, grey, wholeScreenRect);
        Screen('Flip',window);
        WaitSecs(ITI(tr));

    end

end

I have tried deleting several of the videos, it doesn't seem to be an issue with any of them. It also still crashes even when I only select the "incorrect" response (the circle) which would result in no videos being played.


text:
Q: Providing less than operator for one element of a pair What would be the most elegant way too fix the following code:
#include <vector>
#include <map>
#include <set>
using namespace std;

typedef map< int, int > row_t;
typedef vector< row_t > board_t;
typedef row_t::iterator area_t;

bool operator< ( area_t const& a, area_t const& b ) {
    return( a->first < b->first );
};

int main( int argc, char* argv[] )
{
    int row_num;
    area_t it;

    set< pair< int, area_t > > queue;
    queue.insert( make_pair( row_num, it ) ); // does not compile
};

One way to fix it is moving the definition of less< to
namespace std (I know,  you are not supposed to do it.)
namespace std {
    bool operator< ( area_t const& a, area_t const& b ) {
        return( a->first < b->first );
    };
};

Another obvious solution is defining less than< for
pair< int, area_t > but I'd like to avoid that and be
able to define the operator only for the one element
of the pair where it is not defined.

A: When you are implementing a comparator that implements some specific and/or fairly exotic comparison approach, it is better to use a named function or a function object instead of hijacking the operator < for that purpose. I'd say that the natural way to compare a std::pair object would be to use lexicographical comparison. Since your comparison is not lexicographical, taking over operator < might not be a good idea. Better implement a comparator class
typedef pair< int, area_t > Pair; // give it a more meaningful name

struct CompareFirstThroughSecond {
  bool operator ()(const Pair& p1, const Pair& p2) const {
    if (p1.first != p2.first) return p1.first < p2.first;
    return p1.second->first < p2.second->first;
  }
};

and use it with your container
std::set< Pair, CompareFirstThroughSecond > queue;

(I hope I deciphered your intent from your original code correctly).
You can also implement the above operator () method as a template method, thus making it usable with all std::pair-based types with an iterator as a second member. It might not make mich sense though, since your comparison is "exotic" enough.


text:
Q: Will a mixed-reality application and experience developed for Hololens 2 using Unity work on Oculus Quest as is? To allow sales people to meet clients in the COVID19 era without travelling, busienss wants to create a virtual meeting room .
The clients will get Oculus Quest as Hololens is hard to procure right now where as business wants to use Hololens on their end.
Will an application /experience created for Hololens using Unity work as is on Oculus Quest or does it make sense to have the same device on both end?
I am new to this area, so not sure if this question makes sense, but is it something like developing 2 versions of code, one for iOS and one or Android and using something like Xamarin to make the process easy ?
Does Unity have features to make applications compatible between Hololens and Oculus Quest ?

A: MRTK makes it easy to make multiplatform XR applications.
https://microsoft.github.io/MixedRealityToolkit-Unity/Documentation/GettingStartedWithTheMRTK.html
Unity will allow you to run most applications on both Windows on ARM (HoloLens 2) and Android (Quest).
MRTK even has hand tracking support on both platforms.
https://microsoft.github.io/MixedRealityToolkit-Unity/Documentation/CrossPlatform/OculusQuestMRTK.html


text:
Q: Closing (not killing) an Excel file automatically on schedule I have an Excel (read-only) file that I need to close (not kill) twice a day.
I can kill the job by using taskill, but when I restart excel to display the file I get 'Document Recovery' message that takes valuable viewing from the screen.
I left a lot out of the actual process, but I hope this is enough to get my point across.


text:
Q: Program that does a screen print every 15 minutes and saves it to a file I remember hearing of some software that would take a screen print every 15 minutes and store it in a file. They mentioned it can be used to keep track of the amount of time you spent on a project.
I know of SnagIt. http://www.techsmith.com/screen-capture.asp
What are some of the other packages out there?

A: You haven't specified operating system so on linux I'd add this to my crontab:
*/15 * * * * scrot

Assuming scrot was installed.

A: AutoScreenShot:

A: One of the so many software that can do that.
http://www.softpedia.com/get/Multimedia/Graphic/Graphic-Capture/Automatic-Print-Screen-With-Email.shtml

A: TimeSnapper and Irfanview are nice, but they are missing a key feature: stop capturing when the computer is locked. It's pretty annoying to have thousands of screenshots of "Press Ctrl+Alt+Del to login". Using the free nircmd tool from Task Scheduler can resolve that. You need to create two tasks:
Screen Capture Task

*

*Triggers

*

*At logon

*On workstation unlock

*Actions (assuming a screenshot every 5 minutes)

*

*nircmd execmd md C:\Snapshots\~$currdate.yyyy.MM.dd$

*nircmd loop -1 300000 savescreenshot C:\Snapshots\~$currdate.yyyy.MM.dd$\~$currdate.yyyy.MM.dd$-~$currtime.HH_mm_ss$.png
Screen Capture - Stop on Unlock

*

*Trigger: On workstation unlock

*Action: taskkill /IM nircmd.exe /F
It's not perfect because if you have NirCmd running in the background for other reasons, the "Stop on Unlock" task might kill it instead, but I reckon this won't be the case for the vast majority of users.

A: TimeSnapper:

The Automatic Screenshot Journal
TimeSnapper runs in the background of
  your computer, taking screenshots of
  your desktop every few seconds all
  week long.
Where did all my time go?TimeSnapper lets you
  play back your week just like a movie.
  You can play it at any speed you like,
  and jump in at any time you like.
When it's time to fill out that
  dreaded timesheet, TimeSnapper is a
  savior. No need to tear your hair out
  trying to remember where all the time
  went.

A: REFOG is one that is free, and it has the ability to record anything else