WCF Service method synchronous/async

Question: I have a problem with calling WCF Service methods with Silverlight 3.
private bool usr_OK = false;

clientService.CheckUserMailAsync(this.mailTF.Text);

if (usr_OK == true)
{ isValidationOK = true; }
else { isValidationOK = false; MessageBox.Show("User already exists.", "User registered succes!", MessageBoxButton.OK); }

CheckUserMail should change usr_OK parameter. However it runs in other thread and it does not change the usr_OK param before IF block begins. I've tried thread.join byt the application freezed and i do not know what to do else. Please help me...how can i wait for WCF method to return param usr_OK.
Answer: The most direct answer to your question:  Don't block on WCF calls.  They make it hard for a reason.  There, quite likely, is no way to block if you even tried... but don't.
Elaboration: The mode of operation for Silverlight is Asyncronicity.  This is something you have to get used to when you are developing in Silverlight.  They make it really hard for you to block on anything.
This is a good thing, in my opinion.  When you block on the result of something like a WCF service call, you are ultimately blocking the user thread.  It does require some getting used to on the developer's part, but again... get used to it.
Lets say you have code that you want to go like this (Synchronous) :
var theResult = clientService.DoSomething(foo);
Process(theResult);

The way to re-write it would be like this (Asynchronous) :
clientService.DoSomethingCompleted += (sender, args) => Process(args.Result);
clientService.DoSomethingAsync(foo);

Taking it a step further, I like to abstract my services out as interfaces (so I can replace them when testing, or running in stand-alone mode while developing).  I take that as an opportunity to create an interface that looks like this:
public interface IMyService
{
    void DoSomething(string input, Action<string> whenComplete);
}

I implement the service like the async code above, and then when I call it, it is very clean and simple:
myService.DoSomething(foo, Process);

You will find that much of your system will morph into an asynchronous code base, but it might require you to re-adjust your expectations.
Answer: Bind the code that checks the usr_OK variable in the event handler for CheckUserMailCompletedEvent
clientService.CheckUserMailCompleted += new EventHandler<CheckUserMailCompletedEventArgs> (clientService_CheckUserMailCompleted);
clientService.CheckUserMailAsync(this.mailTF.Text);

void clientService_CheckUserMailCompleted(object sender, CheckUserMailCompletedEventArgs e) {
    if (usr_OK == true) {
        isValidationOK = true;
    }
    else {
        isValidationOK = false;
        MessageBox.Show("User already exists.", "User registered success!", MessageBoxButton.OK);
    }
}

Comment: OK...that will work. But is there a way to wait for method to end. Threads does not seam to work.
Comment: I would like to use private AutoResetEvent m_autoResetEvent = new AutoResetEvent(false);
Comment: This is how silverlight works. There is no support for synchronous web service calls by design.

WCF Service method synchronous/async


Can anyone explain part of this opencv code to me?

Question: The original code is here
It's an opencv program used to track hand gestures I'm trying to figure out why the creator of this code needed the c_lower and c_upper arrays
It's too much code to post, I'm mainly wondering if there's someone on here who has used this code before who understands in better than me.
I wondering why he did this:
void produceBinaries(MyImage *m) {
    Scalar lowerBound;
    Scalar upperBound;
    for (int i = 0; i<NSAMPLES; i++) {
        normalizeColors(m);
        lowerBound = Scalar(avgColor[i][0] - c_lower[i][0], avgColor[i][1] - c_lower[i][1], avgColor[i][2] - c_lower[i][2]);
        upperBound = Scalar(avgColor[i][0] + c_upper[i][0], avgColor[i][1] + c_upper[i][1], avgColor[i][2] + c_upper[i][2]);
        m->bwList.push_back(Mat(m->srcLR.rows, m->srcLR.cols, CV_8U));
        inRange(m->srcLR, lowerBound, upperBound, m->bwList[i]);
    }
    m->bwList[0].copyTo(m->bw);
    for (int i = 1; i<NSAMPLES; i++) {
        m->bw += m->bwList[i];
    }
    medianBlur(m->bw, m->bw, 7);
}

Instead of this
void produceBinaries(MyImage *m) {
    Scalar lowerBound;
    Scalar upperBound;
    for (int i = 0; i<NSAMPLES; i++) {
        normalizeColors(m);
        lowerBound = Scalar(avgColor[i][0] - 20, avgColor[i][1] - 20, avgColor[i][2] - 20);
        upperBound = Scalar(avgColor[i][0] + 20, avgColor[i][1] + 20, avgColor[i][2] + 20);
        m->bwList.push_back(Mat(m->srcLR.rows, m->srcLR.cols, CV_8U));
        inRange(m->srcLR, lowerBound, upperBound, m->bwList[i]);
    }
    m->bwList[0].copyTo(m->bw);
    for (int i = 1; i<NSAMPLES; i++) {
        m->bw += m->bwList[i];
    }
    medianBlur(m->bw, m->bw, 7);
}

This code can be found here
Why would he need separate values of c_lower and c_upper for hue, saturation, and value? Why not pick an arbitrary number like 20?
If anyone could be of any help that would be great, the guy hasn't posted anything about this code in years so I don't expect him to reply to me.
Comment: Maybe because he didn't want to have magic numbers in his code?
Comment: @MikeMB then where do his numbers come from?
Comment: As I'm not familiar with this code and you don't even link to the file, where that code comes from I don't know, but your IDE should tell you. Maybe they are the result of a calibration process.
Answer: Because these bounds are controlled by user in GUI and not hardcoded in the code. They are set to initial values in initTrackbars to be controlled later using trackbars (a kind of sliders).


Comparison of dual function breakers brands

Question: This is a follow up to this breaker and panel selection question.
Apparently, there are gfci  failures, and differences between outlet and breaker protection. In particular, gfci breakers are not required to have the same (as much) functionality as gfci outlets.
So! Is there any documented comparison, between the different brands (Siemens, Eaton, Schneider,...), of  the quality/implemented functionality of arc, ground, and dual function, fault breakers? I have not seen any, but...
Comment: What type of panel will you be putting these in?  It matters.
Comment: @Harper I'm in much the same situation as the person in the first post. I am changing the load center anyway, and  am 'free' to choose whichever load center (and corresponding breakers) I want.
Answer: The only "documented" comparisons you will find will come from the manufacturers themselves comparing their products against the others, the value of which becomes immediately suspect. For the most part, UL listing dictates that they all follow the same basic rule and pass the same tests. Everything after that is opinion and people's opinions tend to be formed by their personal experiences. I have installed all of the major manufacturer's products and quite honestly, there isn't a hair's width difference in them in them from a hardware standpoint. The biggest differences come in the form of availability in your area and customer service, which will also vary by location. I would ask around at your available suppliers as to what they carry in stock then ask neighbors about their experiences in terms of customer service.
In my opinion the article on differences between GFCI breakers and GFCI receptacles is a little disingenuous. They refer to breakers not having to meet the same requirements, but then go on to say that one of those is the "line to load reversal" test. Swapping line and load is something that is impossible to do on a plug-in breaker! They also go on about the possible failure modes, but a breaker is ALREADY a disconnecting device, so there is no need to do a redundant test on its ability to disconnect.
Comment: Thanks for your answer, and certainly I should have noticed (on my own) your breaker/receptacle observation...BTW,  I noticed afterwards https://diy.stackexchange.com/questions/150771/siemens-spring-clip-and-bus-bar-not-compatible?rq=1 which mentions, cough, a 'hair's width' difference... FWIW, we are replacing an ITE panel, so my inclination was to use Siemens.
Comment: ITE is Siemens now (since 1983), there is no difference. For the most part, Siemens has not changed anything substantial from the original ITE designs, most of the part numbers are even still the same..
Comment: Again, thank you for your time. I gather you're not inclined to take to heart the worry expressed in the link of the Siemens GFCI breaker not fitting properly on the stab?


Visual Studio 2008 Publish fails, can't load dll (envdte.dll)

Question: I started to get this error after I had installed and uninstalled various MS SDKs
Error: Publish failed with the following error: Unable to cast COM object of type 'System.__ComObject' to interface type 'EnvDTE.Project'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{866311E6-C887-4143-9833-645F5B93F6F1}' failed due to the following error: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)).
Even reinstalling the SDKs didn't fix the problem.
I finally found the answer to the problem, which I'll post as an answer.
Answer: I opened 'cmd' with Administrator privileges, and did
<code>cd C:\Program Files (x86)\Common Files\microsoft shared\MSEnv
regsvr32 dte80.olb
regsvr32 dte80a.olb
regsvr32 dte90.olb
regsvr32 dte90a.olb
</code>
and things magically worked after that.
Comment: didn't work for me bro. I'm storing project names and ENVDTE.Project in a hashtable. When I try to find Project from hashtable, im getting the same type conversion problem with Exception from HRESULT: 0x80004002 (E_NOINTERFACE)


Does it follow that two finite positive measures are the same?

Question: Suppose $\mu$ and $\nu$ are finite positive measures on the Borel $\sigma$-algebra on $[0, 1]$ such that $\int f\,d\mu = \int f\,d\nu$ whenever $f$ is real-valued and continuous on $[0, 1]$. Does it follow that $\mu = \nu$?
Answer: Yes, it's true that $\mu=\nu$. First, recall that if two finite Borel measures satisfy $\mu([a,b])=\nu([a,b])$ for all closed intervals $[a,b]\subset [0,1]$, then $\mu=\nu$. This is because the set of closed intervals $[a,b]\subset [0,1]$ is a $\pi$-system which generates the Borel $\sigma$-algebra on $[0,1]$.
So fix an interval $[a,b]\subset [0,1]$, and choose a sequence of continuous functions $f_n(x)$ which decrease to $1_{[a,b]}$. Then by the monotone convergence theorem,
$$ \mu([a,b])=\lim_{n\to\infty}\int f_n\;d\mu=\lim_{n\to\infty}\int f_n\;d\nu=\nu([a,b]) $$
as desired.
Comment: The indicator of $[a,b]$ is *upper* semi-continuous, so it's possible to find a *decreasing* sequence of continuous functions converging pointwise to $1_{[a,b]}$. Monotone convergence still applies.
Comment: @JohnDawkins: good point. I suppose I could also have picked open intervals.
Comment: You could take $f_n(x) = 1 - d(x,[a,b])^n$ for example.


Oracle database: Group tables in folders, like Postgres Schemas?

Question: is there a way to group tables into Postgres's schema like structure? We have a Postgresql server we want to move to Oracle DB. We use a lot of schemas to categorize tables. Anything Similar in oracle?  Oracle has Schemas but there is a one to one relation between schema and a user. Schema == User.
Is there another stack-exchange that might be more appropriate for this question?
Comment: What *exactly* is the problem here? What is it that you know how to do in Postgres that you don't in Oracle? So what if in Oracle you get every schema has a "user"? A "user" doesn't have any privileges unless specifically granted. There's no penalty that I can see.
Comment: Oracle users can access objects in any number of schemas, granted the proper permissions.
Comment: Accessing is no issue. But for creating 10 schemas, we need to create 10 users of that schema name... In postgresql we have a script that runs a test, stores the results and creates a new schema containing views pointing to the results. In oracle we'd have to create a new user everytime, like User Test_7889
Comment: Creating a user sounds processing overhead. But from your answer I assume that overhead is negligible.
Comment: Creating a user IS creating a schema in Oracle. There's no processing overhead because they're one and the same thing.
Comment: A few years ago I had to do that with Oracle 10g and it turned out to be quite hard/unpleasant. The reason IIRC was there was no way to say "userA can create objects in  userB's schema", unless userA had very high privileges, like create anything anywhere, as opposed to only in userB. If you need only DML, it may be no problem. If you need DDL, be aware of this and check the oracle docs for your specific version.
Answer: You will need to create the same amount of schemas in Oracle as you did in PostgreSQL. The fact that each schema is also associated with a user should not bother you.
You don't have to log-in with all those users if that's what you are wondering.
Just create one "application" user, and grant the necessary privileges on the tables you create in the various schemas to that application user.
If you used PostgreSQL's search path feature to avoid fully qualified table names, then you'll need to create synonyms (owned by the "applicatoin" user) that point to the tables in the various schemas.
Comment: Now I have a followup question...

Is there a php or web based interface available in Oracle. We rely heavly on phppgmyadmin (same as phpmyadmin for mySQL).
Comment: SquirrelSQL isn't web-based.  But it's Java, and runs on my Macs, Windows machines, and Linux machines, and talks to any database that you have a JDBC driver for.   It does require that it be installed on the local machine; however, the only complicated part of the install is setting up the JDBC driver.
Comment: @nulltorpedo Oracle Enterprise Manager is the main administrative interface for Oracle and is Web-based. It is integral part of the Oracle installation.


Aggregate and $ne Not Working as Expected

Question: I'm trying the aggregation below, but do not appear to be getting the expected result using $ne and null.
I have tried other solutions like using a combination of $cond, $not, and $eq to no avail.  Using $gt:[ "$unloadeddate", null] seems to give some results, but that does not seem to be proper syntax and I am concerned it's not trustworthy to run properly over entire dataset.
Also, querying as follows:
db.getCollection('esInvoices').find({"esBlendTickets.loadeddate":{$ne:null}})

... returns results so not sure why the same query in the aggregate function not working.
Any help is appreciated!!
The first part works...
"unloadeddate": { "$switch": {
        branches:[ {
            case: {
                "$ne":[ "$esBlendTickets.ticketdate", null]
            },
            then: "$esBlendTickets.ticketdate"
        }, {
            case: {
                "$ne":[ "$esDeliveryTickets.ticketdate", null]
            },
            then: "$esDeliveryTickets.ticketdate"
        }],
        default: null
    }
},
"loadeddate": { "$switch": {
        branches:[ {
            case: {
                "$ne":[ "$esBlendTickets.loadeddate", null]
            },
            then: "$esBlendTickets.loadeddate"
        }, {
            case: {
                "$ne":[ "$esDeliveryTickets.loadeddate", null]
            },
            then: "$esDeliveryTickets.loadeddate"
        }],
        default: null
    }
},

... but this second part (essentially the same logic except for the resulting value) does not work as expected...
"stagename": { "$switch": {
        branches:[ {
            case: {
                "$ne":[ "$esDeliveryTickets.ticketdate", null]
            },
            then: "Invoiced"
        }, {
            case: {
                "$ne":[ "$esBlendTickets.ticketdate", null]
            },
            then: "Invoiced"
        }],
        default: "Invoiced-Only"
    }
}

Complete Aggregation:
db.esInvoices.aggregate([ {
    $addFields: {
        // A single invoice will not have both a blend ticket and delivery ticket associated so looping tough each case should work.
        "unloadeddate": { "$switch": {
                branches:[ {
                    case: {
                        "$ne":[ "$esBlendTickets.ticketdate", null]
                    },
                    then: "$esBlendTickets.ticketdate"
                }, {
                    case: {
                        "$ne":[ "$esDeliveryTickets.ticketdate", null]
                    },
                    then: "$esDeliveryTickets.ticketdate"
                }],
                default: null
            }
        },
        "loadeddate": { "$switch": {
                branches:[ {
                    case: {
                        "$ne":[ "$esBlendTickets.loadeddate", null]
                    },
                    then: "$esBlendTickets.loadeddate"
                }, {
                    case: {
                        "$ne":[ "$esDeliveryTickets.loadeddate", null]
                    },
                    then: "$esDeliveryTickets.loadeddate"
                }],
                default: null
            }
        },
        "stagedate": "$InvoiceHeader.InvDate",
        "stagename": { "$switch": {
                branches:[ {
                    case: {
                        "$ne":[ "$esDeliveryTickets.ticketdate", null]
                    },
                    then: "Invoiced"
                }, {
                    case: {
                        "$ne":[ "$esBlendTickets.ticketdate", null]
                    },
                    then: "Invoiced"
                }],
                default: "Invoiced-Only"
            }
        }
    }}])

Comment: So if all your variations of "code" do not work for you, then perhaps you might consider showing over people some "data" and see what they come up with. We don't need to see every single thing you tried. Just and attempt, some data to relate that to and an expected result which can be obtained from the presented data. Almost certainly someone will then see what you mean to do and show you a solution.
Answer: Think I just ran into the same problem you were having. Using Mongo 3.4 at the moment. From what I can tell the query $ne behaves differently from the aggregate $ne when you are comparing it to null. Threw me off for a little bit.
Specifically, a { $ne: [ '$field', null ] } predicate in the aggregate pipeline will return true when $field is undefined.
However, when using queries (not $aggregate), the { field: { $ne: null } predicate will return false for those same documents when $field is undefined.
My work-around was to use a $project with { field: { $ifNull: [ '$field': null ] } } in a prior step to turn undefined instances of that field into explicit nulls, which will then make the aggregate $ne work as I needed. For whatever reason, $ifNull works with null, undefined, and missing fields. Not sure why $ne is different.

Here's an example to reproduce.
db.test.insertMany([
    { a: 1, b: 'string' },
    { a: 2, b: null },
    { a: 3 },
])

db.test.find({ b: { $ne: null }}, { _id: 0 })
/*
returns:
{
    "a" : 1.0,
    "b" : "string"
}
*/

db.test.aggregate([
    { $project: {
        _id: 0,
        a: 1,
        b: 1,
        switched: { $switch: {
            branches: [
                { case: { $ne: [ '$b', null ] }, then: 'cased' },
            ],
            default: 'default',
        }}

    }}
])
/*
returns:
{
    "a" : 1.0,
    "b" : "string",
    "switched" : "cased"
},
{
    "a" : 2.0,
    "b" : null,
    "switched" : "default"
},
{
    "a" : 3.0,
    "switched" : "cased" <--
}
*/

Answer: The problem is missing fields are undefined while null fields are, well, nulls. When you write "$ne":[ "$esDeliveryTickets.ticketdate", null] you don't filter the former but only the latter.
But undefined is "smaller" than null. In order to filter them both you just need to make lte/gt instead of eq/ne. So this query returns all existing values:
See example:
db.test.insertOne(
{
    "a" : 10,
    "b" : null
})

...

db.getCollection('mytest').find(    {},
    {
        "a" : { $lte : ["$a", null] },
        "b" : { $lte : ["$b", null] },
        "c" : { $lte : ["$c", null] },
    })

// {
//    "_id" : ObjectId("606724f38ec4d26b981b5a1c"),
//    "a" : false,
//    "b" : true,
//    "c" : true
// }

In your case:
"stagename": { "$switch": {
        branches:[ {
            case: {
                "$gt":[ "$esDeliveryTickets.ticketdate", null]
            },
            then: "Invoiced"
        }, {
            case: {
                "$gt":[ "$esBlendTickets.ticketdate", null]
            },
            then: "Invoiced"
        }],
        default: "Invoiced-Only"
    }
}

and this one returns only missing (or null) values:
"stagename": { "$switch": {
        branches:[ {
            case: {
                "$lte":[ "$esDeliveryTickets.ticketdate", null]
            },
            then: "Invoiced"
        }, {
            case: {
                "$lte":[ "$esBlendTickets.ticketdate", null]
            },
            then: "Invoiced"
        }],
        default: "Invoiced-Only"
    }
}


How to parse a Google Drive File list object

Question: I am using PHP and the Google Drive API and need to get the fileId of all the files in the returned object.
Here is my Code :
<code>  $result = array();
        $files = array();
        $pageToken = NULL;
        try {
            $parameters = array();
            $parameters['pageToken'] = $pageToken;
            $parameters['q'] = "trashed=false and title contains '".$folderName."'";
            $files = $this->service->files->listFiles($parameters);
            $result = array_merge($result, $files->getItems());
            $pageToken = $files->getNextPageToken();
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
            $pageToken = NULL;
        }

        print_r($result);
</code>
How do I get the fileId of all the files in the $result variable?
Answer: Just do :
<code>foreach($files->items as $item)
{
   echo $item['id'];
}
</code>


Android Media Player

Question: I do simple small programs in android for my practice. While I am on the way to create a simple player app, I had to face an error which I could not solve.The following is my code.
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class AndrmusiActivity extends Activity {
    /** Called when the activity is first created. */
    public MediaPlayer playr;
    public Button b1;
    public Button b2;
    public Button b3;
    @Override
    public void onCreate(Bundle State) {
        super.onCreate(State);
        setContentView(R.layout.main);
        b1= (Button)findViewById(R.id.play);
        b1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            playr = MediaPlayer.create(this,R.raw.showme);
            playr.start();

            }
        });
        b2= (Button)findViewById(R.id.Pause);
        b2.setOnClickListener(new OnClickListener() {
            public void onClick(View v1) {
                playr.pause();
            }
        });
        b3=(Button)findViewById(R.id.Stop);
        b3.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                playr.stop();
                playr.reset();

            }
        });

    }
}

Now I faced the error at play method at the line
playr = MediaPlayer.create(this,R.raw.showme);

Could any one please help me in this aspect.
Thanks in adv
Comment: this refers to the clicklistener, use a class reference or any Activity based method e.g. getBaseContext instead of this.
Comment: use classname.this or use getapplicationcontext().
Comment: you have to pass the Activity.class in which you want to run it like       playr = MediaPlayer.create(CurrentActivity.class,R.raw.song);
Answer: Use this line there
 playr = MediaPlayer.create(AndrmusiActivity.this,R.raw.showme);

If error remains post your error logcat.
create this in your on create() method.
 playr = MediaPlayer.create(this,R.raw.showme);

For resume()
use your your code as same as below.
b1 = (Button) findViewById(R.id.play);
b1.setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
             playr.start();
         }
     });

Calling start() to resume playback for a paused MediaPlayer object, and the resumed playback position is the same as where it was paused. When the call to start() returns, the paused MediaPlayer object goes back to the Started state.
http://developer.android.com/reference/android/media/MediaPlayer.html#start()
Comment: I had got the required functionality.But i am unable to give the resume option to the player when pause is pressed.i.e.,  the audio file starts playing from the first when I click the play button after clicking the pause.. Please some one help m,e to clear it.
Comment: @BharathGupta you need to change the button image dynamically while playing and pause.
Comment: @ Padma Kumar thanks a ton, I had done well with your suggestion and could you please tell me a solution for the following problem faced by me. When I navigate to other app and come back to this and click on the options, its giving ma a prompt Force close.
Comment: just post your error log so that only I can know whats your problem. email@example.com
Answer: Replace
playr = MediaPlayer.create(this,R.raw.showme);

with
playr = MediaPlayer.create(AndrmusiActivity.this,R.raw.showme);

Answer: use this code to create mediaplayer context
 playr = MediaPlayer.create(getBaseContext(),R.raw.showme);

Answer: This is my activity example to play videos in Android using VideoView:
package br.com.player;

import android.support.v7.app.AppCompatActivity;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.VideoView;

public class PlayerActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.player);

        Button buttonPlayVideo = (Button)findViewById(R.id.playvideobuttom);

        getWindow().setFormat(PixelFormat.UNKNOWN);

        VideoView mVideoView = (VideoView)findViewById(R.id.videoview);

        buttonPlayVideo.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View v) {

                    VideoView mVideoView = (VideoView)findViewById(R.id.videoview);

                    String uriPath = "android.resource://br.com.player/"+R.raw.filevideo;

                    Uri uri = Uri.parse(uriPath);
                    mVideoView.setVideoURI(uri);
                    mVideoView.requestFocus();
                    mVideoView.start();

            }});
     }
}

And this is activity's xml player.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

  <Button
    android:id="@+id/playvideobuttom"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Play Video"
    />

   <VideoView
    android:id="@+id/videoview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />

</LinearLayout>

Android Media Player


Why the number of frame rate of topic is differnet from realsense image fps in ROS2

Question: I tested if my ros2 node was subscribing exactly to /camera/depth/image_rect_raw topic from reassense ROS2 node.I attatched a realsense camera to TX2 board and  configured as 15 fps.
However, I expected that the rate of subscribing /camera/depth/image_rect_raw should be similar to 15 hz but it is different as below. Why is there the rate difference between publising and subscribing image topic? Is it possible to match the subscribing rate to publishing rate?
$ ros2 topic hz /camera/depth/image_rect_raw
average rate: 10.798
min: 0.040s max: 0.144s std dev: 0.03146s window: 13

average rate: 8.610
min: 0.040s max: 0.357s std dev: 0.06849s window: 22

average rate: 8.085
min: 0.040s max: 0.357s std dev: 0.07445s window: 30

average rate: 9.498
min: 0.015s max: 0.357s std dev: 0.06742s window: 45

average rate: 9.552
min: 0.015s max: 0.415s std dev: 0.07555s window: 55

average rate: 9.265
min: 0.015s max: 0.415s std dev: 0.07543s window: 63

average rate: 8.510
min: 0.015s max: 0.415s std dev: 0.08619s window: 68

average rate: 7.940
min: 0.015s max: 0.480s std dev: 0.09757s window: 73

average rate: 7.539
min: 0.015s max: 0.480s std dev: 0.10456s window: 77

average rate: 7.750
min: 0.015s max: 0.480s std dev: 0.09972s window: 87

Answer: It is likely that the difference is due to the transport delay of putting the image into the network. The significance of this delay depends on whether your subscriber is running on the Jetson or if it is on a separate device on the same physical network. Regardless, I would suggest changing the default QoS policies to get better performance for video streaming such as setting RELIABILITY=BEST_EFFORT. That said the biggest improvement (if you are streaming over a network) will likely come from using the image_transport_plugins to compress the images before they are published. Although these are CPU based (theora, etc.) they will likely help.
Another thing to consider is using the compression hardware accelerators that are built into the Jetson though that will require some more work until the maintainers of image_transport_plugins or another enterprising developer gets this working.


What's the best way to create empty/default rows for missing aggregations

Question: I have a table I want to group over two levels. As the output, I need all the grouping value combinations, such that I end up with zeros where non existant combinations occur. For example, say I have this table:
+------+------+
| user | page |
+------+------+
| a    |    1 |
| a    |    1 |
| a    |    2 |
| b    |    2 |
| b    |    3 |
+------+------+

I'm after output like this:
+------+------+--------+
| user | page | visits |
+------+------+--------+
| a    |    1 |      2 |
| a    |    2 |      1 |
| a    |    3 |      0 |
| b    |    1 |      0 |
| b    |    2 |      1 |
| b    |    3 |      1 |
+------+------+--------+

I can achieve this with the following query, but it seems rather heavy handed:
WITH
    users AS (SELECT distinct(user) FROM sometable),
    pages AS (SELECT distinct(page) FROM sometable),
    users_pages_empty AS (SELECT * FROM users CROSS JOIN pages),
    users_pages_full AS (SELECT user, page, count(*) as visits FROM sometable GROUP BY user, page)
SELECT e.user, e.page, coalesce(f.visits, 0) as visits
FROM users_pages_empty e
LEFT JOIN users_pages_full f ON e.user=f.user AND e.page=f.page

I happen to be using AWS Athena, but I think this is more a generic SQL question than an Athena question.
The performance of this query is fine, it's more the readability/complexity I'm not happy with.
Answer: Use a cross join to generate the rows and a left join to bring in the existing rows and aggregate:
select u.user, p.page, count(s.user)
from (select distinct user from sometable) u cross join
     (select distinct page from sometable) p left join
     sometable s
     on s.user = u.user and s.page = p.page
group by u.user, p.page
order by u.user, p.page;


add "data-id" to  datatables.js

Question: It's possible to do this :
The data that I want to enter I get a method implemented from a servlet using json, which goes perfectly.
The problem is that I want to add to the last  a variable "data-id"
$('#tbl_bienSeleccionado').DataTable({
            destroy: true,
            "columnDefs": [
                {"className": "text-center", "targets": "_all"}
            ],
            "aaData": res.lista,
            "columns": [
                {"data": "idbien"},
                {"data": "nombre"},
                {"data": "description"},
                {"data": "persona"},
                {"data": "ubicacion"},
                {"data": "estado"},
                {"data": "departamento"},
                {"data": "idbien", "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                    $(nTd).html("");
                }
            ]
});

I need add: js data-id='res.lista.idbien' into td → result  html:

Comment: Have you tried $(nTd).data('id', '123' )?
Answer: You can try something like this. There is a row call back function. You can insert a html to the  8th column like this.
var edithtml = '' +
                  '' +
        ''+
    '' +
'	'

$('#tbl_bienSeleccionado').DataTable({
            destroy: true,
            "columnDefs": [
                {"className": "text-center", "targets": "_all"}
            ],
            "aaData": res.lista,
            "columns": [
                {"data": "idbien"},
                {"data": "nombre"},
                {"data": "description"},
                {"data": "persona"},
                {"data": "ubicacion"},
                {"data": "estado"},
                {"data": "departamento"}
            ],
          "fnRowCallback": function (nRow, data)
           {
                var id = data[0]; // 1st column in single row array
                var replacedEditHtml = edithtml.replace("{id}", id);
                $("td:eq(8)", nRow).html(replacedEditHtml); //replace 8th column
});

Comment: The jquery-datatables.js elements do not appear, as the search bar and the drop-down list of items to be displayed; that is to say a simple table appears.
And when I'm adding a function appear this error :TypeError: col is undefined. Thx
Answer:         $('#tbl_bienSeleccionado').DataTable({
            destroy: true,
            "columnDefs": [
                {"className": "text-center", "targets": "_all"}
            ],
            "aaData": res.lista,
            "columns": [
                {"data": "idbien"},
                {"data": "nombre"},
                {"data": "descripcion"},
                {"data": "persona"},
                {"data": "ubicacion"},
                {"data": "estado"},
                {"data": "departamento"},
                {
                    "data": null,
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        $(nTd).html("	");
                    }}
            ],
            createdRow: function (row, data, indice) {

                $(row).find("td:eq(7)").attr('data-id', data.idbien);
            }
        });

add "data-id" to  datatables.js


How to use Enzyme's mount using JEST

Question: Everytime I import mount from Enzyme and try and use it to mount one of my Components for testing, i get the following error: "It looks like you called mount() without a global document being loaded". What I want to know is, do I have to set up a "jest-setup.js" file or something similar and add jsdom as a global? Please advice. Have been searching the web for answers with no luck
Comment: I think this guide should help you https://github.com/airbnb/enzyme/blob/master/docs/guides/jsdom.md
Answer: Jest comes bundled with JSDOM, so you just need to make sure you run with testEnvironment: jsdom (which is the default).

How to use Enzyme's mount using JEST


Spring Data Solr : Unable to locate Attribute from Repository

Question: This was working fine until I manage to migrate to Spring Boot.
Before I was using version spring-data-solr version : 1.4.0.RELEASE and now Boot just got version 1.3.3.
I tried to remove the spring-boot-starter-data-solr and reset to static definition but I got the same issue..
UPDATE My current pom.xml :
 <project>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.2.5.RELEASE</version>
        </parent>
 <repositories>
        <repository>
            <id>excilys-release</id>
            <url>http://repository.excilys.com/content/repositories/releases</url>
        </repository>

        <repository>
            <id>repo2_maven_org</id>
            <url>http://repo2.maven.org/maven2</url>
        </repository>

        <repository>
            <id>maven-restlet</id>
            <url>http://maven.restlet.com</url>
        </repository>
    </repositories>
    <dependencies>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-websocket</artifactId>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-solr</artifactId>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>

            <dependency>
                <groupId>org.apache.solr</groupId>
                <artifactId>solr-core</artifactId>
                <version>4.10.0</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.slf4j</groupId>
                        <artifactId>slf4j-jdk14</artifactId>
                    </exclusion>
                    <exclusion>
                        <artifactId>log4j</artifactId>
                        <groupId>log4j</groupId>
                    </exclusion>
                </exclusions>
            </dependency>
    </project>

My current SolrConfig.java :
@Configuration
@EnableSolrRepositories(basePackages = "com.repository.solr")
@ComponentScan("com.repository.solr")
public class SolRConfig {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public static final String PROPERTY_SOLR_SERVER_CORE  = "solr.core";

    @Resource
    private Environment environment;
    @Resource OgcParameters ogcParameters;

    @Bean
    public SolrServer solrServer() {
        final OgcParameters.slr slr = ogcParameters.slr();
        if (!environment.containsProperty(PROPERTY_SOLR_SERVER_CORE)) {
            logger.warn("You are running on the default solr core, create or edit the application.properties to avoid this behaviour");
        }

        String solrHostWithCoreIfNecessary = slr.host()
                .concat(slr.core());

        return new HttpSolrServer(solrHostWithCoreIfNecessary);
    }

    @Bean
    public SolrOperations solrTemplate() throws ParserConfigurationException, SAXException, IOException {
        return new SolrTemplate(solrServer());
    }
}

My current SolrRepository.java :
@Repository
public interface DocumentSolrRepository extends SolrCrudRepository<Document, Long>, DocumentSolrRepositoryCustom {
    Set<Document> findByTextContaining(@Param("text") String test);
}

My current entity using @Field attribute binded to the SolrRepository field causes the server start fail :
@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
public class Document {

    private Long id;
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="DOCUMENT_SEQ")
    @SequenceGenerator(name="DOCUMENT_SEQ", sequenceName="DOCUMENT_SEQ")
    public Long getId() {
        return id;
    }
    public Document setId(Long id) {
        this.id = id;
        return this;
    }
    /* SOLR Specific Fields */
    @Field("text")
    private String text;
    @Transient @JsonIgnore
    public String getText() {
        return text;
    }
    public Document setText(String text) {
        this.text = text;
        return this;
    }
}

The error log stacktrace :
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicantController': Injection of resource dependencies failed;

Caused by: java.lang.IllegalArgumentException: Unable to locate Attribute  with the the given name [text] on this ManagedType [com.entity.Document]
    at org.hibernate.jpa.internal.metamodel.AbstractManagedType.checkNotNull(AbstractManagedType.java:144)
    at org.hibernate.jpa.internal.metamodel.AbstractManagedType.getAttribute(AbstractManagedType.java:130)
    at org.springframework.data.jpa.repository.query.QueryUtils.toExpressionRecursively(QueryUtils.java:475)
    at org.springframework.data.jpa.repository.query.JpaQueryCreator$PredicateBuilder.build(JpaQueryCreator.java:199)
    at org.springframework.data.jpa.repository.query.JpaQueryCreator.toPredicate(JpaQueryCreator.java:146)
    at org.springframework.data.jpa.repository.query.JpaQueryCreator.create(JpaQueryCreator.java:86)
    at org.springframework.data.jpa.repository.query.JpaQueryCreator.create(JpaQueryCreator.java:44)
    at org.springframework.data.repository.query.parser.AbstractQueryCreator.createCriteria(AbstractQueryCreator.java:109)
    at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:88)
    at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:73)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$QueryPreparer.<init>(PartTreeJpaQuery.java:110)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$CountQueryPreparer.<init>(PartTreeJpaQuery.java:230)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:64)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:94)
    ... 68 more

Answer: You don't need to exclude or add any additional dependency. Instead you could simply define the version to be used by your spring-data projects using properties as follows:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
</parent>

<properties>
    <spring-data-releasetrain.version>Fowler-SR2</spring-data-releasetrain.version>
</properties>

<dependencies>
    ...
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-solr</artifactId>
    </dependency>
    ...
</dependencies>

Nothing else is needed. By the way, Fowler-SR2 was released 28.07 (its still hot).
Comment: defining this property didn't solve my issue.. I added extra elements in my post on my pom.xml (repositories definitions).. I currently need the Spring Solr extra dependencies so I can't only use Spring boot data solr package..
Comment: is this entity intended to be stored in using JPA and Solr? (Document seems to be a JPA `Entity` too)
Comment: additionally, `@Repository` isn't needed, `DocumentSolrRepository` by extending `SolrCrudRepository` is enough.


Webpack cannot resolve core-js paths on Windows

Question: Running webpack I receive the errors:
ERROR in ./node_modules/core-js/index.js
Module not found: Error: Can't resolve './es' in 'pathtoproject\node_modules\core-js'
 @ ./node_modules/core-js/index.js 1:0-15
 @ multi core-js whatwg-fetch ./src/contactForm.tsx

ERROR in ./node_modules/core-js/index.js
Module not found: Error: Can't resolve './internals/path' in 'pathtoproject\node_modules\core-js'
 @ ./node_modules/core-js/index.js 4:11-38
 @ multi core-js whatwg-fetch ./src/contactForm.tsx

ERROR in ./node_modules/core-js/index.js
Module not found: Error: Can't resolve './proposals' in 'pathtoproject\node_modules\core-js'
 @ ./node_modules/core-js/index.js 2:0-22
 @ multi core-js whatwg-fetch ./src/contactForm.tsx

ERROR in ./node_modules/core-js/index.js
Module not found: Error: Can't resolve './web' in 'pathtoproject\node_modules\core-js'
 @ ./node_modules/core-js/index.js 3:0-16
 @ multi core-js whatwg-fetch ./src/contactForm.tsx

The folders do exist though. I believe it's to do with Windows paths as when I change the core-js/index.js file to use path.resolve() instead of relative imports it does work. This is not the solution I want though as it requires altering the core-js module.
For reference here is my webpack.config.js
const path = require('path');

module.exports = {
    entry: ["core-js", "whatwg-fetch", "./src/contactForm.tsx"],

    output: {
        path: path.join(__dirname, "build/assets/js/"),
        filename: "contactForm.js"
    },

    mode: "production",

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx"]
    },

    module: {
        rules: [
            {
                test: /\.ts(x?)$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: "ts-loader"
                    }
                ]
            },
            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            {
                enforce: "pre",
                test: /\.js$/,
                loader: "source-map-loader"
            }
        ]
    },

    // When importing a module whose path matches one of the following, just
    // assume a corresponding global variable exists and use that instead.
    // This is important because it allows us to avoid bundling all of our
    // dependencies, which allows browsers to cache those libraries between builds.
    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    }
};

Any ideas of a fix would be greatly appreciated
Answer: Can you try to replace
output: {
    path: path.join(__dirname, "build/assets/js/"),
    filename: "contactForm.js"
},

with
output: {
    path: path.resolve(__dirname, "build/assets/js/"),
    filename: "contactForm.js"
},

Path join just concatenates the paths, resolve will treat paths as absolute ones.
You can also add context property as well:
module.exports = {
    context: path.resolve(__dirname),

    entry: ["core-js", "whatwg-fetch", "./src/contactForm.tsx"],

Comment: Sorry, this did not work. I thought it did as but I removed core-js as an entry point prior.
Answer: The reason for this was because I did not have javascript files as a resolvable extension in my webpack config.
...
resolve: {
        //modules: ['node_modules'],
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx"]
    },
...

Needed to be
...
resolve: {
        //modules: ['node_modules'],
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx", ".js"]
    },
...


Passing e:MouseEvent as an argument via setInterval

Question: So i have this function
capture_mc.buttonMode = true;
capture_mc.addEventListener(MouseEvent.CLICK,captureImage);

function captureImage(e:MouseEvent):void {
//lalalala

}

I want to call this function every 2 seconds (after mouse click event happens).
I tried using setInterval
setInterval(captureImage,2000,e:MouseEvent);

but it leads to following error
1084: Syntax error: expecting rightparen before colon.

What's wrong ?
And ya, i am new to AS.
Answer: First, since this is AS3 you should be using Timer and TimerEvent. I'll show you how in the example.
Now you'll need to separate your functions:
edit: I've updated this to be safer based on @(Juan Pablo Califano) suggestions. I would keep the same timer for ever if the amount of time isn't going to change.
// first param is milliseconds, second is repeat count (with 0 for infinite)
private var captureTimer:Timer = new Timer(2000, 0);
captureTimer.addEventListener(TimerEvent.TIMER, handleInterval);

function handleClick(event:MouseEvent):void
{
    // call here if you want the first capture to happen immediately
    captureImage();

    // start it
    captureTimer.start();
}

function handleInterval(event:TimerEvent):void
{
    captureImage();
}

function captureImage():void
{
    // lalalala
}

You can also stop the timer with captureTimer.stop() whenever you want.
Comment: +1. It would also be a good idea to check whether your timer is running at the top of `handleClick`, and perhaps bailing out if it's running (or reseting the timer if that makes sense given the context). This could be implemented with a simple boolean flag or checking if `captureTimer` is not null. Otherwise, you could end up with multiple timers running and you won't have a way to stop them (because you'd be losing the reference to the old ones when you assign a new `Timer` object to the `captureTimer` variable.
Answer: The problem is that you should use the parameterName:ParameterType syntax only when declaring formal parameters (or when declaring vars and consts). Meaning, this is valid only when you are defining a function:
function func(paramName:Type){
}

When you call the function, you don't have to put the type of the arguments.
So, your function call should look like this:
setInterval(captureImage,2000,e);


Why the bson java implementation uses 4 bytes inc field?

Question: In BSON Java implementation, an ObjectId is composed by 3 pieces (source code: http://grepcode.com/file/repo1.maven.org/maven2/org.mongodb/mongo-java-driver/2.9.0/org/bson/types/ObjectId.java#ObjectId.%3Cinit%3E%28int%2Cint%2Cint%29 ):
XXXX   XXXX          XXXX
-------------------------
time   machine&pid   inc

(each X represents a byte)
this is a bit different from what's described in document (doc: http://docs.mongodb.org/manual/core/object-id/ )
XXXX   XXX       XX    XXX
--------------------------
time   machine   pid   inc

(each X represents a byte)
Can anyone let me know why the java-driver didn't follow the spec?
Thanks!
Comment: Incidentally, Java's approach is better, because it gives 8 bits more randomness (since inc is initialized randomly).  The "machine/pid" thing does nothing but significantly increase the chances of a collision in a large cluster compared to simply using 12 bytes of randomness.
Answer: I will put this as answer since it is a bit long for a comment.
There are a couple of JIRA links to this:

https://jira.mongodb.org/browse/JAVA-81
https://jira.mongodb.org/browse/JAVA-337

The second acknowledges that the spec is different under Java however makes no reference as to why.
If I were to make a guess it could be due to the way the PID and machine id in Java works, it could be related to: https://jira.mongodb.org/browse/JAVA-586.
You may find your answer better on the Google Group: mongodb-user since the maintainers hang out there.
Comment: Thanks Sammaye, according to the JIRAs, it seems to be a known issue. I'm not able to access google group from China, would you please help me forward my question to the group? btw, my real question is [Hack ObjectId to indicate the object type](http://stackoverflow.com/questions/13769013/hack-objectid-to-indicate-the-object-type), can you please add some comments? Thanks~~~
Comment: I have forwarded it, hopefully there will be a response soon, I'll take a look at that other one but kristina does have the right idea.
Comment: There are historical reasons for the difference, but JAVA-337 is currently planned to be addressed in the 3.0 Java driver release (i.e. the ObjectIDs will conform to the spec).
Comment: @Stennie Can you the reason be stated? That is basically this question.
Comment: @Stennie Oh never mind it seems the JIRA has been updated talking about machine id
Comment: "Historical" means that's the way ObjectIDs have been generated in the Java driver and there are existing users relying on that implementation ;-).  If you look at the [BSON spec](http://bsonspec.org/#/specification) you will see there are a few subtypes for UUID used by older drivers.  In order to introduce the "correct" ObjectID spec to the Java driver there will likely have to be some support for the "Java legacy" ObjectID.  I expect the original intent of an ObjectID was to provide a reasonably unique primary key, rather than packing fields that drivers would then start parsing as data.
Comment: @Stennie aha awesome cheers, you should put that as an answer :)
Answer: I expect the original intent of an ObjectID was to generate a reasonably unique primary key, rather than packing fields that drivers would then start parsing as data.
As the MongoDB ecosystem has evolved, some developers have found it useful to interpret the ObjectID from multiple drivers as well as ensure consistency of generated IDs.
If you look at the BSON spec you will see there are a few subtypes for UUID used by older drivers, and various changes for interoperability.  For example, there is mention on PYTHON-387 of supporting "legacy" byte orders and endianness for the C# and Java drivers.
As per JAVA-337 in the MongoDB issue tracker, the Java driver's ObjectID inconsistency is planned to be addressed in the 3.0 Java driver release.
Answer: I cannot explain why they are different, but I can tell you that the Python driver generates object ids using the same approach that the Java one does:
https://github.com/mongodb/mongo-python-driver/blob/master/bson/objectid.py


How do I get to the Upper Level to Disable the Venting of the Hangar?

Question: I am about to attack Cerberus headquarters. EDI tells me to access a console in the upper level, but I don't see how to get there. And since it's time-critical I've already got a few mission overdue to this.
How do I access the console on the upper level?
Answer: There should be a ladder to the left side of the hanger, where a sniper will take up a defensive position when you're beginning your attack.

Going up the ladder will take you to the first control, and then you'll need to make your way through that room and around the upper level to the second control room to complete the process.


C++11: defining function on std::array

Question: std::array takes two template parameters:
typename T // the element type
size_t N // the size of the array

I want to define a function that takes a std::array as a parameter but only for a specific T, in this case char, but for any size array:
The below is malformed:
void f(array<char, size_t N> x) // ???
{
    cout << N;
}

int main()
{
    array<char, 42> A;

    f(A); // should print 42

    array<int, 42> B;

    f(B); // should not compile
}

What is the correct way to write this?
Answer: Use a template function:
template<size_t N> void f(array<char, N> x) {
}

Comment: will this deduce the N correctly `f(A)`? or will it need to be specified `f<42>(A)`?
Comment: @AndrewTomazos-Fathomling Yes, it will deduce it.
Answer: The N needs to be a static value. You can, e.g., make a template argument:
template <std::size_t N>
void f(std::array<char, N> x) {
    ...
}

In your example, I would still pass the argument by reference, though:
template <std::size_t N>
void f(std::array<char, N> const& x) {
    ...
}

C++11: defining function on std::array


Conditioning random variables

Question: I have two issues that seem to be related.
1) Suppose we have two random variables $A$ and $B$ that are conditioned by $X$. If we want to calculate $$ \frac{p(A, B | X)}{p(B | X)},$$ do we always need to use Bayes rule and get $p(A|X, B)$? Since both are conditioned on $X$, why can't we say $p(A|X)$?
2) Suppose $Y \sim \rm{Normal}(0,1)$. I think $\mathbb{E}[Y]$ is 0, but does it change the value if we calculate $\mathbb{E}[Y|Y]$, is it $\mathbb{E}[Y|Y] = Y$? I cannot understand why conditioning changes its expectation.
Comment: For #2, you may know that E[Y] has mean zero based on the distribution, but conditioning will change the expectation. If you know that $Y=c$ for some c, then of course, $E[Y|Y=c]=E[c]=c$. In a sense, it is trivial. Knowing that $Y=c$, you wouldn't expect Y to be zero any more.
Answer:
Starting with
$$ p\left(A\middle|B\right) = \dfrac{p\left(A,B\right)}{p\left(B\right)} $$
and conditioning everything on $X$ gives
$$ p\left(A\middle|B, X\right) = \dfrac{p\left(A,B\middle| X\right)}{p\left(B\middle| X\right)} $$
So $p\left(A\middle|X\right) \neq \dfrac{p\left(A,B\middle| X\right)}{p\left(B\middle| X\right)}$ in the same way that $ p\left(A\right) \neq \dfrac{p\left(A,B\right)}{p\left(B\right)} $.
For the particular case $\mathbb{E}\left[Y\middle|Y\right] = Y$, I like to reason about this as follows. If I gave you the value of $Y$ and asked what you expected the value of $Y$ to be, what would you answer? Well of course the expectation should be whatever the value I just gave you, which is $Y$.

Conditioning random variables


How do I keep drawer knobs from loosening over time?

Question: I see knobs like this on cabinets, dressers, and closet doors. They are held in place with a single wood screw.

Very often they are loose. I guess when we grab them we often impart a slight twist. Also, temperature and humidity changes cause the wood to swell and shrink. The system is biased towards unscrewing, so over time they loosen up.
My DIY instinct says that this is bad. That the screw will strip out the knob, or it will ream out the hole in the door. Well, it seems sloppy.
When I notice one, I give it a twist to tighten. Sometimes I put my finger over the screw head to hold it still. When it's really stiff, I might get out the multitool. Sometimes, in my enthusiasm, I strip out the knob. Doh!
What's the best way to deal with these things? For example:

Use handles that take two screws.
Put a washer under the head to distribute the load, then make them really tight.
Keep them all tight according to a schedule.
Only use knobs made of strong wood, and keep them tight.
Use knobs that take a machine screw instead of a wood screw.
Put wood glue in the screw hole.
Use door designs that don't need a handle.
Comment: I think you mean "machine screws" instead of "wood screws"?  All of the handles like that that I run into have been machine screws (small fine pitch thread rather than very coarse).
Comment: What do you do if the screw has reamed out the hole?
Answer: I'd recommend going with a metal knob that's held in place by a machine screw. They're going to cost more, but they won't get damaged from everyday use, and you don't have to worry about them stripping out. Most of the knobs in my house are metal and take machine screws. I do have to periodically re-tighten them though. Some Blue Loctite might take care of it, but I've never taken the time to address the issue.
Comment: Loctite is the way to go. I did this in our kitchen in a fit of pique and it fixed everything. Make sure the handle's wood is still in good condition first, however. (You can use superglue as a hack to firm up the wood if it's gotten squishy.)
Answer: I've used teflon tape, normally used by plumbers; on knobs when the threads are stripped. It can work pretty well. Just don't expect to remove the knob without a pair of strong wrenches.
Answer: I have knobs with machine screws (notably on bi-fold doors), and still have the same problem.  Personally I would recommend putting a dab of epoxy on the screw threads and screwing it into the knob.  Of course that will make it pretty difficult to remove them later though if you ever want to replace the hardware.
Comment: Most threadlockers like Loctite are removable with hand tools, with the exception of red Loctite - you need heat for that one.
Comment: I agree with Doresoom: Use the right tool for the job, keep some loctite around.
Answer: Put a lockwasher between the nut and a regular washer (inside the door). Or use a Locknut and a regular washer.
Comment: @IamSJ It's a lock washer, which prevents loosening. I've had the exact same problem with pressure cookers (we must have the same brand!). I think that the washer may be loosening for a few reasons... in my case, I'm pretty sure that expansion and contraction from cooking was the problem (which explains why the manufacurer used a lock washer). If you replace it, it should last a while before it starts to loosen again.
Comment: @IamSJ Other common issues with lock washers (and lock nuts) may be that the it didn't have enough "spring" in it to begin with (cheap materials), or it might have been loosened and tightened so many times now that it has lost it's "spring". Or it might be that the area above and below the washer have been worn smooth and slippery. Sometimes you can get some more life out of it by bending the washer (or opening it a little) and sanding/roughening the areas of contact (increasing the grip).
Comment: In the above picture, won't the washer #1 with uneven joint cause loosening issues? We have a pressure cooker whose handle is fixed with a machine screw along with a washer with uneven ends as shown in your picture. It avoids us to tighten the screw completely and loosens more often.
Answer: Ben Welborn's lock washers are nice. When things get problematic, I move on to Loctite Blue 242 Threadlocker. It's easier to deal with than dried on nail polish or epoxy.


Whats the name of this function?

Question: I read this function in an exercise. It looks quit familiar to me, however I do not know its name.

Whats the name of the $\rho_n$ function and who brought it up first?
Comment: it is connected with the $\beta$-function. In fact $1/\beta$. Have a look at http://en.wikipedia.org/wiki/Beta_function
Comment: I mean $\rho_n$
Answer: Here $\rho_{n}=B\left(\frac{1}{2},\frac{1}{2}n-1\right)^{-1}$. I
do not know a special name for it.

Whats the name of this function?


How to fix the issue of Civilization V not launching in "Direct X 10 & 11" mode

Question: I launch Civlization V from steam and the launcher appears, it gives me the option of Direct X 9, Direct X 10 & 11 or Windows 8 Touch Enabled Mode. I wish to run it in DX11 so I select that, the window then disappears then nothing happens. How can I launch it in DX11 mode?
Answer: I've just spent about 30 minutes seeking this solution but I finally figured it out. I know how frustrating it can be to find straightforward answers to problems and I don't want the time I spent figuring this out to be wasted. If I can help one person it is worth it. Anyways here is how I fixed it.
All you have to do is install this official version of DirectX from Microsoft. I don't know why but this solved my problem immediately.
Here is the link: http://www.microsoft.com/en-us/download/details.aspx?id=35
Have fun and enjoy


14.04 freezes during installation 'copying files'

Question: I'm installing ubuntu 14.04 on a machine which currently runs windows 8.
I selected the option to completely erase the hard drive and do a clean install of ubuntu. I also selected the options to download updates and install 3rd party software. Ubuntu ran fine off the usb, but now im trying to install it, it copies around 80% of the files, but then seems to freeze. I can still click through the features, and the task bar buttons seems responsive, but the cursor is stuck on the spinning mode and the loading bar hasn't moved for at least 15 mins.
Is it safe to reboot to try again?
Any help would be much appreciated
Comment: I tried reinstalling without selecting updates, and it sort of worked, but now it crashed (bug report and all) during 'retrieving files'.
Comment: Gonna try downloading 15.04 after my dinner
Comment: I created a new life usb with 15.04
Comment: Now install seemed to go fine, but it froze at 'downloading packages time left 30 seconds'
Comment: Retrying now. So far so good
Comment: Well, it installed, but froze when trying to restart. One hard reboot later, i'm getting black screens and buffer i/o errors everywhere. Yay!
Answer: Install it without selecting to install the updates during installation. You can also try again with the latest release Ubuntu 15.04.
Answer: Yeah, try again reboot, re-install if you get stuck again try burning it onto the USB again. (That was my issue first time I got ubuntu) I recommend using Refus.exe to burn it onto your USB.
Refus.exe: https://rufus.akeo.ie/
Comment: Dude he's using virtual machine


What is the type of those methods of Class java.util.ArrayList

Question: The methods of Class java.util.ArrayList:
public E set(int index, E anEntry)
public boolean add(E anEntry)
public E remove(int index).

What are those methods' types? My guess is too ridiculous to post here...
Comment: Do some research into [generics](http://docs.oracle.com/javase/tutorial/java/generics/)
Answer: List<String> list1 = new ArrayList<String>(); // E here is String

List<Integer> list2 = new ArrayList<Integer>(); // E in this case would be Integer

So E represents the type when you declare or instantiate the ArrayList. This is really helpful for compile time type check. Since you can not add any other type of object other than the one you created it with.
Example
List<String> list1 = new ArrayList<String>(); //if by mistake you try to add an
                 //Integer object, it will give you a compile time error.
list1.add(new Integer(2)); // compile time error

Read: http://docs.oracle.com/javase/tutorial/java/generics/why.html
Answer: It means exactly the same thing it would mean if there was a class called E.
set is a method that takes an int (called index), an E (called anEntry) and returns another E.
add is a method that takes an E (called anEntry) and returns a boolean.
remove is a method that takes an int (called index) and returns an E.
Now, in this case E isn't a class - it's what is called a type parameter. If you look at the first line of ArrayList you will see something like this:
public class ArrayList<E>

which declares E as a type parameter of ArrayList. When you're talking about an ArrayList<String>, E means String. When you're talking about an ArrayList<Integer>, E means Integer. In this way they are sort of similar to normal method parameters - if you have void x(int i), then when you call x(5), i contains 5. When you call x(42), i contains 42.
Answer:
E denotes the type of Object you stored in your ArrayList. For example it could be ArrayList of 'String', 'Integer' etc.
If you use ArrayList<String>, it returns String.
add() returns boolean type (true or false).
Answer: E in this context is referring to Generics.
In Object Oriented Programming, generic types are used to create classes that can handle any data type. That's a simple explanation and while generics are a pretty in depth topic that should give you a good enough overview.
http://docs.oracle.com/javase/tutorial/java/generics/


continuity and differentiability of function of two variables

Question: Let $f(x,y)$ be
$$f(x,y): \begin{cases} x & \text{for } y = 0\\ x-y^3\sin\left(\frac{1}{y}\right)& \text{for } y \neq 0\end{cases} $$
then check continuity and differentiability  at $(0,0)$.
Answer: $$
f(x,y) = x - y^3\sin(.) = x + o(x,y)
$$
because $$\lim_{(x,y)\to (0,0)}\frac {y^3\sin(.)}{\sqrt{x^2 + y^2}} =0$$

For continuity:
$$\lim_{(0,0)} f(x,y) = \lim_{(0,0)}x + \lim_{(0,0)}o(x,y) =0
$$
then $f$ is continunous in $(0,0)$.
For differentiability:
Now identify with the definition of the derivative:
$$
f(x,y) = f(0,0) + Df(0,0)\cdot(x,y) + o(x,y)
$$
gives you the result:
$f$ is diffrentiable in in $(0,0)$ and $Df(0,0)\cdot(x,y) = x$.
Comment: its not a home work question, and also i dont know what you have done in your soln. can you tell little bit more? i see that f(0,0) is 0. and $\lim_{x\to 0}\; f(x,y)$ = 0 along x axis and $\lim_{y\to 0}\; f(x,y)$ =0 along y axis, what else do we need for continuity
Comment: sorry, i don't know which concept are u using in ur soln.i was doing by approaching (0,0) along different paths, so i used x axis and y axis as two standard paths.
Comment: i  meant about continuity.
Comment: plz tell about usage of this: $f(x,y) = f(0,0) + Df(0,0)\cdot(x,y) + o(x,y)$  . which text explains this kind of approach?
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/13640/discussion-between-ketan-and-mookid)
Comment: also plz tell me some source where can i get info about how you wrote f(x,y) in following form: $f(x,y) = x - y^3\sin(.) = x + o(x,y)$


loading indicator code doesn't work on jquery 1.10

Question: This works on jquery 1.8
<code>$(function() {
    var $loader = $("#loading-indicator"),
        timer;

    $("#loading-indicator").css('visibility','hidden').ajaxSend(function() {
        timer && clearTimeout(timer);
        timer = setTimeout(function() {
            $loader.css('visibility','visible');
        }, 50);
    }).ajaxComplete(function() {
        clearTimeout(timer);
        $loader.css('visibility','hidden');
    });
});
</code>
<code>#loading-indicator</code> just doesn't show up..
Which methods changed on 1.10?
Answer: solved with
<code>$(function() {
    var $loader = $("#loading-indicator"),
        timer;
$loader.css('visibility','hidden');
    $(document).ajaxSend(function() {
        timer && clearTimeout(timer);
        timer = setTimeout(function() {
            $loader.css('visibility','visible');
        }, 50);
    }).ajaxComplete(function() {
        clearTimeout(timer);
        $loader.css('visibility','hidden');
    });
});
</code>
as of 1.8, ajaxStart should be attached to document..
on 1.8.3 it did work.. hmmm


How can I bring zombies down to one-punch kills in Minecraft?

Question: There's something about zombies in Minecraft that if you merely drop them down 23 blocks for the fall damage, they take two punches to kill, rather than one punch like other mobs. (23 ½ is the same, and 24 blocks will simply kill them.) I've heard that this is due to zombies having "armor" (not visible armor, evidently) that has to be broken first (or perhaps it has something to do with the effects of rounding on armor damage reduction).
How can I automatically soften up the zombies a little bit more so that they only take one punch to kill, preferably in a way which ends in a drop of at least 11 blocks?
The mechanism must be fully automatic and accept zombies arriving through a water stream. It's OK if the occasional real-visible-armor-carrying zombie still takes extra hits.

What doesn't work:
Fall damage and suffocation damage seem not to be able to "remove the armor": I have not found any combination of two falling stages, or 1 tick of suffocation followed by falling, which will result in a one-punch kill. (If you have found such a combination then I'd love to see an answer with a complete design to demonstrate it!)
There is the possibility of dropping mobs through lava, then water, which seems like it should work, but has the disadvantage that in order to prevent the mobs from swimming up in the liquids (thus dying to lava, or getting stuck in water), a simple tube would have to have, in order: a long drop, a lava block, (another long drop? not sure), a water block, and finally another long drop to the collection pad. This extreme height would make my underground zombie trap's plumbing poke up into my above-ground buildings.
Comment: Posting here as this is untested, but you can try a two-stage falling trap. Have the zombie fall a certain distance to get rid of its armor, land on a pressure plate which triggers a piston to push it into another fall.
Comment: Never heard of zombie armor, but suffocating them with pistons usually does the trick
Comment: Have you tried lava?
Comment: @Domocus Tried that, and it doesn't seem to work (perhaps because suffocation ignores armor?), and is also tricky to do consistently on a continuous stream of zombies.
Comment: @JeffreyLin I'd love to see an answer containing a mechanism for reliably applying a precise amount of lava damage to mobs. Fire might be an option too.
Comment: @Yawus Just tried that — doesn't work.
Comment: Applying a precise amount of lava damage? Easy. Build a fall trap with some suspended lava (assuming the mob doesn't float in lava). Then it is just a matter of calculating the time it takes to sustain X amount of fire damage. At the bottom of the fall is water which simultaneously negates the fall damage (as long as it is deep enough) and puts out the fire.
Answer: I have invented a solution to this problem using a mechanism to apply one tick of lava damage. It occurred to me that a tripwire could be placed immediately above lava in order to remove it (using a dispenser) as soon as a mob hits it, thus preventing the mob from continuing to swim in it. Doing this for the water as well as the lava means that no acceleration is needed to make sure the mob will fall down, so the whole mechanism is only a little bit of extra height above a standard fall-damage trap.

Build details, from top to bottom:

The zombies are pushed by water into the drop pipe. I don't know how important the length of the upper section is.
The water and lava mechanisms are identical:

Each dispenser contains an empty bucket.
All pistons are sticky.
The tripwire above the fluid is the input to the left (in first image) piston monostable (rising edge detector), which causes the dispenser to remove the fluid into the bucket. The monostable ensures that the tripwire input will not interfere with the second fluid-restoring pulse.
Behind the dispenser is a comparator followed by 2 blocks of redstone wire; this detects the dispenser having a lava bucket (which counts as 1 stack) instead of an empty bucket (which counts as 1⁄16 stack), and triggers the right piston monostable to remove the fluid. In the event that the state of the dispenser gets reversed, this circuit will simply not generate a pulse, thus correcting the problem.

Below the water block is exactly 19 ½ blocks of empty space (counting the sign) down to the fall-damage landing platform.

Results: When the zombies hit the platform, a few still take 2 punches, but most of them take 1 punch to kill. I have successfully operated this mechanism in my survival world fed by two zombie spawners.
Glitches:

The amount of damage done is not completely reliable.
It is possible for the dispensers to get inverted (resulting in zombies falling on fire, without taking any lava damage, or from the wrong height). This latest revision with comparators can self-correct this problem, but it still may result in an occasional zombie with the wrong amount of health. (I have also seen a dispenser completely fail to respond to pulses, so I suspect there is a Minecraft bug involved.)

I know it can be hard to build mechanisms from screenshots, so if you would like any further explanation of other camera angles, feel free to ask me to add them.
Comment: Did my comment inspire this?
Comment: @jeffreylin_ Can't say; I've been occasionally pondering this problem for a couple months, and I of course read all of the previous comments.
Comment: Whew, finally got most of the bugs out.
Comment: You can also use a bucket of lava in a dispenser: one pulse to dispense lava, one pulse to suck it back up. Timing as quick or slow as you like. (Not my original idea: this grinder style is credit to kingdaddydmac on YouTube, from one of his many Let's Plays.)
Answer: From what I gathered from reading a couple of forum posts/threads, 23 ½ is your best bet. Some of the zombies will die from the fall damage but the majority should end up being a one hit kill.
This seems to be because of a change between 1.0/1.1 that added "natural" armor points to zombies, here's the code from 1.1 ( Source ) :
<code>public class EntityZombie extends EntityMob
{
        ...
        public int getMaxHealth()
        {
                return 20;
        }

        public int getTotalArmorValue()
        {
                return 2;
        }
        ...
}
</code>
Hope this helped you, good luck!
Comment: Of course, you could just amass several of them at 2 hits and use a splash potion of healing to kill them all.
Comment: I'm afraid your proposal does not work. I have tested the fall damage approach — there is a height at which all zombies die, and a height just adjacent at which they take two hits to kill. Perhaps this is because fall damage is a damage type not absorbed by armor. Thank you for adding the info that zombies really do "have armor", though.
Comment: Another way to go about this is go to the height where they take 2 hits to kill and just use a wooden sword, then they will only take one hit.
Answer: Mechanism above is good to expose 1 tick of lava damage, however you ALSO need precision for the falling zombies. That device can have multiple zombies falling together each with "overlapping" parts of their bodies say the feet of 2nd zombie overlapping with head of first zombie, so ONLY the first zombie takes the lava damage.
So you need to make sure ALL zombies fall either totally separately (very hard) or as a single group that are all EXACTLY at the same Y elevation.
So INSTEAD use a long-delay clock to send a "start" signal at regular intervals.
Right under the spawning rooms, some (to be found) height above the water+lava device, you have a "trap room". Zombies fall from above from a hole in roof, onto the floor, and mass up there.
All signals go from the precise "start" signal, which repeats say every 10 seconds (or whatever).
Start signal activates a piston to close the traproom roof leaving exactly a 1x1x2 high room for the zombies. Thus, no more zombies arrive (for this "wave").
Small Delay. This makes sure all zombies in room are all on trap room floor, at EXACTLY the same height. well, some might be trying to "jump around" so this ain't 100% perfect. But at least the height difference of overlapping zombies is kept limited to a minimum (aboie distance between a zombie head and roof, only a few texture pixels, compared to before where a "train" of falling but overlapping zombies had no theoretical limit on it's total height length).
2nd piston opens floor, all zombies drop.
Small delay, 2nd piston closes floor and 1 tick later, ceiling piston opens roof for starting amassing the zombies for the next wave.
Then some falling distance = that yields a SPECIFIC falling time.
Then some other delay = activates the water+lava damaging device. NO STRING WIRE necessary, the delay can be directly from the start signal not from the falling zombies. That is in fact better because... zombies jump around, right ? A precise clock is thus better. More precise and thus more controlled device.
That way, ALL zombies will take the same exact same amount of lava damage. Well, theoretically possible that the SMALL vertical distance between zombies that were flat on the trapdoor floor vs zombies that were jumping right when the trapdoor opened, is sufficient to allow a zombie avoiding the 1 lava damage (I seriously doubt it), but that should either be a VERY rare occurence, or else just try another falling height / redstone delay combination. Or just try exposing the zombies to MORE than 1 tick of lava. After all, the zombies have a "cooldown" time between damage, so making tem exposed for more thna 1 tick but way less than the cooldown time, will allow even the "slightly latecomer" falling zombies (beause they jumped right when the trapdoor opened) to "catch up" to the others and thus ALSO take the 1 point of lava damage, while the "falling normally" zombies will still be in damage immunity cooldown.
Ergo, ALL zombies take exactly 1 damage in a VERY predictable fashion.
Then some falling distance for enough falling damage so that 1 punch kills are always the case (well, zombies without actual armor equipped, that is).
:-)
Answer: You can keep the zombie suffocating for exactly 8 seconds and it will be a one punch kill (Minecraft 1.7.8).
Answer: Try to do 24 blocks but the 24th block is a fence which shouldn't kill them and shouldn't have them at two punches it should be a 1 punch kill
Comment: "Try"? "Should"? Have you tested this, or is it just guessing?


NodeJS: loading ES Modules and native addons in the same project

Question: Before the actual questions (see at the end), please let me show the steps that lead to that question through an example:
Creating the project
tests$ mkdir esm && cd esm
tests/esm$ nvm -v
0.37.2
tests/esm$ nvm use v15
Now using node v15.6.0 (npm v7.5.6)
tests/esm$ node -v
v15.6.0
tests/esm$ npm -v
7.5.6
tests/esm$ npm init
package name: (esm) test-esm
entry point: (index.js)

Installing nodehun
tests/esm$ npm install nodehun
added 2 packages, and audited 3 packages in 11s
tests/esm$ npm ls
email@example.com tests/esm
└── firstname.lastname@example.com

dependencies of nodehun here

index.js
import { suggest } from './checker.js'
suggest("misspeling");

checker.js
import Nodehun  from 'nodehun'
import fs from 'fs';

const affix       = fs.readFileSync('dictionaries/en_NZ.aff')
const dictionary  = fs.readFileSync('dictionaries/en_NZ.dic')
const nodehun     = new Nodehun(affix, dictionary)

export const suggest = (word) => hun_suggest(word);

async function hun_suggest(word) {
  let suggestions = await nodehun.suggest(word);
  console.log(suggestions);
}

To obtain the required Hunspell dictionary files (affix and dictionary):
tests/esm$ mkdir dictionaries && cd dictionaries
tests/esm/dictionaries$ curl https://www.softmaker.net/down/hunspell/softmaker-hunspell-english-nz-101.sox > en_NZ.sox
tests/esm/dictionaries$ unzip en_NZ.sox en_NZ.aff en_NZ.dic

Running the project
As per nodejs documentation (Determining Module System) to support the import / export:

Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:
• Files ending in .js when the nearest parent package.json file contains a top-level "type" field with a value of "module".

We add "type": "module" field in the package.json file of the project.
package.json
{
  ...
  "main": "index.js",
  "type": "module",
  ...
}

First Failed Run
tests/esm$ node index.js
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".node" for tests/esm/node_modules/nodehun/build/Release/Nodehun.node
... omitted ...
at async link (node:internal/modules/esm/module_job:64:9) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

Digging a bit on the reason of the above error:

in the documentation on how to load addons, it refers to the use of require

The filename extension of the compiled addon binary is .node (as opposed to .dll or .so). The require() function is written to look for files with the .node file extension and initialize those as dynamically-linked libraries.

once you define your node project as a "type": "module", require it ceases to be supported (as specified in Interoperability with CommonJS):

Using require to load an ES module is not supported because ES modules have asynchronous execution. Instead, use import() to load an ES module from a CommonJS module.

Temporary Solution
After some time searching the documentation, I found a temporary solution: Customizing ESM specifier resolution algorithm:

The current specifier resolution does not support all default behavior of the CommonJS loader. One of the behavior differences is automatic resolution of file extensions and the ability to import directories that have an index file.
The --experimental-specifier-resolution=[mode] flag can be used to customize the extension resolution algorithm.
To enable the automatic extension resolution and importing from directories that include an index file use the node mode.

tests/esm$ node --experimental-specifier-resolution=node index.js
(node:XXXXX) ExperimentalWarning: The Node.js specifier resolution in ESM is experimental.
(Use `node --trace-warnings ...` to show where the warning was created)
[
  'misspelling',
  'misspending',
  'misspeaking',
  'misspell',
  'dispelling',
  'misapplier',
  'respelling'
]

There are a some posts that get to this same resolution (ref 1, ref 2).
However, using experimental flags does not seem a proper way to run your application on production.
Failed Alternative with esm package
From that point, several failed attempts have been tried to avoid the use of --experimental-* flags. Doing some search, I found some posts (ref 1, ref 2) recommending the use of the esm package.

esm gets 1.3M downloads per week.
According the read-me file in GitHub, it does not require any changes.

However, at this point, when I try this node -r esm index.js, a new error appears:
tests/esm$ npm install esm
added 1 package, and audited 4 packages in 709ms
tests/esm$ npm ls
firstname.lastname@example.com tests/esm
├── email@example.com
└── email@example.com
tests/esm$ node -r esm index.js
tests/esm/index.js:1
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: tests/esm/index.js
    at new NodeError (node:internal/errors:329:5)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1125:13) {
  code: 'ERR_REQUIRE_ESM'
}

The above could be due to a reported issue (Error [ERR_REQUIRE_ESM]: Must use import to load ES Module / require() of ES modules is not supported).

There is proposed patch to fix it, although I do not know how to use it myself.

const module = require('module');
module.Module._extensions['.js'] = function(module, filename) {
  const content = fs.readFileSync(filename, 'utf8');
  module._compile(content, filename);
};

Questions

Is there a (standard) way to use import / export (ES Modules) without incurring in issues with import addons?

Avoiding the use of the --experimental-specifier-resolution=node flag.

Perhaps esm could be the solution to the above. Is there anything I am doing wrong with the usage esm package?

If it is a correct usage, is there a way to use the proposed patch myself as a working around?

Any hints to help to solve it would be really appreciated.
Note: the final status of the example can be cloned from https://github.com/rellampec/test-esm.git
Comment: I _think_ you can do `import { createRequire } from 'module'; const require = createRequire(import.meta.url);` to get a `require` function inside the ESM to load the native module?
Comment: @loganfsmyth just pasted your code at the top of the `index.js` and retried `node -r esm index.js`: same error `ERR_REQUIRE_ESM` (btw, `node index.js` persists with the error `ERR_UNKNOWN_FILE_EXTENSION`)
Answer: I ran into a similar problem and fixed it this way:
https://nodejs.org/api/module.html#module_module_createrequire_filename
// The project is "type": "module" in package json
// createRequire is native in node version >= 12
import { createRequire } from 'module';
import path from 'path';
// Absolute path to node modules (or native addons)
const modulesPath = path.resolve(process.cwd(), 'node_modules');
// Create the require method
const localRequire = createRequire(modulesPath);
// require the native add-on
const myNativeAddon = localRequire('my-native-addon');

Comment: `function bindings(addonName, relPath="build/Debug") {
    const modulesPath = path.resolve(process.cwd(), relPath, addonName);
    // Create the require method
    const localRequire = createRequire(modulesPath);
    // require the native add-on
    const myNativeAddon = localRequire(modulesPath);
    return myNativeAddon;
}` This worked for me. Note how I am passing the same path to both createRequire and localRequire.
Comment: You sir are a hero. Sad that such a kludgy solution is needed. I despise the new ES module system, it makes everything so awkward and unintuitive... But there's no other way if even a SINGLE dependency of yours goes the ES route, you are dragged along with lol. Plus you can use async at the root level which is nice.
Answer: After some ramblings trying to figure this out got to the root cause.
When using node -r esm index.js, the esm package does already all the work for your (as noted in other answers), and therefore (not mentioned in other answers):

the package.json should be updated by removing "type:" "module" (as it creates unintended interactions between the native node ES Modules feature and the esm package you installed)

Aside note: if you tried to use node ES Modules and then you try to switch to esm package, it is very easy to miss this point.


Symmetric rational function is a rational function in the elementary symmetric polynomials.

Question: For a course on Galois theory, we proved the fundamental theorem of symmetric polynomials, which states that every symmetric polynomial can be uniquely written as a polynomial in the elementairy symmetric polynomials. As an exercise we were asked to prove that every symmetric rational function also is a rational function in the elementary symmetric polynomials.
For this I have the following (partial) proof. Let $K$ be a field, let $f \in K(T_1, \dots, T_n)$ be a symmetric function. We can write $f = g/h$ with $g, h$ coprime. Let $\sigma \in S_n$, then $\sigma(g)/\sigma(h) = \sigma(g/h) = g/h$, so $\sigma(g)h = \sigma(h)g$. Since $g$ and $h$ are coprime, it follows that $g \mid \sigma(g)$, and since the total degrees of the polynomials are the same it follows there exists some $k \in K^\times$ such that $\sigma(g) = kg$. Similarly for $h$.
Ofcourse I would like to conclude from this that we must have $\sigma(g) = g$ since $\sigma$ doesn't change the coefficients, but I realised the argument is more subtle than that, since this is not necessarily true. For example, with $K = \mathbb{F}_7$ and $n = 3$ we have
$$
(3 2 1) \cdot (X_1 X_2 + 2 X_2 X_3 + 4 X_3 X_1) = 2 \cdot (X_1 X_2 + 2 X_2 X_3 + 4 X_3 X_1).
$$
So, does anyone know how to proceed? Ofcourse, once you have $\sigma(g) = g$ and $\sigma(h) = h$ for all $\sigma \in S_n$ the result follows from the fundamental theorem of symmetric polynomials.
As a sidenote: I know there's a proof using the fundamental theorem of Galois theory, but I would like to finish a proof using this approach.
Comment: in the particular case the polynomial is an eigenvector only for the subgroup generated by $(3,2,1)$. But otherwise the constant $k$ depends multiplicatlvely on $\sigma$ and there are (at most) two such morphism from $S_n$ to $K^{\times}$
Answer: Let $f\in \mathbf{Q}(T_1,\ldots,T_n)$ be a symmetric rational function, then we can write $f=\frac{g}{h}$ with $g,h\in \mathbf{Z}[T_1,\ldots,T_n]$.
If $h$ is a symmetric polynomial, then $g=hf$ is symmetric too. By the fundamental theorem of symmetric polynomials, $f$ is a rational function in the elementary symmetric polynomials.
If $h$ is not a symmetric polynomial, consider $h'=\prod_{\sigma\in S_n\setminus \{e\}} \sigma h$. Then $hh'$ is a symmetric polynomial by construction. By writing $f=\frac{g}{h}=\frac{gh'}{hh'}$, we reduce ourselves to the previous case.
Comment: Thanks for your answer! That's a nice simple proof. I'll accept the other answer though, since that answer provided a direct answer to my question instead of a different proof.
Answer: For $\sigma \in S_n$, let $\lambda_\sigma \in K^\times$ be such that $\sigma(g) = \lambda_\sigma g$ and $\sigma(h) = \lambda_\sigma h$. Then $\sigma \mapsto \lambda_\sigma$ is a group homomorphism $\lambda : S_n \to K^\times$. (When $n \geq 6$, there are at most two such homomorphisms.)
We want to show that $\lambda$ is trivial. Suppose not, and let $(i, j)$ be a transposition that does not lie in the kernel of $\lambda$. We will arrive at a contradiction with the fact that $g$ and $h$ are coprime. Because $\lambda_{(i, j)} \neq 1$, we obtain that $g(T_1, \ldots, \widehat T_j, T_i, \ldots, T_n) = 0$. (We substituted $T_i$ for $T_j$.) When $g$ is considered as a polynomial over $K((T_k)_{k \neq j})$, this means that $T_i$ is a root of $g$. Thus $g$ is divisible by $(T_i - T_j)$. Similarly, $h$ is divisible by $(T_i - T_j)$. But by Gauss's lemma, $g$ and $h$ are coprime in $K((T_k)_{k \neq j})[T_j]$, a contradiction.


How to create custom TFS check-in policies in .NET Core 2.0?

Question: I'm familiar with the new deployment/installation design of VS 2017, and the way it leaves no footprint on registry.
And I'm also familiar with how we need to change our check-in policy installation from registry manipulation to VS extension creation.
However, now I need to create check-in policies in .NET Core 2.0. The problem is that I need to use Microsoft.TeamFoundation.VersionControl.Client dll to be able to access PolicyBase and also PendingChange classes. This results in FileNotFoundException.
Also I need to use Mono.Cecil as the reflection library, to be able to process things in more detail before checking-in. I can't find if Mono.Cecil supports .NET Core 2.0 or not. Nuget page is not informative and the libraries page on GitHub is also not easy to understand.
And another obstacle is to create a VS Extension. I can't find out the required package definition items to be added to source control.
Can you please provide a simple example of how to create a custom TFS Check-in Policy in VS 2017 via .NET Core 2.0?
Comment: Why you have to create the check-in policy project with .Net Core 2.0?  For now the TFS .NET client libraries packages, some of the dependencies are not compatible with .NET Core.
Answer: Since the policy ends up running in the context of Visual Studio itself, I believe you have to be compatible with the .NET framework that Visual Studio is running in, and that is the "classic" .NET Framework, not .NET Core. Libraries written to a .NET Standard can potentially be consumed by both .NET Framework and .NET Core applications, and I believe you could also include separate executables in an extension and run them as separate processes if there's some piece that absolutely must run in a .NET Core environment, but you can't mix-and-match within a single process, and the extension code itself doesn't get a choice: it runs in the Visual Studio process.


Should I install Ubuntu Desktop or Ubuntu Server?

Question: Sorry if this is a simple question, but - eeks - I'm really a Windows person(!).  I'm getting a PowerEdge Server to do really just ONE thing: I need to run interactive sessions of MATLAB (parallel computing with high CPU/RAM use).  Should I install the server or desktop version of Ubuntu?  As an aside, I would have just gotten a workstation, but I got a good deal on the server with better specs - Dual E5-2690s :)
I know basically nothing about this, so any help would be greatly appreciated!  Thanks so much!
Comment: Take a look st the answer to the question [Is it possible to run matlab on a remote server and control it using the matlab GUI from a thin client?](http://stackoverflow.com/questions/7932806/is-it-possible-to-run-matlab-on-a-remote-server-and-control-it-using-the-matlab) and then consider replacing "remote server" with "local host". The server used as an example in the answer is an Ubuntu server.
Comment: If this is all you are going to the machine for, I would go for a minimal install of desktop to keep as much CPU//RAM free as possible.
Answer: Honestly, there's really no reason to use the Desktop version of Ubuntu on a server. Especially if it's going to be using a high amount of CPU/RAM/etc. I would install Ubuntu Server and go from there. If you really need a GUI to work with, then you can install a lightweight desktop environment like XFCE or LXDE. Gnome, KDE, or Unity are the heavyweights, so try to stay away from those in this particular instance. For more information regarding desktop environments, read this comparison of X Window System Desktop Environments.


PLINQ + LINQ = NRE?

Question: What is the reason for random NREs when running the code below? Given that results is initialized how is it possible to get t within lambda as null?
var results = new List<Result>();

for (int i = 0; i < 100; i++)
{
    Parallel.For((index) =>
        {
            results.Add(Result.Create(...));
        });

    results = results.Where(t => t.IsValid).ToList(); // NRE here due to t is null!

}

Comment: Your example doesn't compile and is wrong. there is a `Parallel.For` without a collection.
Answer: List<> isn't thread safe. You are adding elements from multiple threads. If you really want to use it:
lock (results)
{
    results.Add(Result.Create(...));
}

Note that your example is wrong... Something that compiles and runs would be:
var results = new List<Result>();

Parallel.For(0, 100, index =>
{
    lock (results)
    {
        results.Add(Result.Create(...));
    }
});

results = results.Where(t => t.IsValid).ToList(); // NRE here due to t is null!

or better
var results = new List<Result>();

Parallel.For(0, 100, index =>
{
    var result = Result.Create(...);

    lock (results)
    {
        results.Add(result);
    }
});

results = results.Where(t => t.IsValid).ToList(); // NRE here due to t is null!

so that the result creation doesn't block the List<> writing :-) Otherwise the code is useless and it would be executed sequentially.
Comment: You might also want to use [ConcurrentBag](https://msdn.microsoft.com/en-us/library/dd381779%28v=vs.110%29.aspx) as it is optimized for this situation.
Comment: Or simply `var results = Enumerable.Range(0, 100).AsParallel().Select(i => Result.Create(...)).Where(t => t.IsValid).ToList()`
Comment: @sloth Yes, if you are trying to do one of those contests where you have to save on bytes, or you are ranked on obfuscation :-) But I do think there is at least a difference here... `Parallel.For` knows the range of numbers, so it has the `Length` information, while `Enumerable.Range(0, 100).AsParallel()` doesn't know it. I don't know if this information is really used.
Comment: True, you could use `var results = Enumerable.Range(0, 100).ToList().AsParallel()...` to optimize this if needed so the default partitioner could distribute the workload better.
Comment: Locking here essentially converts the code to sequential. Better to use a  ConcurrentQueue<> which doesn't require any locking.
Comment: @PanagiotisKanavos Not if `Result.Create` is very slow. The "better" variant only locks on `results.Add`. And for a fast `Result.Create`, the `Parallel.For` is worse than useless
Comment: @Caramiriel That is correct... Unless you want to do many read-only operations after the end of the `Parallel.For`, or if you need/want to use an indexer. On writing the `ConcurrentBag<>` is surely many times faster than `lock + List.Add`

PLINQ + LINQ = NRE?