Q:

Unmanaged to managed interop performance in x86 and x64

In my tests I'm seeing the performance cost of unmanaged to managed interop double when compiling for x64 instead of x86. What is causing this slowdown?
I'm testing release builds not running under the debugger. The loop is 100,000,000 iterations.
In x86 I'm measuring an average of 8ns per interop call, which seems to match what I've seen in other places. Unity's x86 interop is 8.2ns. A Microsoft article and Hans Passant both mention 7ns. 8ns is 28 clock cycles on my machine which seems at least reasonable, though I do wonder if it's possible to go faster.
In x64 I'm measuring an average of 17ns per interop call. I can't find anyone mentioning a difference between x86 and x64, or even mentioning which they are referring to when giving times. Unity's x64 interop clocks in around 5.9ns.
Regular function calls (including into an unmanaged C++ DLL) cost an average of 1.3ns. This doesn't change significantly between x86 and x64.
Below is my minimal C++/CLI code for measuring this, though I'm seeing the same numbers in my actual project that consists of a native C++ project calling into the managed side of a C++/CLI DLL.
#pragma managed
void
ManagedUpdate()
{
}

#pragma unmanaged
#include <wtypes.h>
#include <cstdint>
#include <cwchar>

struct ProfileSample
{
    static uint64_t frequency;
    uint64_t startTick;
    wchar_t* name;
    int count;

    ProfileSample(wchar_t* name_, int count_)
    {
        name = name_;
        count = count_;

        LARGE_INTEGER win32_startTick;
        QueryPerformanceCounter(&win32_startTick);
        startTick = win32_startTick.QuadPart;
    }

    ~ProfileSample()
    {
        LARGE_INTEGER win32_endTick;
        QueryPerformanceCounter(&win32_endTick);
        uint64_t endTick = win32_endTick.QuadPart;

        uint64_t deltaTicks = endTick - startTick;
        double nanoseconds = (double) deltaTicks / (double) frequency * 1000000000.0 / count;

        wchar_t buffer[128];
        swprintf(buffer, _countof(buffer), L"%s - %.4f ns\n", name, nanoseconds);
        OutputDebugStringW(buffer);

        if (!IsDebuggerPresent())
            MessageBoxW(nullptr, buffer, nullptr, 0);
    }
};

uint64_t ProfileSample::frequency = 0;

int CALLBACK
WinMain(HINSTANCE, HINSTANCE, PSTR, INT)
{
    LARGE_INTEGER frequency;
    QueryPerformanceFrequency(&frequency);
    ProfileSample::frequency = frequency.QuadPart;

    //Warm stuff up
    for ( size_t i = 0; i < 100; i++ )
        ManagedUpdate();

    const int num = 100000000;
    {
        ProfileSample p(L"ManagedUpdate", num);

        for ( size_t i = 0; i < num; i++ )
            ManagedUpdate();
    }

    return 0;
}

1) Why does x64 interop cost 17ns when x86 interop costs 8ns
2) Is 8ns the fastest I can reasonably expect to go?
Edit 1
Additional information
CPU i7-4770k @ 3.5 GHz
Test case is a single C++/CLI project in VS2017.
Default Release configuration
Full optimization /O2
I've randomly played with settings like Favor Size or Speed, Omit Frame Pointers, Enable C++ Exceptions, and Security Check and none appear to change the x86/x64 discrepancy.
Edit 2
I've stepped through the disassembly (not something I'm very familiar with at this point).
In x86 is seem something along the lines of
call    ManagedUpdate
jmp     ptr [__mep@?ManagedUpdate@@$$FYAXXZ]
jmp     _IJWNOADThunkJumpTarget@0

In x64 I see
call    ManagedUpdate
jmp     ptr [__mep@?ManagedUpdate@@$$FYAXXZ]
        //Some jumping around that quickly leads to IJWNOADThunk::MakeCall:
call    IJWNOADThunk::FindThunkTarget
        //MakeCall uses the result from FindThunkTarget to jump into UMThunkStub:

FindThunkTarget is pretty heavy and it looks like most of the time is being spent there. So my working theory is that in x86 the thunk target is known and execution can more or less jump straight to it. But in x64 the thunk target is not known and a search process takes place to find it before being able to jump to it. I wonder why that is?

A:

I have no recollection of ever giving a perf guarantee on code like this.  7 nanoseconds is the kind of perf you can expect on C++ Interop code, managed code calling native code.  This is going the other way around, native code calling managed code, aka "reverse pinvoke".
You are definitely getting the slow flavor of this kind of interop.  The "No AD" in IJWNOADThunk is the nasty little detail as far as I can see.  This code did not get the micro-optimization love that is common in interop stubs.  It is also highly specific to C++/CLI code.  Nasty because it cannot assume anything about the AppDomain in which the managed code needs to run.  In fact, it cannot even assume that the CLR is loaded and initialized.

Is 8ns the fastest I can reasonably expect to go?

Yes.  You are in fact on the very low end with this measurement.  Your hardware is a lot beefier than mine, I'm testing this on a mobile Haswell.  I'm seeing between ~26 and 43 nanosec for x86, between ~40 and 46 nanosec for x64.  So you are getting x3 better times, pretty impressive.  Frankly, a bit too impressive but you are seeing the same code that I do so we must be measuring the same scenario.

Why does x64 interop cost 17ns when x86 interop costs 8ns?

This is not optimal code, the Microsoft programmer was very pessimistic about what corners he could cut.  I have no real insight whether that was warranted, the comments in UMThunkStub.asm don't explain anything about choices.
There is not anything particularly special about reverse pinvoke.  Happens all the time in, say, a GUI program that processes Windows messages.  But that is done very differently, such code uses a delegate.  Which is the way to get ahead and make this faster.  Using Marshal::GetFunctionPointerForDelegate() is the key.  I tried this approach:
using namespace System;
using namespace System::Runtime::InteropServices;

void* GetManagedUpdateFunctionPointer() {
    auto dlg = gcnew Action(&ManagedUpdate);
    auto tobereleased = GCHandle::Alloc(dlg);
    return Marshal::GetFunctionPointerForDelegate(dlg).ToPointer();
}

And used like this in the WinMain() function:
typedef void(__stdcall * testfuncPtr)();
testfuncPtr fptr = (testfuncPtr)GetManagedUpdateFunctionPointer();
//Warm stuff up
for (size_t i = 0; i < 100; i++) fptr();

    //...
    for ( size_t i = 0; i < num; i++ ) fptr();

Which made the x86 version a little faster.  And the x64 version just as fast.
If you are going to use this approach then keep in mind that an instance method as the delegate target is faster than a static method in x64 code, the call stub has less work to do to rearrange the function arguments.  And do beware I took a shortcut on the tobereleased variable, there is a possible memory management detail here and a GCHandle::Free() call might be preferred or necessary in a plug-in scenario.


Q:

A star c++, what is wrong

Here it is, I have no idea why it doesnt work. Sometimes its ok, sometimes it crashes and sometimes it returns the wrong way...
//apath.h
#ifndef APATH_H
#define APATH_H
#include <vector>
#include <cmath>
#include <memory>
#include <allegro.h>

using namespace std;

double len(int x1, int y1, int x2, int y2);

class GameMap;

class point
{
public:
      int x,y;
      double f,g;
      point *parent;
      point(int _x=0, int _y=0, point *par=NULL) {x=_x; y=_y; parent=par; f=0; g=0;};
      void countF(int sx, int sy, int tx, int ty)
      {
      g=len(x,y,tx,ty);
      f=g+len(sx,sy,x,y);
      };
};

struct point2d
{
      int x,y;
};

//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
const point2d directions[]=
{
      {1,0},{1,1},{0,1},{-1,1},{-1,0},{-1,-1},{0,-1},{1,-1},
};

class path
{
public:
      vector<point2d> way;
      int step;
      bool findPath(int x, int y, int fx, int fy, GameMap& map, BITMAP* out);
private:
      vector<point> open;
      vector<point> closed;
};

#endif

and apath.cpp:
//apath.cpp
#include "apath.h"
#include <vector>
#include <cmath>

double len(int x1, int y1, int x2, int y2)
{
       return (sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)));
       //return max(abs(x1-x2), abs(y1-y2));

      /*int mx=max(x1,x2)-min(x1,x2);
      int my=max(y1,y2)-min(y1,y2);
      return (min(mx,my)*14+max(mx,my)-min(mx,my)*10);*/
};

bool findPoint(vector<point> arr, point pt, point &ret)
{
     for (int i=0; i<arr.size(); i++) if (arr[i].x==pt.x && arr[i].y==pt.y) { ret=arr[i]; return true;}
     return '\0';
};

//GameMap holds the map...
bool path::findPath(int x, int y, int fx, int fy, GameMap& map, BITMAP* out)
{
     while(!open.empty()) open.pop_back();
     while(!closed.empty()) closed.pop_back();
     while(!way.empty()) way.pop_back();

     point start(x,y);
     start.countF(x,y,fx,fy);
     open.push_back(start);

     point finish(fx,fy);

     double min=999999999;
     int index;
     point tmp;
     point *tmp2;
     point comparer;

     while (!findPoint(closed,finish,comparer))
     {
           min=999999999;
           for (int i=0; i<open.size(); i++)
           {
               if(open[i].f<min)
                   {
                       min=open[i].f;
                       index=i;
                   }
           }

           tmp=open[index];
           closed.push_back(open[index]);
           open.erase(open.begin()+index);

           for (int i=0; i<8; i++)
               {
                    tmp2=new point(tmp.x+directions[i].x,tmp.y+directions[i].y);
                    if (map.getCollisionXY(tmp2->x,tmp2->y)==1 // map.getCollision returns 1 when you cant pass through the tile and 0 otherwise...
                    || findPoint(closed,*tmp2,comparer)) continue;
                    if (!findPoint(open,*tmp2,comparer))
                    {
                        point newP(tmp.x+directions[i].x,tmp.y+directions[i].y,&closed[closed.size()-1]);
                        newP.countF(x,y,fx,fy);
                        open.push_back(newP);
                    }
                    else
                    {
                        if (comparer.g>tmp.g)
                        {
                             comparer.parent=&closed[closed.size()-1];
                             comparer.countF(x,y,fx,fy);
                        }
                    }
                    delete tmp2;
               }
/*     for (int i=0; i<open.size(); i++)
        if (open[i].parent!=0)circlefill(out,open[i].x*16+4,open[i].y*16+4,3,0xff0000);
           if (open.empty()) return false;
     for (int i=0; i<closed.size(); i++)
        if (closed[i].parent!=0)circlefill(out,closed[i].x*16+12,closed[i].y*16+12,3,0xffff00);*/ //debug draw

     }
     point2d pt;
     pt.x=finish.x;
     pt.y=finish.y;
     way.push_back(pt);
     point wayer;
     wayer=closed[closed.size()-1];
     while(wayer.parent!=0) //CRASH from here
     {
         wayer=*wayer.parent;
         pt.x=wayer.x;
         pt.y=wayer.y;
         way.push_back(pt);
//         circlefill(out,pt.x*16+12,pt.y*16+12,3,0xffffff); //debug draw
     }    //CRASH to here, i dont exacly know where it is, but when trying to recreate path.
     return true;
};

Some explaination:
GameMap is class with map
and its getCollisionXY returns 1 you cant pass throught tile and 0 otherwise.
Thanx for any help.

A:

One main source I see that could cause access violation is that your points contain parents as pointers and they are members of a vector. If the vector is reallocated these pointers could become invalidated.
Other than that it is hard to immediately see what causes the crash.
You really should run your code through a debugger. I have just pointed out one thing I immediately see.


Q:

String not being returned

I'm trying to access a parent class to pass information from it to its child and then echo that information to the page, but i cannot seem to get the $flavor to echo out from the Soda class i created. What gets echo'd out to the screen is; Product Name: Space Juice Soda Flavor: - obviously something is wrong with my __construct (i think)  in the Soda class but cannot figure out what.
class Product {

public $name = 'default_name';
public $price = 0;
public $desc = "default description";

function __construct($name, $price, $desc) {
    $this->name = $name;
    $this->price = $price;
    $this->desc = $desc;
}

public function getInfo() {
    return "Product Name: " . $this->name;
}
}

class Soda extends Product {

public $flavor;

function __construct($name, $price, $desc, $flavor) {
    parent::__construct($name, $price, $desc);
}

public function getInfo() {
    return "Product Name: " . $this->name . " Flavor: " . $this->flavor;
}
}

$shirt = new Product("Space Juice T-Shirt", 20, "Awesome Grey T-Shirt");
$soda = new Soda("Space Juice Soda", 2, "Thirst mutilator", "Grape");

echo $soda->getInfo();

A:

You are not initializing flavor in your Soda class.
class Soda extends Product {

       public $flavor;

       function __construct($name, $price, $desc, $flavor) {
           parent::__construct($name, $price, $desc);
           $this->flavor = $flavor; // add this line here <<<<<<<<<<<<<
       }
       ...


Q:

Getting uploaded shapefile into geometry field on PostGIS table?

I am working with a PHP web application where we have a user submitting a ShapeFile.
I am able to convert that ShapeFile then to a format of geojson.
What I am wondering now is how I can best get that geojson into a PostGIS table as a geometry column?

A:

It might be easier to use shp2pgsl to directly load the shapefile into a PostGIS table, for example:
shp2pgsql -d -I shapefile.shp table | psql -U user database

If you prefer to use GeoJSON directly, there is ST_GeomFromGeoJSON, but for this (as I understand), you'll need to parse and insert individual features from the GeoJSON file. See this answer for additional details.
You can always keep the GeoJSON file on the server for transfer to the client, or export individual features from PostGIS as GeoJSON, using ST_AsGeoJSON
If going directly from shape to PostGIS doesn't fit your use case, perhaps include some additional information.


Q:

Stopwatch that counts down in C#

I've seen variations of this by googling it but I have a windows form with a timer control, three textboxes (hour, minute, second) and based on a button being clicked, I want to count down from 2 hours.  So right after clicking textbox1 (hour) will be 1, textBox2 (minute) will be 59, textBox3 (second) will be 59 and they will all continue to count down until all read 0.
Does anyone have some code to share for that?
Many thanks.

A:

You can use the TimeSpan class. Initialize of to 2 hours. If you start the Timer get the current timer. Then with a Timer object refresh your display every second. Simply get the current Time. So the remaining time is:
TimeSpan remaining = twoHoursTimespan - (CurrentTime - StartTime);

A:

Extract the components from a TimeSpan. Record the current time and date as soon as the button is clicked, and store that in a variable. Then, every second your timer should calculate the duration since the start time.
IE: DateTime result = DateTime.Now.Subtract(StartingTime);
Then, use the parts of the resulting TimeSpan to populate the fields.
IE: int Hour = result.Hour; (or something like that).
Addendum: Don't count down manually every second, because this is likely to cause the countdown to be inaccurate.


Q:

Cannot install Matplotlib on Mac

I cannot install Matplotlib on Mavericks 10.9.  I have the following error message telling me freetype cannot be built:
    ============================================================================
    Edit setup.cfg to change the build options

    BUILDING MATPLOTLIB
                matplotlib: yes [1.3.1]
                    python: yes [2.7.6 (default, Apr  9 2014, 11:48:52)  [GCC
                            4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)]]
                  platform: yes [darwin]

    REQUIRED DEPENDENCIES AND EXTENSIONS
                     numpy: yes [version 1.8.1]
                  dateutil: yes [dateutil was not found. It is required for date
                            axis support. pip/easy_install may attempt to
                            install it after matplotlib.]
                   tornado: yes [tornado was not found. It is required for the
                            WebAgg backend. pip/easy_install may attempt to
                            install it after matplotlib.]
                 pyparsing: yes [pyparsing was not found. It is required for
                            mathtext support. pip/easy_install may attempt to
                            install it after matplotlib.]
                     pycxx: yes [Couldn't import.  Using local copy.]
                    libagg: yes [pkg-config information for 'libagg' could not
                            be found. Using local copy.]
                  freetype: no  [The C/C++ header for freetype2 (ft2build.h)
                            could not be found.  You may need to install the
                            development package.]
                       png: yes [pkg-config information for 'libpng' could not
                            be found. Using unknown version.]

    OPTIONAL SUBPACKAGES
               sample_data: yes [installing]
                  toolkits: yes [installing]
                     tests: yes [nose 0.11.1 or later is required to run the
                            matplotlib test suite]

    OPTIONAL BACKEND EXTENSIONS
                    macosx: yes [installing, darwin]
                    qt4agg: no  [PyQt4 not found]
                   gtk3agg: no  [Requires pygobject to be installed.]
                 gtk3cairo: no  [Requires cairo to be installed.]
                    gtkagg: no  [Requires pygtk]
                     tkagg: yes [installing, version 81008]
                     wxagg: no  [requires wxPython]
                       gtk: no  [Requires pygtk]
                       agg: yes [installing]
                     cairo: no  [cairo not found]
                 windowing: no  [Microsoft Windows only]

    OPTIONAL LATEX DEPENDENCIES
                    dvipng: no
               ghostscript: no
                     latex: no
                   pdftops: no

    ============================================================================
                            * The following required packages can not be built:
                            * freetype
    Complete output from command python setup.py egg_info:
    ============================================================================

Edit setup.cfg to change the build options

BUILDING MATPLOTLIB

            matplotlib: yes [1.3.1]

                python: yes [2.7.6 (default, Apr  9 2014, 11:48:52)  [GCC

                        4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)]]

              platform: yes [darwin]

REQUIRED DEPENDENCIES AND EXTENSIONS

                 numpy: yes [version 1.8.1]

              dateutil: yes [dateutil was not found. It is required for date

                        axis support. pip/easy_install may attempt to

                        install it after matplotlib.]

               tornado: yes [tornado was not found. It is required for the

                        WebAgg backend. pip/easy_install may attempt to

                        install it after matplotlib.]

             pyparsing: yes [pyparsing was not found. It is required for

                        mathtext support. pip/easy_install may attempt to

                        install it after matplotlib.]

                 pycxx: yes [Couldn't import.  Using local copy.]

                libagg: yes [pkg-config information for 'libagg' could not

                        be found. Using local copy.]

              freetype: no  [The C/C++ header for freetype2 (ft2build.h)

                        could not be found.  You may need to install the

                        development package.]

                   png: yes [pkg-config information for 'libpng' could not

                        be found. Using unknown version.]

OPTIONAL SUBPACKAGES

           sample_data: yes [installing]

              toolkits: yes [installing]

                 tests: yes [nose 0.11.1 or later is required to run the

                        matplotlib test suite]

OPTIONAL BACKEND EXTENSIONS

                macosx: yes [installing, darwin]

                qt4agg: no  [PyQt4 not found]

               gtk3agg: no  [Requires pygobject to be installed.]

             gtk3cairo: no  [Requires cairo to be installed.]

                gtkagg: no  [Requires pygtk]

                 tkagg: yes [installing, version 81008]

                 wxagg: no  [requires wxPython]

                   gtk: no  [Requires pygtk]

                   agg: yes [installing]

                 cairo: no  [cairo not found]

             windowing: no  [Microsoft Windows only]

OPTIONAL LATEX DEPENDENCIES

                dvipng: no

           ghostscript: no

                 latex: no

               pdftops: no

============================================================================

                        * The following required packages can not be built:

                        * freetype

----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in /private/var/folders/jj/0w0dd3n16jq4g5579g6c7h040000gn/T/pip_build_mc/matplotlib
Storing debug log for failure in /Users/mc/.pip/pip.log

I have followed the instructions here and here but it still doesn't work.  This is a clean system install and I just installed Python with brew as well.

A:

I had to install pkg-config with brew to fix it
    brew install freetype
    brew install pkg-config

'brew list' now reports:
    freetype    libpng      pkg-config

A:

Use home-brew python to install Matplotlib.  That finally fixed it for me:
brew tap Homebrew/python  # installs the Homebrew/python "tap"
brew install matplotlib   # install matplotlib with homebrew

More info here: https://github.com/Homebrew/homebrew-python


Q:

Set custom headers for websocket handshake in .NET 4.5

I'm trying to set a WebSocket connection of C# client with third-party server. When I connect with JS client to the same server, it establishes connection and everything goes fine. C# client connects to the server, but for some unknown reason server responds with 500 code. Debugging with WireShark has shown that HTTP handshake phase of WebSocket connection differs between client implementation in a set of headers. I would like to tweak the headers default System.Net.WebSockets.ClientWebSocket class sends to the server to check that the issue is there. Though, I couldn't find a way to do that.
How do I instruct ClientWebSocket of some other class in that namespace to send additional given headers in handshake phase?

A:

It looks like this is exposed by ClientWebSocketOptions.SetRequestHeader, so:
obj.Options.SetRequestHeader("foo", "bar");

should work. This also provides access to AddSubProtocol(...).


Q:

Business layer in an asp.net application

Suppose you have a web application where based on some numbers the user has entered you give him another number (over simplified) when he/she clicks a button. All the data is stored in SQL server. Now I can get all the required data to the Business access layer and do the calculation there. Or do the calculation in the database stored proc and send the result to the application. I strongly prefer the latter,because I find it much easier. But some people may argue all the business logic must lie in business layer in the app. I feel if there is any business logic in the app, it belongs in business layer. But you don't have to have the data related business logic in the app.
What would the experts recommend?

A:

If I might rephrase your question, I think you're asking, "Should I put my business logic in tsql or c#?"
Personally, I would strongly recommend c# (or vb.net if that's what you're using). As a programming tool, it gives you so much more power than tsql. And when I say power, I mean power to write easy to understand, logical, well organized self documenting code, that, more importantly, is easy to maintain. Object oriented techniques like abstract classes and interfaces allow you to create not only reusable pieces of code, but allow you to enforce business logic that is easily traceable. This can be simulated with stored procs, but you end up jumping through hoops to implement it, and then trace it when there are issues.
Code repositories are also built to integrate with VS much more easily than SQLserver, and change management, or even local dev environment upkeep becomes more difficult when things are centered on a database that is too large to run locally as opposed to updating a developers local working copy of c# code.
Of course, in a single developer scenario, when no one else will ever work on this app, collaboration and change management considerations pale in comparison to the developer's comfort with tsql vs any other tool.
And finally, just because c# provides rich language features, not everyone uses them. I can (and have!!) write a 1000 line c# method just as easily as I can write a 1000 line stored proc.
Hope this helps,
Lawrence


Q:

Proofs of The Fundamental Theorem of Symmetric Polynomials

I have been considering a few proofs of this theorem, and I noticed that a few of them (for example Proof 1, and Proof 2) prove the theorem first for homogeneous symmetric polynomials and then generalise it. However I have seen other proofs which don't seem to require this step (e.g. Proof 3) and it seems to me superfluous.
Could anyone explain why so many proofs include this step and/or if it is necessary?

A:

As you observe regarding "Proof 3", the lexicographic order proof (which goes back to Gauss and may be the earliest clean, clear proof of this theorem), there is no need to reduce to the homogeneous case to prove the theorem. The lex-order algorithm operates happily on any symmetric polynomial, homogeneous or not. There are many other proofs that also avoid this reduction. In fact, as you correctly sense, both your other linked proofs ("Proof 1" at PlanetMath, which is really the same lex-order proof, and "Proof 2" at Wikipedia, which I first encountered in the algebra textbooks by Serge Lang and Michael Artin) can be easily rewritten without this assumption. The theorem can also be proven non-constructively from Galois theory (as is done e.g. in the textbook by Hungerford), and in such a proof it would be kind of ridiculous to bother with the assumption of homogeneity.
However, when one wants in practice to represent a symmetric polynomial in terms of the elementary ones, one does in fact always end up working separately on each homogeneous component, for the simple reason that the elementary symmetric polynomials are themselves homogeneous. So while the reduction to the homogeneous case can be eliminated to make the exposition of the proof more economical, it cannot be eliminated from the actual calculation of a representation (of a symmetric polynomial in terms of the elementary ones).
Thus, to the constructively-minded, there is no real loss of efficiency in a proof that reduces to the homogeneous case first. If the proof is at all constructive (as are all the proofs you link), rigging it to avoid this step could be seen as a kind of deception, since when you unpack the calculations behind the proof, you must work separately on each homogeneous component. I'm guessing that's why those proofs are written that way.


Q:

How to compare one file's data to other file's data using python?

I have 90 files in csv format which have data like this-
    PID,          STARTED,%CPU,%MEM,COMMAND
    1,Wed Sep 12 10:10:21 2018, 0.0, 0.0,init
    2,Wed Sep 12 10:10:21 2018, 0.0, 0.0,kthreadd

Now I have to compare in such a way that whether file2 has any repeting data(PID,STARTED,%CPU,%MEM,COMMAND)with file1 or not.
If file2 has repeated data then pick the repeated data with all values(PID,COMMAND,STARTED,%CPU,%MEM) and store it in a seperate files.
Same explained process I have to do with all 90 files.
My code(Approach) is here. Please have a look -
file=open(r"Latest_27_02_2019.csv","r")
pidList=[]
pNameList=[]
memList=[]
startTimeList=[]
df=pd.read_csv(file)
pidList=df.index
df.columns = df.columns.str.strip()
pidList = df['PID']
pNameList=df['COMMAND']
memList=df['%MEM']
startTimeList=df['STARTED']
After that compare one by one.

But since I have large number files. So it will take more time and more iteration.
Somehow I have found that it can be do in easier way with help of python(pandas library) but don't know how? Please help me?

A:

here is the solution for comparing 2 files:
#read file1 to df1
#your header seems no good with blank, so i rename it
df1 = pd.read_csv('file1',  sep=',' header=1, names=['PID','STARTED','%CPU','%MEM','COMMAND']])
#df1 is your first file, df2 the second
df_compare = df1.merge(df2.drop_duplicates(), on=['PID','STARTED','%CPU','%MEM','COMMAND'],
                   how='right', indicator=True)

print(df_compare)

#in result, you'll have a column '_merge' with both or right_only
#right_only means only in df2 and not in df1
#after you just filtered:

filter = df_compare._merge == 'both'
df_compare = df_compare[filter].drop(['_merge'],axis=1)

#in df_compare, you have the repeateted rows from df2 and df1, you could reindex if you want
print(df_compare)

or another solution (better i think):
df_compare = df1[df1.index.isin(df1.merge(df2, how='inner', on=['PID','STARTED','%CPU','%MEM','COMMAND']).index)]
print(df_compare)


Q:

Why "__getattr__" does not work in python "ctypes"?

I stop it in the example of "datetime", is rewritten in a real example of lxml.
(It may be strange because English is translated in Google Translate is my statement I'm sorry.)

It is thought that I like lxml from very good performance, but the source is hard to read.
If you are actively using the XML, I do frequently can also be modified code of python.
Time has passed since forgotten, source because very difficult to understand,
I have taken the time to debug and fix.
For example, I think usually when you search as follows: deep XML hierarchy.
elem = lxml.etree.parse ("xxx/xxx/sample.xml").getroot()

elem.xpath("//depth3/text()")[0]

elem.find("./depth1/depth2/depth3").get("attr1").text

I wanted to use as follows.
(Use this code it's just me.)
elem.depth3.text (Ex.1)
OR
elem.depth1.depth2.depth3.text (Ex.2)

I tried the class inheritance is first to implement this.
You have customized a little bit by referring to the "Using custom Element classes in lxml".
I used the __getattr__ in order to search an XML element.
from lxml import etree
class CustomElement (etree.ElementBase):
    def __ getattr__ (self, k):
        ret = self.xpath ("/ /" + k)
        setattr(self, k, ret)
        return getattr(self, k)

Example of (Ex.1) to succeed.
But the example of (Ex.2) becomes Attribute Error __getattr__ is not present in the instance of the return of etree._Element depth1.

Although not (supplemental) practical, but I used an example of adding a "millisecond" of "datetime" in the first question from Easy to understand.

It was thought then it was a way to add functions to the Element class of lxml using the ctypes module.
import ctypes
import lxml.etree

class PyObject_HEAD(ctypes.Structure):
    _fields_ = [
        ('HEAD', ctypes.c_ubyte * (object.__basicsize__ -
                           ctypes.sizeof(ctypes.c_void_p))),
        ('ob_type', ctypes.c_void_p)
    ]
def __getattr__(self, k):
    ret = self.xpath("//" + k)
    setattr(self, k, ret)
    return getattr(self, k)

_get_dict          = ctypes.pythonapi._PyObject_GetDictPtr
_get_dict.restype  = ctypes.POINTER(ctypes.py_object)
_get_dict.argtypes = [ctypes.py_object]

EE = _get_dict(lxml.etree._Element).contents.value
EE["__getattr__"] = __getattr__

elem = lxml.etree.parse("xxx/xxx/sample.xml").getroot()
elem.xpath("//depth3")[0]

=> Return _Element object
from ispect import getsource
print getsource(elem.__getattr__)

=>def __getattr__(self, k):
=>    ret = self.xpath("//" + k)
=>    setattr(self, k, ret)
=>    return getattr(self, k)
sources is added..
elem.depth3

=> AttributeError .. no attribute 'depth3'

I do not know if or should I write how using the "PyObject_GetAttr".
Please tell me if.
Best regards
====================Previous Question===================================
I'm trying to enhancements in ctypes.
Add function usually go well.
However, it does not work if you add a special method and Why?
import ctypes as c

class PyObject_HEAD(c.Structure):
    _fields_ = [
        ('HEAD', c.c_ubyte * (object.__basicsize__ -
                              c.sizeof(c.c_void_p))),
        ('ob_type', c.c_void_p)
    ]

pgd = c.pythonapi._PyObject_GetDictPtr
pgd.restype = c.POINTER(c.py_object)
pgd.argtypes = [c.py_object]

import datetime

def millisecond(td):
    return (td.microsecond / 1000)

d = pgd(datetime.datetime)[0]
d["millisecond"] = millisecond

now = datetime.datetime.now()
print now.millisecond(), now.microsecond

This prints 155 155958, Ok!
def __getattr__(self, k):
    return self, k

d["__getattr__"] = __getattr__

now = datetime.datetime
print now.hoge

This doesn't work, why?
Traceback (most recent call last):
  File "xxxtmp.py", line 31, in <module>
    print now.hoge
AttributeError: type object 'datetime.datetime' has no attribute 'hoge'

A:

PyObject_GetAttr (Objects/object.c) uses the type's tp_getattro slot, or tp_getattr if the former isn't defined. It doesn't look up __getattribute__ in the MRO of the type.
For a custom __getattr__ you'll need to subclass datetime. Your heap type will use slot_tp_getattr_hook (Objects/typeobject.c) as its tp_getattro. This function will look for __getattribute__ and __getattr__ in the type's MRO by calling _PyType_Lookup (Objects/typeobject.c).

Given your update, see "using custom Element classes in lxml". For multiple results I've hacked a __getattr__ hook that uses a suffix notation for the index. It defaults to index 0 otherwise. Admittedly I haven't given it much thought, but clashes with existing names can be avoided if you always use the index.
from lxml import etree

def make_parser(element):
    lookup = etree.ElementDefaultClassLookup(element=element)
    parser = etree.XMLParser()
    parser.setElementClassLookup(lookup)
    return parser

class CustomElement(etree.ElementBase):
    def __getattr__(self, attr):
        try:
            name, index = attr.rsplit('_', 1)
            index = int(index)
        except ValueError:
            name = attr
            index = 0
        return self.xpath(name)[index]

parser = make_parser(CustomElement)

For example:
>>> spam = etree.fromstring(r'''
... <spam>
...     <foo>
...         <bar>eggs00</bar>
...         <bar>eggs01</bar>
...     </foo>
...     <foo>
...         <bar>eggs10</bar>
...         <bar>eggs11</bar>
...     </foo>
... </spam>
... ''', parser)

>>> spam.foo_0.bar_0.text
'eggs00'
>>> spam.foo_0.bar_1.text
'eggs01'
>>> spam.foo_1.bar_0.text
'eggs10'
>>> spam.foo_1.bar_1.text
'eggs11'


Q:

Referenced Nuget DLL Not Found Working Visual Studio

I added a Nuget library called Mpir.Net, which specializes in manipulating gigantic numbers much faster than the in-built BigInteger class does. When I added it in, Visual Studio 2017 was able to find the DLL, add it into my references, and provide suggestions based on the variables and functions defined in the DLL. Visual Studio was clearly able to find the DLL, unlike many questions on here from people with similar problems.
The problem is that when I run the program, it says xmpir64.dll not found, even though Visual Studio can reference things inside it in the code editor.
I've tried changing the target .NET version to no avail. What is the problem?
As a side note, I'm very new to C# and Visual Studio, so please keep that in mind when answering. Here is a link to a picture of my solution explorer.

A:

Mpir.Net is a wrapper around an unmanaged library (GMP). When it says it's unable to find the DLL, it's because it's looking for the unmanaged one (xmpir64.dll) which is in your project folder (not the managed one in the references, which is the wrapper).
You probably just need to click on xmpir64.dll (and the x32 one too), look at its properties in the bottom right, and ensure copy to output directory is set to "copy always".
As a side note, Mpir.NET does not dispose of its unmanaged resources correctly, so don't be surprised if you have a big memory leak. I don't think I'd use it for commercial code.


Q:

Unwrapping error connecting UITbale view to firebase real time database

I am truing to get a UITableview to read video from firebase database.
I have connected to firebase data base. set up my data base as shown:

I set up a structure and linked and have the videos linked to it.
The app reads the database title fine but when i go to click on the individual cells that link directly to the videos i am getting an unwrapping error.

So the table view is populated with the title video 1 and video 2 but for some reason these cells arent reading the link to the video file stored in firebase.
The structure I set up is:

The code in the viewcontroller.swift is:
import UIKit
import Firebase
import FirebaseDatabase
import AVKit
import AVFoundation
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
 var table = [Videos]()
var ref: DatabaseReference!

@IBOutlet weak var Tableview: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    ref = Database.database().reference().child("videos")
    ref.observe(DataEventType.value, with: {(snapshot) in
        if snapshot.childrenCount > 0 {
            self.table.removeAll()

            for video in snapshot.children.allObjects as! [DataSnapshot] {

                let Object = video.value as? [String: AnyObject]
                let Title =  Object?["Title"]
                let videolink = Object?["link"]

                let video = Videos(Title: Title as? String, link: video as? String)
                self.table.append(video)

                self.Tableview.reloadData()
            }
        }
    })
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return table.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = Tableview.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
    let video: Videos
    video = table[indexPath.row]
    cell.titleLabel.text = video.Title
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    guard let videoURL = URL(string: table[indexPath.row].link!) else {
        return
    }

    let player = AVPlayer(url: videoURL)

    let controller = AVPlayerViewController()
    controller.player = player

    present(controller, animated: true) {
        player.play()
    }
}
}

The only other thing I have is a TableViewCell.swift file:

its a fairly simple project but I am stuck somehow. if anyone can see where i am going wrong that would be great.
Thanks.

A:

I think the problem is at this line:
let video = Videos(Title: Title as? String, link: video as? String)

It should be:
let video = Videos(Title: Title as? String, link: videolink as? String)

Hope this helps.


Q:

Kontsevich's formality theorem from an explicit homotopy

Suppose that $X$ is a smooth manifold, whose $C^{\infty}$-functions we denote by $A$.  Let $D_{poly}^*(A):=\bigoplus_{n\geq -1}Hom(A^{\otimes n+1},A)$ be the Lie algebra of polydifferential operators with the Hochschild differential and the Gerstenhaber bracket.  A version of the Hochschild-Kostant-Rosenberg theorem shows the cohomology of $D_{poly}^*(A)$ is isomorphic to $\bigoplus_{n\geq -1}\wedge^{n+1}T_X$, polyvector fields.  The graded vector space of polyvector fields is also a Lie algebra with the Schouten-Nijenhius bracket.  However, the HKR-isomorphism is not a morphism of Lie algebras.  The formality theorem of Kontsevich shows the HKR-isomorphism can be corrected to an $L_{\infty}$-morphism whose first term is the HKR-isomorphism.  The upshot is this proves star-products on $C^{\infty}(X)$ correspond to formal Poisson structures.
In the article: M. de Wilde and P. B. A Lecomte: An homotopy formula for the Hochschild cohomology, Compositio Mathematica, tome 96, no. 1 (1995), the authors construct an explicit homotopy for the HKR-isomorphism.  From this explicit homotopy the authors construct a star-product on $\frak g^*$, the dual of the Lie algebra $\frak g$.  My question is the following: can one do the same thing for the general case of a Poisson manifold.  In particular, is the explicit homotopy which induces Kontsevich's $L_{\infty}$-quasiisomorphism known?  I believe that one has to exist since two $L_{\infty}$-algebras are quasiisomorphic if and only if they are homotopy equivalent. But, can you write down the explicit homotopy from the quasiisomorphism.

A:

The only way I know to construct a formality quasi-morphism for poy-vector fields out of an homotopy is via Tamarkins approach (i.e. $G_\infty$-formality). What Tamrakin does is

prove that there is a suitable $G_\infty$-structure on Hochschild cochains
prove that the obstruction to construct a $G_\infty$-formality step by step is unobstructed. At each step you have to make some choice, and the homotopy for the Hochschild complex of De Wilde-Lecomte gives you a way to do such choices.

But Tamarkin construction (part 1) involves the choice of an associator (i.e. choice of appropriate weights in Kontsevich's $L_\infty$-qausi-isomorphism)... so I think that this is hopeless to construct the formality out of an homotopy.
Moreover, even the other way I don't see how you could associate an homotopy for the Hochschild complex to an $L_\infty$-quasi-isomorphism from $T_{poly}$ to $D_{poly}$.
I might be wrong but I have the feeling that you are mixing two different notions of homotopy: that of higher homotopies in the $L_\infty$-morphism, and that of homotopy retract for the Hochschild cochain complex. In particular, what do you mean by a "homotopy equivalence" between $L_\infty$-algebras (whatever you mean, a homotopy for the Hochschild complex in the sens of De Wilde-Lecomte won't produce an example).


Q:

Plotting $\omega(k_x, k_z)$ in $(\omega, k)$ plane with assumption of $k^2 = k_x^2 + k_z^2$

I'm currently studying atmospheric-gravity waves and their dispersion relations.
For analysis I need to plot the dispersion function:
\begin{equation}
    \omega^4 - \omega^2\cdot C_s^2(k_x^2 + k_z^2 + \dfrac{1}{4H^2}) + (\gamma - 1)g^2\cdot k_x^2 = 0
\end{equation}
where, $C_s^2$, $H$, $\gamma$ and $g$ are some constant values.
I used Solve to get $\omega$ as a function of $k_x^2$ and $k_z^2$ - $\omega = \omega(k_x^2, k_z^2)$.
Code for solving:
   Solve[ω^4 - ω^2*(Subscript[k, x]^2 +
        Subscript[k, z]^2 + 1/(4*H^2)) + (γ - 1)*g^2*Subscript[k, x]^2 == 0, ω]

What I want:
Plot[f, {k, 0, 20}]

where f is any solution of Solve. It plot nothing, because Mathematica didn't know about $k^2 = k_x^2 + k_z^2$ relation.

A:

I'm pretty unsure about this, because I don't know much about manifolds and other difficult words. So I hope I learn something here too.
I use your equation with all parameters set to simple values as Chris did
eqn = w^4 - w^2 ((kx^2 + kz^2) + 1/4) + 2 kx^2 == 0;

Your second equation k^2==kx^2+kz^2 defines a tube with different radii k. We could for instance look at both equations and choose k==3
contPlot = ContourPlot3D[{w^4 - w^2 ((kx^2 + kz^2) + 1/4) + 2 kx^2 == 0,
   kx^2 + kz^2 == 9}, {kx, -5, 5}, {w, -5, 5}, {kz, -5, 5},
  ContourStyle -> {Directive[Opacity[0.3], Red], Automatic}]

We are interested in the intersection of both contours. What we can do here, is to parametrize k^2==kx^2+kz^2 differently. A tube along w with radius k can expressed as the parametric equation
$$f(w,\phi)=\{k \cos(\phi), w,k \sin(\phi)\}$$
therefore we define a transformation rule
rule = Thread[{kx, w, kz} :> {k*Cos[phi], w, k*Sin[phi]}]

(* {kx :> k Cos[phi], w :> w, kz :> k Sin[phi]} *)

We can now apply this transformation and solve your initial equation for w. With this we get solutions for w which only depend on phi and k. With those solutions, we have an explicit parametrization of the curve in 3d
sol = Solve[eqn /. rule, w];
paramPlot =
 ParametricPlot3D[{kx, w, kz} /. rule /. sol /. k :> 3, {phi, 0,
    2 Pi}, PlotStyle -> Red] /. Line[pts_] :> Tube[pts, 0.1]

And we can of course combine them to see whether it fits with our imagination
Show[{contPlot, paramPlot}]

What you want to have now is a plot where on the first axis is k and on the second w
ParametricPlot[Evaluate[{k, w} /. sol], {k, 0, 9}, {phi, -Pi, Pi}]

A:

Let's give ad hoc values to your physical parameters
eqn = ω^4 - ω^2 ((kx^2 + kz^2) + 1/4) + 2 kx^2

Let's now apply the extra condition on the modulus of $k$
eqn= eqn /. kz -> Sqrt[k^2 - kx^2];

then we can find zeros of the dispersion relation at fixed kx
 Table[ContourPlot[
 eqn == 0 /. kx -> i/4 // Release, {ω, 0, 2}, {k, 0, 2},
 ContourStyle -> ColorData[10][i],
 RegionFunction -> Function[{k, ω}, k > i/4],
 FrameLabel -> {k, ω}], {i, 1, 4}] // Show

which produces

where I have added a cut to impose k>kx as suggested by Rahul Narain.
Alternatively, following more closely his strategy (i.e. proceed at fixed angle between 'kx' and 'ky')
 eqn = ω^4 - ω^2 ((kx^2 + kz^2) + 1/4) + 2 kx^2 /.
 kx -> k Cos[θ] /. kz -> k Sin[θ]
 Table[ContourPlot[eqn == 0 /.θ-> Pi i/8 // Release,
 {ω, 0, 2}, {k, 0,2}, ContourStyle -> ColorData[10][i],
 FrameLabel -> {k, ω}], {i, 1, 8}] // Show


Q:

Using MPICH with Boost.MPI on Ubuntu

I was trying to use boost.mpi under Ubuntu 12.04. apt-get will install openmpi, but some other software (involving torque) I run expect mpich2/mpich, and complain that
"mpdstartup: Command not found"
I certainly don't want to mess with changing the software to use openmpi and worry about migration issues when the software is upgraded.
My question is, is there a user-friendly way to install boost.mpi + mpich2 in Ubuntu (12.04 LTS)? (e.g. an unofficial repository). In the worst-case, if I have to build boost from source, is there a user-friendly way to uninstall a boost installation when I upgrade to a new boost version? I liked the fact that apt-get will install files and links to well-known locations and do a clean remove when asked to.
BTW, I have tried apt-get installing mpich2 first and then libboost-mpi-dev, but apt-get still installs openmpi even though there is a working mpi implementation. This seems to be somewhat constraining.
Thanks,

A:

There's no way to avoid installing openmpi due to the package dependencies. But if you have both openmpi and mpich2 installed, you can use the Debian alternatives system to make mpich2 the preferred mpi on your system. To do this, run:
 sudo update-alternatives --set mpi /usr/include/mpich2


Q:

Remove data from column using data from another file and deleting the row

I have several files:
file 1:
1    2    3     4  5     6
ALA, 002, 2fv9, H, N,   O6
ALA, 002, 2fv9, N, CA,   C20
ALA, 002, 2fv9, N, CA,   O6
ALA, 002, 2fv9, N, N,   O6
ALA, 00G, 3fuj, N, CB,   C2
ALA, 00G, 3fuj, N, CB,   C3
ALA, 00G, 3fuj, N, N,   O10
ALA, 010, 4ii8, N, C,   C1
ALA, 010, 4ii8, N, O,   C

file 2:
003
00G
010
017

I tried to delete lines from file 1 using file 2 with grep:
grep -vif file2 file1 >outputFile

But because sometimes values in column 6 may be similar with the values in column 2, the file wasn't cleaned up the way I wanted it to be cleaned. How can I delete the rows by comparing the values of column 2 in file 1 with the values in file2?
I have also found such a solution for   awk, but it is not useful in my case (file 2 contains about 3000 values):
awk -F, '$2 == anyValue' yourFileToFilter

Is there any way to modify the command? Or any other solution?
UPDATE
I have also found this solution and it seemed to be quite similar to what I needed but it didn't work.
$ awk -F, 'NR==FNR{a[$1];next}!($2 in a)' file2 file1 > file3

But the output of file3 looks like that:
1    2    3     4  5     6
ALA, 002, 2fv9, H, N,   O6
ALA, 002, 2fv9, N, CA,   C20
ALA, 002, 2fv9, N, CA,   O6
ALA, 002, 2fv9, N, N,   O6
ALA, 00G, 3fuj, N, CB,   C2
ALA, 00G, 3fuj, N, CB,   C3
ALA, 00G, 3fuj, N, N,   O10
ALA, 010, 4ii8, N, C,   C1
ALA, 010, 4ii8, N, O,   C

UPDATE:
I have just removed all the spaces from file, so now it looks like:
ALA,002,2fv9,H,N,O6
ALA,002,2fv9,N,CA,C20
ALA,002,2fv9,N,CA,O6
ALA,002,2fv9,N,N,O6
ALA,00G,3fuj,N,CB,C2
ALA,00G,3fuj,N,CB,C3
ALA,00G,3fuj,N,N,O10

And the output is still:
ALA,002,2fv9,H,N,O6
ALA,002,2fv9,N,CA,C20
ALA,002,2fv9,N,CA,O6
ALA,002,2fv9,N,N,O6
ALA,00G,3fuj,N,CB,C2
ALA,00G,3fuj,N,CB,C3
ALA,00G,3fuj,N,N,O10
ALA,010,4ii8,N,C,C1

A:

If your data contains spaces before the field itself, you can set the field separator to a space plus some spaces:
awk -F"[, ]+" 'FNR==NR {a[$0]=$0; next} !($2 in a)' f2 f1

For your updated input it returns:
$ awk -F"[, ]+" 'FNR==NR {a[$0]=$0; next} !($2 in a)' f2 f1
1    2    3     4  5     6
ALA, 002, 2fv9, H, N,   O6
ALA, 002, 2fv9, N, CA,   C20
ALA, 002, 2fv9, N, CA,   O6
ALA, 002, 2fv9, N, N,   O6


Q:

How to get the percentage of quantity inside the  tag?

I want to get the percentage of quantity per day. I'm using methods to get the sum of all the quantity. The problem when I combined it to distributed.Quantity like this {{distributed.Quantity / sumAllOfQuantity() * 100 | twoDecimal}}	. I get a NaN value. How can I compute the percentage of quantity per day.
HTML

     Avg. Qty / Day

 0">

     {{distributed.Quantity / sumAllOfQuantity() * 100 | twoDecimal}}

Methods
sumAllOfQuantity : function() {
    var sum = 0;
    for(var i = 0; i < this.distributed_per_day.length; i++) {
        sum += parseInt(this.distributed_per_day[i].Quantity);
    }
},

Filter
twoDecimal(value) {
   return value.toFixed(2);
}

A:

Your function sumAllOfQuantity is not returning a value you can either add return  sum on your function / add the parseInt to the distributed.Quantity on the template or use a computed property for the total quantity which i recommend rather than a method that gets called multiple times:
computed : {
  totalQuantity() {
    return this.distributed_per_day.reduce((acc,val)=> acc + parseInt(val.Quantity),0)
  }
}

   {{ parseInt(distributed.Quantity) / totalQuantity * 100 | twoDecimal}}


Q:

Python “NameError: Global name ”nameCheck“ is not defined.”

I am new to python and have been practicing on Classes and methods. When I ran the script containing the code below, I get the error "NameError: Global name "nameCheck" is not defined." How can I fix it? Thanks in advance.
class game(object):
    def play():
         name = input("What's your name, my friend? ")
         check = nameCheck(name)

         if check == 1:
             print ("Hello %r " %(name))
         else:
             print ("Sorry, I can't print your name because you don't have one!")

    def nameCheck(name):
         if name == "":
             print("I can't believe you have no name!")
             return 0

         else:
             print("%s is a nice name!" %name)
             return 1
game.play()

Python “NameError: Global name ”nameCheck“ is not defined.”

A:

Since the methods are in a class you need to give then the self attribute:
do this:
class game(object):
    def play(self):
         name = input("What's your name, my friend? ")
         check = self.nameCheck(name)

         if check == 1:
             print ("Hello %r " %(name))
         else:
             print ("Sorry, I can't print your name because you don't have one!")

    def nameCheck(self, name):
         if name == "":
             print("I can't believe you have no name!")
             return 0

         else:
             print("%s is a nice name!" %name)
             return 1
game = Game()
game.play()

the selfis a placeholder for the instance so you have to create an instance of the object by doing this game = game() then you can call any of the methods for that instance
now you can call the method from anywhere in the class and if you give then variables the self attribute they can also be access anywhere in the class
more on self


Q:

Is it possible to have Angular @HostListener('window:scroll',) in simple Service not Component or Directive

Is it possible to have Angular @HostListener('window:scroll',) in simple Service not Component or Directive code?
I don't want to polute any of my components, since the awareness of scroll should be injected in several other services... Currently i have following code that compiles, but does not work somehow.
import { Component, OnInit, Injectable, Inject, HostListener } from '@angular/core';
import { SearchService } from './search.service';
import { DOCUMENT } from '@angular/platform-browser';

const scrollStepToReload = 3700;

@Injectable()
export class ScrollWatcherService {

  private maxReachedScroll = 0;
  private lastLoadedAt = 0;

  constructor(private searchService: SearchService, @Inject(DOCUMENT) private document: any) { }

  @HostListener('window:scroll', ['$event'])
  onScroll($event) {

    const scrollOffset = window.pageYOffset || this.document.documentElement.scrollTop || this.document.body.scrollTop || 0;
    console.debug("Scroll Event", scrollOffset);

    if (scrollOffset > this.maxReachedScroll) {
      this.maxReachedScroll = scrollOffset;
    }
    if (this.lastLoadedAt + scrollStepToReload < this.maxReachedScroll) {

      this.lastLoadedAt = this.maxReachedScroll;
      this.searchService.continueSearch();

    }
  }
}

Similar code works i Component as desired.
Any ideas how to get it run in a service? or something similar?

A:

You cannot have a HostListener in a service. Use the classic:
window.addEventListener('scroll', () => {
        console.log('scrolling');
});


Q:

Unity - SetActive not defined

When using a script to hide and unhide specific sprites on the click of a button, I get these two errors.
Assets\Scripts\ButtonLeft.cs(26,5): error CS1061: 'int' does not contain a definition for 'SetActive' and no accessible extension method 'SetActive' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
Assets\Scripts\ButtonLeft.cs(22,8): error CS1061: 'int' does not contain a definition for 'activeSelf' and no accessible extension method 'activeSelf' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
I was assured by previous posts, some only dating back a few weeks, that activeSelf was the correct way to check whether a sprite was already hidden, and I have used SetActive before in this project with no issues. Here's the script I'm trying to run:
using System.Collections.Generic;
using UnityEngine;

public class ButtonLeft : MonoBehaviour
{

    public void Click ()
    {
    if (23.activeSelf)
    {
        23.SetActive (false);
        3.SetActive (true);
        1.SetActive (false);
    }
    if (3.activeSelf)
    {
        23.SetActive (false);
        3.SetActive (false);
        1.SetActive (true);
    }
    if (1.activeSelf)
    {
        23.SetActive (true);
        3.SetActive (false);
        1.SetActive (false);
    }
    }

    // Update is called once per frame
    void Update()
    {

    }
}

Is the syntax wrong in any way? Is activeSelf not the correct way to check whether an object is active or not?
Using Unity 2019.4.5f1 Personal

A:

The reason you're getting those error messages is due to running them on integers instead of sprites. You need to use an instance of a GameObject.
You can acquire a reference to something of that sort in several ways. One would be by making a field that's exposed to the inspector and providing the reference through there.
using UnityEngine;

public class ButtonLeft : MonoBehaviour
{
    [SerializeField]
    private SpriteRenderer sprite1 = null;

    [SerializeField]
    private SpriteRenderer sprite3 = null;

    [SerializeField]
    private SpriteRenderer sprite23 = null;

    public void Click()
    {
        if (sprite23.gameObject.activeSelf)
        {
            sprite23.gameObject.SetActive(false);
            sprite3.gameObject.SetActive(true);
            sprite1.gameObject.SetActive(false);
        }
        if (sprite3.gameObject.activeSelf)
        {
            sprite23.gameObject.SetActive(false);
            sprite3.gameObject.SetActive(false);
            sprite1.gameObject.SetActive(true);
        }
        if (sprite1.gameObject.activeSelf)
        {
            sprite23.gameObject.SetActive(true);
            sprite3.gameObject.SetActive(false);
            sprite1.gameObject.SetActive(false);
        }
    }
}

How things may end up looking in the editor:

If you want to be able to drag in any game object as a reference
using UnityEngine;

public class ButtonLeft : MonoBehaviour
{
    [SerializeField]
    private GameObject sprite1 = null;

    [SerializeField]
    private GameObject sprite3 = null;

    [SerializeField]
    private GameObject sprite23 = null;

    public void Click()
    {
        if (sprite23.activeSelf)
        {
            sprite23.SetActive(false);
            sprite3.SetActive(true);
            sprite1.SetActive(false);
        }
        if (sprite3.activeSelf)
        {
            sprite23.SetActive(false);
            sprite3.SetActive(false);
            sprite1.SetActive(true);
        }
        if (sprite1.activeSelf)
        {
            sprite23.SetActive(true);
            sprite3.SetActive(false);
            sprite1.SetActive(false);
        }
    }
}


Q:

CameraPreviewImageSource.StartPreviewAsync doesn't work with videoEncodingProperties

I'm using CameraPreviewImageSource.PreviewFrameAvailable event to determine flashes by calculating average luminosity of each frame.
For my purposes I don't need big frames, but with default settings StartPreviewAsync() method generates frames with size 1280*720px.
I tried to use StartPreviewAsync(videoEncodingProperties) but every time I get an exception HRESULT:0x80040155 Interface not registered.
I can set preview frame size through underlying VideoDeviceController object, but it looks overcomplicated a bit, especially concerning that I have to set properties in a magically determined sequence (otherway the camera will be broken after exiting from the app).

await App.CameraPreviewImageSource.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, _previewProperties);
var properties = await App.CameraPreviewImageSource.StartPreviewAsync();
properties.Width = _previewProperties.Width;
properties.Height = _previewProperties.Height;

Am I doing something wrong or StartPreviewAsync(videoEncodingProperties) method in SDK simply doesn't work at all?

A:

Well, "right" sequence of commands solves the problem:

var properties = await App.CameraPreviewImageSource.StartPreviewAsync();
await App.CameraPreviewImageSource.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, _previewProperties);
properties.Width = _previewProperties.Width;
properties.Height = _previewProperties.Height;


Q:

Unable to get vertical scroll bars in an WPF TextBlock

I'm presenting text in a wpf TextBlock control (.Net 3.5). The content of the textblock varies depending on what the user selects in a list box. The text wraps, so I don't need an horizontal scroll bar. However, there is often more text than the amount the window can display, so I need a vertical scroll bar.
As I started searching I quickly found that the answer is to wrap the TextBlock in a ScrollViewer. However, It Does Not Work (TM) and I'm hoping someone can help me work out why.
This is the structure of the UI code:
<Window x:Class=..>
    <StackPanel>
        <ListBox HorizontalAlignment="Stretch"
                 VerticalAlignment="Top"  Height="200"
                 SelectionChanged="listbox_changed" SelectionMode="Single">
        </ListBox>
        <Button Click="Select_clicked">Select</Button>
        <ScrollViewer VerticalScrollBarVisibility="Auto">
            <TextBlock Name="textblock" TextWrapping="Wrap"/>
        </ScrollViewer>
    </StackPanel>
</Window>

When the user selects an item in the list box, some text associated with this item is presented in the TextBlock. I would have thought that the code as it stands should have been all that's required, but it never provides me with a scroll bar.
Searching and experimenting have given me two clues: the root of the problem might be related to me updating the content of the TextBlock dynamically, and that the TextBlock does not resize itself based on the new content. I found a posting that seemed relevant that said that by setting the Height of the TextBlock to its ActualHeight (after having changed its content), it would work. But it didn't (I can see no effect of this).
Second, if I set the height (during design time) of the ScrollViewer, then I do get a vertical scroll bar. For instance, if I set it to 300 in the xaml above, the result is almost good in that the window as first opened contains a TextBlock with a vertical scroll bar when (and only when) I need it. But if I make the window larger (resizing it with the mouse during runtime), the ScrollViewer does not exploit the new window size and instead keeps its height as per the xaml which of course won't do.
Hopefully, I've just overlooked something obvious..
Thanks!

A:

Because your ScrollViewer is in a StackPanel it will be given as much vertical space as it needs to display it's content.
You would need to use a parent panel that restricts the vertical space, like DockPanel or Grid.
<DockPanel>
    <ListBox DockPanel.Dock="Top" HorizontalAlignment="Stretch"
             VerticalAlignment="Top"  Height="200"
             SelectionChanged="listbox_changed" SelectionMode="Single">
    </ListBox>
    <Button DockPanel.Dock="Top" Click="Select_clicked">Select</Button>
    <ScrollViewer VerticalScrollBarVisibility="Auto">
        <TextBlock Name="textblock" TextWrapping="Wrap"/>
    </ScrollViewer>
</DockPanel>


Q:

Is it possible to render MSAA to RGBA32F texture in WebGL2?

Firstly, I have msaa working good, like this(abstract):
    sceneFramebuffer = new MultisampleRenderbuffer({
        msaa: 8,
        internalFormat: "RGBA8"
    });

    blitFramebuffer = new Framebuffer({
        internalFormat: "RGBA8",
        format: "RGBA",
        type: "UNSIGNED_INT"
    });

   Draw scene with sceneFramebuffer;

   sceneFramebuffer.blit(blitFramebuffer);

   Draw blitFramebuffer on the screen quad;

Now, I want to render sceneFramebuffer to RGBA32F for HDR purpose, and when I try this configuration:
sceneFramebuffer = new MultisampleRenderbuffer({
    msaa: 8
    internalFormat: "RGBA32F"
});

blitFramebuffer = new Framebuffer({
    internalFormat: "RGBA32F",
    format: "RGBA",
    type: "FLOAT"
});

I get this:
GL ERROR :GL_INVALID_OPERATION : glBlitFramebufferCHROMIUM: src and dst formats differ for color
But, when I set msaa: 0 for sceneFramebuffer it shows my scene but no msaa antialiasing ofcourse.
Is it possible somehow to combine multisampling and float output, which I'd use for hdr?
Thanks!

A:

Seem to work for me

function main() {
  const gl = document.querySelector('canvas').getContext('webgl2');
  if (!gl) {
    return alert('need webgl2');
  }
  // without this we can't render to RGBA32F
  if (!gl.getExtension('EXT_color_buffer_float')) {
    return alert('need EXT_color_buffer_float');
  }
  // just guessing without this we can't downsample
  if (!gl.getExtension('OES_texture_float_linear')) {
    return alert('need OES_texture_float_linear');
  }

  const msFB = gl.createFramebuffer();
  gl.bindFramebuffer(gl.FRAMEBUFFER, msFB);
  const msRB = gl.createRenderbuffer();
  gl.bindRenderbuffer(gl.RENDERBUFFER, msRB);
  const samples = 4;
  const internalFormat = gl.RGBA32F;
  const width = 16;
  const height = 16;
  gl.renderbufferStorageMultisample(
     gl.RENDERBUFFER, samples, internalFormat, width, height);
  gl.framebufferRenderbuffer(
     gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msRB);
  checkFramebuffer(gl);

  gl.clearColor(1,0,0,1);
  gl.clear(gl.COLOR_BUFFER_BIT);

  const texFB = gl.createFramebuffer();
  gl.bindFramebuffer(gl.FRAMEBUFFER, texFB);
  const tex = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, tex);
  const levels = 1;
  gl.texStorage2D(gl.TEXTURE_2D, levels, internalFormat, width, height);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.framebufferTexture2D(
      gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);

  checkFramebuffer(gl);

  // check before
  checkPixel(gl, 'before blit')

  gl.bindFramebuffer(gl.READ_FRAMEBUFFER, msFB);
  gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texFB);
  gl.blitFramebuffer(
     0, 0, width, height,
     0, 0, width, height,
     gl.COLOR_BUFFER_BIT, gl.LINEAR);

  console.log('ERROR?:', glEnumToString(gl, gl.getError()));

  gl.bindFramebuffer(gl.FRAMEBUFFER, texFB);
  checkPixel(gl, 'after blit:');
}

function checkFramebuffer(gl) {
  const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  if (status !== gl.FRAMEBUFFER_COMPLETE) {
    console.error(glEnumToString(gl, status));
  }
}

function checkPixel(gl, msg) {
  const pixel = new Float32Array(4);
  gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.FLOAT, pixel);
  console.log(msg, Array.from(pixel).join(', '));
}

function glEnumToString(gl, v) {
  const hits = [];
  for (const key in gl) {
    if (gl[key] === v) {
      hits.push(key);
    }
  }
  return hits.length ? hits.join(' | ') : `0x${v.toString(16)}`;
}

main();
<canvas></canvas>

Just to make it clear it has nothing to do with texStorage2D

function main() {
  const gl = document.querySelector('canvas').getContext('webgl2');
  if (!gl) {
    return alert('need webgl2');
  }
  // without this we can't render to RGBA32F
  if (!gl.getExtension('EXT_color_buffer_float')) {
    return alert('need EXT_color_buffer_float');
  }
  // just guessing without this we can't downsample
  if (!gl.getExtension('OES_texture_float_linear')) {
    return alert('need OES_texture_float_linear');
  }

  const msFB = gl.createFramebuffer();
  gl.bindFramebuffer(gl.FRAMEBUFFER, msFB);
  const msRB = gl.createRenderbuffer();
  gl.bindRenderbuffer(gl.RENDERBUFFER, msRB);
  const samples = 4;
  const internalFormat = gl.RGBA32F;
  const width = 16;
  const height = 16;
  gl.renderbufferStorageMultisample(
     gl.RENDERBUFFER, samples, internalFormat, width, height);
  gl.framebufferRenderbuffer(
     gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msRB);
  checkFramebuffer(gl);

  gl.clearColor(1,0,0,1);
  gl.clear(gl.COLOR_BUFFER_BIT);

  const texFB = gl.createFramebuffer();
  gl.bindFramebuffer(gl.FRAMEBUFFER, texFB);
  const tex = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, tex);
  const level = 0;
  gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, width, height, 0,
                gl.RGBA, gl.FLOAT, null);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.framebufferTexture2D(
      gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);

  checkFramebuffer(gl);

  // check before
  checkPixel(gl, 'before blit')

  gl.bindFramebuffer(gl.READ_FRAMEBUFFER, msFB);
  gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texFB);
  gl.blitFramebuffer(
     0, 0, width, height,
     0, 0, width, height,
     gl.COLOR_BUFFER_BIT, gl.LINEAR);

  console.log('ERROR?:', glEnumToString(gl, gl.getError()));

  gl.bindFramebuffer(gl.FRAMEBUFFER, texFB);
  checkPixel(gl, 'after blit:');
}

function checkFramebuffer(gl) {
  const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  if (status !== gl.FRAMEBUFFER_COMPLETE) {
    console.error(glEnumToString(gl, status));
  }
}

function checkPixel(gl, msg) {
  const pixel = new Float32Array(4);
  gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.FLOAT, pixel);
  console.log(msg, Array.from(pixel).join(', '));
}

function glEnumToString(gl, v) {
  const hits = [];
  for (const key in gl) {
    if (gl[key] === v) {
      hits.push(key);
    }
  }
  return hits.length ? hits.join(' | ') : `0x${v.toString(16)}`;
}

main();
<canvas></canvas>


Q:

ASP.Net MVC and IIS 7 using Virtual Directory to a config file

I have an MVC application that is shared by many websites in IIS, but each needs it's own app settings.  In my Web.Config, I have the following:
<appSettings file="Config/AppSettings.config" />

Then, in IIS I set up virtual directories for each site's separate file.
To my astonishment, this did not work, but did when I tried it without using a virtual directory.  Any ideas?
I saw this post IIS Config file in virtual directory
which was very similar, but did not offer the response I was looking for.
I'm also open to other ways to accomplish the same thing; if such a solution exists.

A:

It's not possible to use a virtual directory (or even files outside of the current website; only the current folder, or a sub-folder) in 'appSettings file=...'.
One possible way to share setting across projects would be to do it at build-time - either by coping it in, or using a Linked File in VS to have it copied to the folder on publish.
If you really need this functionality on the server, you could try (though I can't say how well it would work) a Junction.


Q:

What are the advantages/disadvantages on passing arguments to the AsyncTask constructor?

I am using AsyncTask and wondering what are the implications of passing the arguments to the constructor instead of passing them directly on the execute() call to the doInBackground(...) method, for example:
Call:
new SomeTask(bitmap, integer, "somestring").execute();

Class:
public class SomeTask extends AsyncTask<Void, Void, String> {
private String string;
private Bitmap image;
private int integer;

public SomeTask (Bitmap bmp, int someint, String s){
    this.image = bmp;
    this.string = s;
    this.integer = someint;
}

protected String doInBackground(Void... params) {
    // whatever
    return "string";
}

@Override
protected void onPostExecute(String result){
    // whatever
}

}
What are the advantages/disadvantages regarding design, elegance, reuse and performance?
Thank you.

A:

What are the advantages/disadvantages regarding design, ellegance, reuse and performance??

Use parameters to execute() if you will have an arbitrary number of the same type (e.g., several URLs as Strings that you want the task to download).
Use constructor parameters if you will have several parameters of distinct types, so you can take advantage of Java's compile-time type safety.
If you will have just one object to pass in (or none), both approaches are pretty much equivalent.


Q:

Python callable() built-in function returns false for an instance method

I am using Python version 3.6.
class Pen:
    def write(self):
        print("Writing")

def __call__(self,p):
    print("calling a pen object")

pen1 = Pen()

print(callable(pen1.write()))

The above Python example returns the following output
Writing
False

Why this behaviour?
Is an instance method not a callable in Python?

A:

pen1.write is callable, but not the results pen1.write(). This will call the method and pass its results (None) to the callable method as the argument. None is not callable.
Try:
print(callable(pen1.write))


Q:

Parent and Child Shell Script Problem

I have two scripts parent.sh and child.sh. There is a variable in parent.sh which needs to be accessed by the child process. I have achieved this by exporting the variable in the parent script and the variable is available to the child process?
Is there any way that child can modify the value of the export variable defined in parent shell?
Parent.sh
#!/bin/bash
export g_var=2
./child.sh

child.sh
#!/bin/bash
g_var=`expr $g_var + 1 `   #This modification is available in child shell only.

A:

Most shells support the source built-in, which executes a script in the current shell rather than spawning a new one. In bash and a few others, the command . is equivalent to source. I haven't read it, but the POSIX shell standard might require the two to be equivalent. Try:
#!/bin/bash
export g_var=2
. ./child.sh

"child.sh" is the same as your example.


Q:

Calling multiple sub-processes sequentially

I need to be able to call a bash command every few milliseconds and I am trying to use the sub-process to do so. I currently use:
p = subprocess.Popen(command, universal_newlines=True, cwd=CurrentWorkingDirectory ,shell=True, stdout=subprocess.PIPE)

and have a timer firing the command at the times needed.
My question is, if I am calling these commands through the use of subprocess.Popen, will this be opening new terminals to run each command? I want to make sure I don't run into any memory usage issues as I will be calling thousands of these commands.
What is the best way to go about this?

A:

Whatever you do, there are probably better alternatives than starting a thousand of processes in a minute whether you run out of memory or not.
To run subprocesses sequentially, use subprocess.check_call instead of subprocess.Popen.

will this be opening new terminals to run each command?

No, unless the command itself starts a new terminal.


Q:

Practical way to find out if SMS has been sent

I am interested in how I can figure out if SMS has been sent from the device.
In order to get notification when SMS is recieved, we use a broadcaster with:
android.provider.Telephony.SMS_RECEIVED

Important to mention that I do not send SMS from my app, I just should listen when SMS is sent from the device.
May be I should listen to some Content provider (which somehow related with SMS) and react for that change. Any ideas how I can achieve that?

A:

Yes, It is possible to listen SMS ContentProvider by using ContentObserver
Here is my example for Outgoing SMS:
First register a ContetObserver with content://sms/
   public class Smssendservice extends Service{

       @Override
       public void onCreate() {
            SmsContent content = new SmsContent(new Handler());
            // REGISTER ContetObserver
            this.getContentResolver().
                registerContentObserver(Uri.parse("content://sms/"), true, SMSObserver);
       }

       @Override
       public IBinder onBind(Intent arg0) {
            // TODO Auto-generated method stub

            return null;
       }

SMSObserver.class
       public class SMSObserver extends ContentObserver {
            private Handler m_handler = null;

            public SMSObserver(SMSLogger handler){
                 super(handler);
                 m_handler = handler;
            }

            @Override
            public void onChange(boolean selfChange) {
            super.onChange(bSelfChange);
            Uri uriSMSURI = Uri.parse("content://sms");

            Cursor cur = this.getContentResolver().query(uriSMSURI, null, null,
                 null, null);
            cur.moveToNext();

            String protocol = cur.getString(cur.getColumnIndex("protocol"));

            if(protocol == null) {
         //the message is sent out just now
            }
            else {
                 //the message is received just now
            }
      }
  }

}

A:

use the following method to send sms as well as check whether the sms get delivered or not.
send.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String phoneNo = "Phone number to sent";
                String message = "Your message";
                if (phoneNo.length() > 0 && message.length() > 0) {
                    TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                    int simState = telMgr.getSimState();
                    switch (simState) {
                    case TelephonyManager.SIM_STATE_ABSENT:
                        displayAlert();
                        break;
                    case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
                        // do something
                        break;
                    case TelephonyManager.SIM_STATE_PIN_REQUIRED:
                        // do something
                        break;
                    case TelephonyManager.SIM_STATE_PUK_REQUIRED:
                        // do something
                        break;
                    case TelephonyManager.SIM_STATE_READY:
                        // do something
                        sendSMS(phoneNo, message); // method to send message
                        break;
                    case TelephonyManager.SIM_STATE_UNKNOWN:
                        // do something
                        break;
                    }

                } else {
                    Toast.makeText(getBaseContext(),
                            "Please enter both phone number and message.",
                            Toast.LENGTH_SHORT).show();
                }

            }

            private void displayAlert() {
                // TODO Auto-generated method stub

                new AlertDialog.Builder(YourActivity.this)
                        .setMessage("Sim card not available")
                        .setCancelable(false)
                        // .setIcon(R.drawable.alert)
                        .setPositiveButton("ok",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        Log.d("I am inside ok", "ok");
                                        dialog.cancel();
                                    }
                                })

                        .show();

            }

        });

            private void sendSMS(String phoneNumber, String message) {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(YourActivity.this, 0,
                new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(YourActivity.this,
                0, new Intent(DELIVERED), 0);

        // ---when the SMS has been sent---
        final String string = "deprecation";
        registerReceiver(new BroadcastReceiver() {

            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(YourActivity.this, "SMS sent",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(YourActivity.this, "Generic failure",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(YourActivity.this, "No service",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(YourActivity.this, "Null PDU",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(getBaseContext(), "Radio off",
                            Toast.LENGTH_SHORT).show();
                    break;

                }
            }
        }, new IntentFilter(SENT));

        // ---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(YourActivity.this, "SMS delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(YourActivity.this, "SMS not delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }, new IntentFilter(DELIVERED));

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);

    }


Q:

What is the name of this elm construct: type X = X {...}?

I am trying to understand this Elm construct:
type Item = Item { name : String, data : String }

It resembles a record, but it behaves very differently.
It is useful for defining recursive data models.
Unlike type alias Item = {...}, it does not provide a "constructor".
I cannot find it in Elm Syntax guides.
I cannot figure out how to access its fields:

> item = Item { name = "abc", data  = "def" }
Item { name = "abc", data = "def" } : Repl.Item

> item.name
-- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm

`item` does not have a field named `name`.

6|   item.name
     ^^^^^^^^^ The type of `item` is:

    Item

Which does not contain a field named `name`.

How is this construct called?
How do you access the contained fields?

A:

It is a Union Type with a single constructor which happens to take a Record as its only type parameter.
The fact that the type name and constructor name are both Item is a common idiom, but holds no significance. It could easily be any other valid constructor name:
type Item = Foo { name : String, data : String }

For practical purposes, it can be useful to use a type alias for the internal record type so you can more succinctly pull values out. If you move things around a little bit:
type alias ItemContents = { name : String, data : String }

type Item = Item ItemContents

You could provide a function that returns the internal contents:
getItemContents : Item -> ItemContents
getItemContents (Item contents) = contents

And now it could be used like this REPL example:
> item = Item { name = "abc", data  = "def" }
Item { name = "abc", data = "def" } : Repl.Item
> contents = getItemContents item
{ name = "abc", data = "def" } : Repl.ItemContents
> contents.name
"abc" : String


Q:

How can I get device id for push notifications using firebase in android

I found this solution and I think it is not the ID which is required for notification kindly tell me by some samples:
import android.provider.Settings.Secure;

private String androidIdd = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);

I guess I don't need an android id. I just want to get the device unique ID for Firebase Notification or GCM.

A:

Instead of using some third party tutorials I would prefer to take a look into the official Firebase Cloud Messaging documentation.
If you have set up everything correctly you can just scroll to the topic

Retrieve the current registration token
When you need to retrieve the current token, call FirebaseInstanceId.getInstance().getToken(). This method returns null if the token has not yet been generated.

In a nutshell: Call FirebaseInstanceId.getInstance().getToken() to reveive the current device token.
EDIT:
The command FirebaseInstanceId.getInstance().getToken() is deprecated. The same documentation mentions a new approach as below:
FirebaseInstanceId.getInstance().getInstanceId()
        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
            @Override
            public void onComplete(@NonNull Task<InstanceIdResult> task) {
                if (!task.isSuccessful()) {
                    Log.w(TAG, "getInstanceId failed", task.getException());
                    return;
                }

                // Get new Instance ID token
                String token = task.getResult().getToken();

            }
        });


Q:

How to approach an unknown person via email if I only have a name that sounds like her nickname?

So, I am researching master courses opportunities on a university at a different country (Scotland) and I was talking to the course director via email, asking about the workload of the course and he suggested I talk to a student, and gave me her email.
When the director gave the student email, he just said "Try emailing Jo", followed by her email.
However, it sounds a little awkward to approach that person with an email starting like "Hey Jo" or "Dear Jo", given that "Jo" sounds like some sort of nickname.
"Jo" is, however, all the information I have about that person.
It might also be rude to somehow imply that Jo might be an informal name and it turns out to be an actual name, given that I don't even know where she is from.
How can I start my email?

A:

There are a few different ways you can go about doing this.

Start the email with Hello Jo,. Jo could very well be just their nickname, but that is not for you to assume. The name you were given is Jo. Jo is all you know about the person.
If you feel highly confident that their actual name is something longer than Jo, then you can either mention in the same email (or on your second email, after getting the reply to the first one) that the professor told you that their name was Jo and if it is OK if you call her by that. You could ask her if that is a nickname or the real name. Don't sound like you don't think Jo is a real name. It might very well just be her name and you might just be insulting her. Phrase your sentence like this:

The professor told me to contact Jo, so I went with the assumption that Jo is your name. Is that OK or would you like me to address you as something else?

If you don't want to do either of that, you could just start your email with Hello,. Hello is what you should use if you don't know who this email is supposed to be for. In a workplace environment, when I email a client or a support team or something, I just start my email with Hello. Then when they reply to my email, I get a "real person" attached to that email and I can go with that person for all my corresponding emails. Just start it with Hello and in their reply, watch for their signature or other clues to see how to address them in future emails. I would also take an extra step and mention that the professor told you to contact Jo. Like so:

Hello,
  Blah blah and blah. I spoke to the professor regarding this and he asked me to contact Jo and gave me your email address.
  Blah blah and blah.

This will ensure that Jo knows that you are contacting them KNOWING THAT they are Jo.
Hope this helps.


Q:

Drag and Drop with custom control onto a Grid

I am looking to allow a user to drag a custom control around a Grid control smoothly, and I am not sure exactly what I am missing. All controls have AllowDrop set to true.

On MouseMove I do the following in the control that is being dragged:
DataObject dataObj = new DataObject("PersistentObject",this);
DragDrop.DoDragDrop(this, dataObj, DragDropEffects.Move);

On the Grid's DragEnter, DragOver, and DragDrop events, I set the effects of the DragEventArg to all.

The feedback shows that it the new location on the grid is a valid drop target, but it never seems to move.
Is there a way to do this on a Grid, or I am trying to do this on the wrong control (I am using a grid because the designer started with one)?
Are there other events that I have to fix, and/or are my current ones broken?
Edit: It would also be appreciated if it showed the control being dragged as it was happening. I am not sure if that is supposed to happen with my current approach, but that is the goal.

A:

You can easily do this without using the built-in drag-drop stuff.
Point mouseOffset = new Point();

userControl.PreviewMouseLeftButtonDown += (sender, e) =>
{
    mouseOffset = Mouse.GetPosition(userControl);
    userControl.CaptureMouse();
};

userControl.PreviewMouseMove += (sender, e) =>
{
    if (userControl.IsMouseCaptured)
    {
        Point mouseDelta = Mouse.GetPosition(userControl);
        mouseDelta.Offset(-mouseOffset.X, -mouseOffset.Y);

        userControl.Margin = new Thickness(
            userControl.Margin.Left + mouseDelta.X,
            userControl.Margin.Top + mouseDelta.Y,
            userControl.Margin.Right - mouseDelta.X,
            userControl.Margin.Bottom - mouseDelta.Y);
    }
};

userControl.PreviewMouseLeftButtonUp += (sender, e) =>
{
    userControl.ReleaseMouseCapture();
};

So the demo code I wrote up for this looks something like the following:
<Window x:Class="StackOverflowScratchpad.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="350"
    Width="525">
    <Grid>
        <!-- I am using a Button here just for simplicity. The code
             will function the same no matter what control is used. -->
        <Button x:Name="userControl" Width="75" Height="23" />
    </Grid>
</Window>

public MainWindow()
{
    InitializeComponent();

    Loaded += MainWindow_Loaded;
}

private void MainWindow_Loaded(object obj, RoutedEventArgs args)
{
    // Add the above C# here.
}


Q:

Getting Data from foreign table by primary key

In this setup, I have one Owner and he has 10 schools. I get the list of Owners in a combo box and select the Owner with its Id using combox.selectedvalue and name using its text value. Now I have a data grid view in which I want to list all the schools which belongs to selected owners with an additional column of owner name that is in the Owner table in data grid view.
I want to do this using Entity Framework.

I have seen many questions here but I didn't find exactly what I need.

A:

Depending on your schema for the database
Try this in event ComboBoxOwner_SelectedIndexChanged()
var selectedOwner = ((Owner)ComboBoxOwner.SelectedItem).Id;

GridViewSchools.DataSource = (from school in DbContext.Schools
                              join owner in DbContext.Owners on school.OwnerId equals owner.Id
                              where school.OwnerId == selectedOwner
                              select new { schoolName= school.Name , OwnerName = owner.Name }).ToList();

you can add all information of school at the same method


Q:

How do I prevent Ajax.BeginForm from loading a new page?

I have an Ajax form with a single input and a button.  On submit, the form should only post the entered value to an action method.  My form is correctly posting to the User controller's Log method but when done, the page redirects to /User/Log.
How can I avoid this?

<% using (Ajax.BeginForm("Log", "User", null, new AjaxOptions {HttpMethod = "POST" }))
{%>
    Please enter the username:
    <%= Html.TextBox("Username", "")%>
    <input type="submit" />
<% } %>

Here is the action method:

public class UserController : Controller
{
    [AcceptVerbs(HttpVerbs.Post)]
    public void ForgotPassword(FormCollection collection)
    {
        string username = collection["Username"];

        //TODO:  some work
    }
}

Thanks,
-Keith

A:

for this adding a new { target = "_self" } as htmlAttributes object worked for me as in
<% using (Ajax.BeginForm("Log", "User", null, new AjaxOptions {HttpMethod = "POST" }, new { target = "_self" }))
{%>


Q:

Append a list to the first row and column of a pandas dataframe

I have a 4300 x 4300 pandas dataframe (rows and columns) and want to add a list to the first rows and the first column. I don't know how to do so, without filling the dataframe completely with zeros…
Example for old 4300 x 4300 dataframe (excerpt):

Example of list to add:
["axis","output","group","plurality","record"]
Example for new A x A dataframe:

A:

If values in list not exist in index and columns use DataFrame.reindex with Index.append or Index.union:
L = ["axis","output","group","plurality","record"]
#if order is important
df = df.reindex(index=df.index.append(pd.Index(L)), columns= df.columns.append(pd.Index(L)))

#if index, columns values should be sorted
df = df.reindex(index=df.index.union(L), columns= df.columns.union(L))

If possible values exist in index, columns and order is important:
L1 = [x for x in L if x not in df.index]
L2 = [x for x in L if x not in df.columns]

df = df.reindex(index=df.index.append(pd.Index(L1)), columns= df.columns.append(pd.Index(L2)))


Q:

$k$ be an algebraically closed field , $R=M(n,k)$ , then $k \cong End_R (k^n)$

Let $k$ be an algebraically closed field. Let $n \ge 1$ be an integer and let $R=M(n,k)$ . Now every element $f \in R=M(n,k)$ is a $k$-linear map $f:k^n \to k^n$, hence $k^n$ forms a left $R$-module with the external multiplication defined as $f.v:=f(v)$. Let $End_R(k^n)$ be the set of all $R$-module maps on $k^n$, so that $End_R (k^n)$ forms a ring with unity w.r.t. usual pointwise addition and function composition. Then how to show that $k \cong End_R (k^n)$ as rings with unity ?

A:

If you unpack the definition, then it becomes clear that such an endomorphism is a linear map that commutes with all other linear maps. Equivalently a matrix that commutes with all other matrices.
It's a common exercise to show that if a matrix commutes with all other matrices, then it is a multiple of the identity. Consider the elementary matrices $E_{ij}$ with 1 in position (i,j) and zero elsewhere. Then first, checking what it means that your matrix commutes with $E_{ii}$, you find that all off-diagonal entries are zero. Then, by checking what it means that the matrix commutes with $E_{ij}$, you find that all the diagonal entries are equal.
So now you have an obvious morphism $k \to End_R(k^n)$ given by $\lambda \mapsto \lambda \operatorname{id}$. It's clearly injective, and the paragraph above shows that it's surjective, so it's an isomorphism.


Q:

How to invoke a non static method by reflection

I'm trying to understand the reflection C#, specifically loading a third-party dll in my program.
I created a simple dll:
namespace testclass
{
    public class Class1
    {
        private string f;
        public string f1 { get; set; }
    }

    public class Class2
    {
        public static int f2 = 0;
        public static string f1 { get; set; }

        static Class2()
        {
            Console.WriteLine("1st string");
        }

        public  void runme()
        {
            Console.WriteLine("2nd string");
        }
    }
}

And load it to my program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

class program
{
   static void Main()
    {
        Assembly assembly;
        assembly = Assembly.LoadFrom(@"D:\user\ClassLibrary1.dll");
        var exporttypes = assembly.GetExportedTypes();
        foreach (var types in exporttypes)
        {
            var fields = types.GetFields();
            foreach (var fi in fields)
            {
                if (fi.Name == "f2")
                {
                    fi.SetValue(exporttypes, 2);
                }
            }
            var m1 = types.GetMethods();
            for (int i = 0; i < m1.Length; i++)
            {
                if (m1[i].Name == "runme")
                {
                    m1[i].Invoke(types, null);
                }
            }
        }

        Console.ReadKey();
    }
}

The problem is that when you try to call the method 'runme', the compiler gives  an exception if 'runme' is not static. I would like to understand that in this case you need to pass as the first argument to invoke

A:

To invoke a non-static method using reflection, you must create an instance of the type and pass that as the first argument to Invoke.
So in  terms of your code, this could be
if (m1[i].Name == "runme")
{
    var inst = Activator.CreateInstance(types);
    m1[i].Invoke(inst, null);
}

Note, that will only work because that type has a parameterless constructor, and is the most basic way of creating an instance from a type, many others exist.


Q:

Compute integral $\int_{-\infty}^{\infty}\frac{e^{-ixt}}{\sqrt{1+x^2}} dx$

How to compute integral $\int_{-\infty}^{\infty}\frac{e^{-ixt}}{\sqrt{1+x^2}}dx$, which is the Fourier transform of $f(x)= \frac{1}{\sqrt{1+x^2}}$?
We already know that we can get the Fourier transform of $\frac{1}{(1+x^2)^2}$ by using the convolution theorem linked-to result.\
Now the question is that can we apply the same for  $f(x)= \frac{1}{\sqrt{1+x^2}}$? And how?
Thanks!

A:

Yes, this integral may be done using complex analysis.  Sort of.  What we end up with are two different representations of a modified Bessel function.  That said, the complex analysis route results in a transformation of the oscillatory Fourier integral - which is harder to compute - into a very quickly convergent integral representation.
Consider the contour intgeral
$$\oint_C dz \frac{e^{i t z}}{\sqrt{1+z^2}} $$
where $C$ is the following contour:

Note that the radius of the large circular arcs is $R$ and the small circle about the branch point at $z=i$ is $\epsilon$.  Note that we avoid crossing the branch cut along the imaginary axis.  By Cauchy's theorem, this contour integral is zero.  (Why?)  On the other hand, the contour integral is equal to, after parametrizing the various pieces:
$$\int_{-R}^R dx \frac{e^{i t x}}{\sqrt{1+x^2}} + i R \int_0^{\pi/2} d\theta \, e^{i \theta} \frac{e^{i t R e^{i \theta}}}{\sqrt{1+R^2 e^{i 2 \theta}}} \\ + i \int_R^{1+\epsilon} dy \, \frac{e^{-t y}}{i \sqrt{y^2-1}} + i \epsilon \int_{\pi/2}^{-3 \pi/2} d\phi \, e^{i \phi} \frac{e^{i t (i+\epsilon e^{i \phi})}}{\sqrt{1+(i+\epsilon e^{i \phi})^2}} \\ + i \int_{1+\epsilon}^R dy \, \frac{e^{-t y}}{-i \sqrt{y^2-1}}+ i R \int_{\pi/2}^{\pi} d\theta \, e^{i \theta} \frac{e^{i t R e^{i \theta}}}{\sqrt{1+R^2 e^{i 2 \theta}}}$$
We now consider the limits as $R \to \infty$ and $\epsilon \to 0$.  We first note that we may combine the second and sixth integrals and show that they vanish in this limit when $t \gt 0$.  Consider the absolute value of the combined integral and it is bounded from above as follows:
$$\frac{2 R}{\sqrt{R^2-1}} \int_0^{\pi/2} d\theta \, e^{-t R \sin{\theta}} \le \frac{2 R}{\sqrt{R^2-1}} \int_0^{\pi/2} d\theta \, e^{-2 t R \theta/\pi} \le \frac{\pi}{ t \sqrt{R^2-1}}$$
which clearly vanishes as $R \to \infty$.  It is straightforward to show that the fourth integral vanishes as $\epsilon \to 0$.  This, because the contour integral is zero, we are left with the following expression for the original Fourier integral:
$$\int_{-\infty}^{\infty} dx \, \frac{e^{i x t}}{\sqrt{1+x^2}} = 2 \int_1^{\infty} dy \, \frac{e^{-t y}}{\sqrt{y^2-1}} = 2 \int_0^{\infty} du \, e^{-t \cosh{u}}$$
The latter integral is $2 K_0(t)$.  That said, note that the integral we obtained is a far easier one to handle numerically if it came to it.  Accordingly, complex analysis is very useful in general for converting oscillatory Fourier integrals that are hard to evaluate numerically into exponential integrals that are very easy.
Note also that the above required $t \gt 0$.  When $t \lt 0$, we must use a different contour below the real axis, but the result is the same.  Therefore,

$$\int_{-\infty}^{\infty} dx \, \frac{e^{i x t}}{\sqrt{1+x^2}} = 2 K_0(|t|)$$

A:

$\frac{e^{-ixt}}{\sqrt{1+x^2}}$ does not belong to $L^1(\mathbb{R})$, but
$$ \lim_{M\to +\infty}\int_{-M}^{M}\frac{e^{-ixt}}{\sqrt{1+x^2}}\,dx =2\, K_0(|t|)$$
where $K_0$ is a modified Bessel function of the second kind (see eq 11). You can prove such identity by noticing that for $t>0$ both sides are solutions of the same differential equation.