text:
Q: Workfront/Attask: Retrieving "workUnit" from Task or Assignment returns http-500 For objects "Assignment" and "Task" the field "workUnit" is documented in the Workfront-Apiexplorer: https://developers.workfront.com/api-docs/api-explorer/ (sry, i cannot deeplink to a certain object in the documentation). I am using version 4.0.
But when executing https://.attasksandbox.com/attask/api/v4.0/ASSGN/search?sessionID=SOMESESSIONID&method=GET&assignedTo:lastName=SOMELASTNAME&fields=workRequired,avgWorkPerDay,task,task%3AdurationUnit,assignedTo,project,role,workUnit
i get 500 as returncode.
Task:durationUnit is working.
Is this a bug in the documentation or am i doing something wrong?

A: The cause seems to be from the workUnit field in the fields section. This is a bug since it is contained both in the metadata for ASSGN and in the developers website.


text:
Q: Connection refused to mysql database from C++ driver Problem
I'm following tutorial on Connect/C++ provided by dev.mysql. After copying the example and successfully compiling and linking it, I run into following issue:

terminate called after throwing an instance of 'sql::SQLException'
what():  Can't connect to MySQL server on '127.0.0.1' (111)

From what I know 111 stands for Permission Denied.
Setup
Here is the example code taken from here and slightly modified:
#include <mysql_driver.h>

int main()
{
    auto driver = sql::mysql::get_mysql_driver_instance();
    auto con = driver->connect("tcp://127.0.0.1:0", "root", "123");

    delete con;
}

Trying with tcp://127.0.0.1:3306 give the same result.
Here is the CMakeLists.txt:
cmake_minimum_required(VERSION 3.9)
project(mysql_try)

set(CMAKE_CXX_STANDARD 14)

set(SOURCE_FILES main.cpp)
add_executable(mysql_try ${SOURCE_FILES})

target_include_directories(mysql_try PUBLIC /usr/local/include/mysql++)
target_link_libraries(mysql_try mysqlclient /usr/local/lib/libmysqlcppconn-static.a pthread dl)

I can easily run mysql with the credentials in the code. I disabled networking, so that it would only listen on localhost. Running
mysql> SHOW GLOBAL VARIABLES LIKE 'PORT';

gave me 0, so I guess it is port 0.
C Connector and command line interfaces work just fine.
My OS is ubuntu 16.04.

A:
I disabled networking, so that it would only listen on localhost.

There's a difference between disabling networking all together (tcp) and specifying tcp to listen ONLY on your loopback adapter (127.0.0.1). Your mysql client is almost certainly connecting via Unix Socket, not TCP, which is why that works fine.  Verify that by running mysql --protocol tcp.  If that fails, then you know you disabled TCP connections all together, and it's connecting via Unix Socket.

connect("tcp://127.0.0.1:0"

If you did disable networking with skip-networking you need to change your connect() to reference your socket file instead. See the docs

unix://path_name
This URL format enables use of Unix domain socket files for connections to the local host on Unix and Unix-like systems. The path_name value is the socket file path name, just as for the --socket option of MySQL clients such as mysql and mysqladmin running on Unix (see Connecting to the MySQL Server).

Find your socket with:

mysql> SHOW GLOBAL VARIABLES LIKE 'socket'

If you want to keep your connect string the same, remove skip-networking and instead add
bind-address = 127.0.0.1
That should fix it!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Visual Studio 2015 - Two instances, same solution - how to retain two view states? I have a solution that I view with two separate instances of visual studio; One for the main app project, and the other for the web service project.
Visual Studio will restore the view state (which windows are opened, how they are situated (split screen, etc...)) of the last closed solution. This makes sense, I'm sure it is general OS functionality provided to all apps - cache out view state to the registry (notepad++ retains view state too).
I want to be able to retain and restore two separate view states. I know if I move the web service into it's own solution that I will get this desired behavior, but an architectural decision was made to roll it into the main solution, so it is not an option.
I need a way to snatch the view state from the registry somehow, and then maybe use a command switch when launching VS to tell it which to use (I guess I need reg and file monitor to see where it is caching to)??
Any ideas or suggestions (reg hacks welcome)?


text:
Q: Payment verification with the iOS Paypal SDK - Clarification needed please I have a specific question about the verification side of Paypal (using the latest iOS PayPal SDK)
From this document: https://github.com/paypal/PayPal-iOS-SDK/blob/master/docs/single_payment.md
This is mentioned:

Send the payment response to your servers for verification, as well as any other processing required for your business, such as fulfillment. Tip: At this point, the payment has been completed, and the user has been charged. If you can't reach your server, it is important that you save the proof of payment and try again later.

And from there is a link to the verify-mobile payments documentation, in which various things are mentioned, i'm assuming this part applies to the iOS SDK (latest)

Looking up a payment using the REST API
  You can payment id value in a response to look up a payment by calling the REST API. The following example retrieves a payment in the sandbox:
curl
  https://api.sandbox.paypal.com/v1/payments/payment/PAY-5YK922393D847794YKER7MUI
  \  -H "Content-Type: application/json" \  -H "Authorization: Bearer
  {accessToken}" You should verify that the Payment:
Is approved ("state": "approved"). Contains a Transaction with: An
  Amount with total and currency that match your expectation. A Sale
  that is completed (in related_resources, with "state": "completed").
  The live endpoint is
  https://api.paypal.com/v1/payments/payment/{payment_id}.

https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
Got it. So given the above assumptions (which I hope are correct!) what should one do with the details returned from the server? Save them to a database?
The docs seem to be a little vague in terms of this particular subject. This is my understanding of the flow:
1) Make payment.
2) Send payment details to server.
3) Get back payment state from server.
4) Check that it's approved and the other details match up (amount, currency etc)
5) Upon making another payment, check to see if the payment id has already been used? This is another part of my confusion.
Thank you in advance for any assistance. Just would like some clarification in layman's terms to see if I understand the flow correctly.

A: from the sdk you will get a response which will have a state and id. the id you should save to database for your purposes, because you can always call /payments/id https://developer.paypal.com/webapps/developer/docs/api/#look-up-a-payment-resource and see the details of it. Every id is unique. state will have more information if the payment has been successful or not. Please check documentation. Hope it helps.


text:
Q: Model does not contain a constructor that takes 8 arguments Im am completely new to C# and was trying to setup a very basic application where I created the class/model:
public class Customer
    {
        public int CustomerID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string Zipcode { get; set; }
        public string City { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
    }

Now, when I try to instanciate a Customer Object from another class like so:
Customer c1 = new Customer(1, "Susan", "Peterson", "Borgergade 45", "8000", "Aarhus", "supe@xmail.dk", "21212121");

I get:

'PetParadiseHotel.Models.Customer' does not contain a constructor that
  takes 8 arguments

From my understanding there are exactly 8 arguments that it should take, so what is the problem here?

A: You have to create a contructor for your class
public class Customer
{
    public Customer(int customerID, string firstName, string lastName, string address,
                    string zipCode, string city, string email, string phone)
    {
        CustomerID = customerID;
        FirstName = firstName;
        // ...
        Phone = phone;
    }
    public int CustomerID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string Zipcode { get; set; }
    public string City { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
}

then call it (like you did)
var customer = new Customer(1, "Susan", "Peterson", "Borgergade 45", "8000", "Aarhus", "supe@xmail.dk", "21212121");

Or you can use the object initializers:
var customer = new Customer() { CustomerID = 1, FirstName = "Susan" ... Phone = "21212121"}

A: C# classes have a default constructor if no explicit constructor is defined. It would look essentially like:
public class Customer
{
    public Customer()
    {
    }

    ...
}

In other words, it doesn't do anything, really, and takes no arguments. This allows you to new it up using just the syntax:
var customer = new Customer();

If you wanted to be able to pass in all those values to the constructor, you would have to create a custom constructor along the lines of:
public class Customer
{
    public Customer(int customerId, string firstName, string lastName, string address, string zipCode, string city, string email, string phone)
    {
        CustomerId = customerId;
        FirstName = firstName;
        LastName = lastName;
        Address = address;
        ZipCode = zipCode;
        City = city;
        Email = email;
        Phone = phone;
    }

    ...
}

You would also need to redefine the "default" constructor, or you would never be able to just new up an empty Customer:
public Customer()
{
}

Additionally, if you only wanted to pass some subset of those properties, instead of every single one, you would need to create additional constructors for each subset, or provide default values for any not passed in parameters to the constructor. Long and short, this is highly arduous, and makes maintenance a bloody nightmare. Thankfully, C# also has what's called the object initializer syntax. Instead of parenthesis, you use curly brackets and you set each property you want to explicitly:
var customer = new Customer
{
    CustomerId = 1,
    FirstName = "Susan",
    LastName = "Peterson",
    ...
}

The benefit of this approach is that you can just keep the default constructor, but still set each property you want to "initialize". Additionally, you can specify whatever subset of properties you want to initialize, so if you don't want to set the Phone property, just leave it out. Everything will still work fine.

A: Generally I've found if there's more than 3, that's a sign to do a quick sanity check on the design. If there's more than 5, that's a major warning that something is probably wrong with the design.
However, note the word "probably" - in the end, the only real rule is use as many as needed to function, no more and no less. There are always exceptions and cases where more parameters makes the most sense.
If the parameters are related somehow, you should encapsulate them into a container class.


text:
Q: How to fix: "Always-on screen" OFF, causes irregular location updates on android wear I am getting location updates in a service via FusedLocationProviderClient. Problem is: When "Always-on screen" is disabled on the watch, the location updates become very irregular.
Is there a way to circumvent this?

A: I figured out that it was actually not the location provider but android restricting the resources of the encapsulating service since it wasn't configured as a ForegroundService. From the documentation:

If your app targets API level 26 or higher, the system imposes restrictions on using or creating background services unless the app itself is in the foreground. If an app needs to create a foreground service, the app should call startForegroundService().


text:
Q: Remove one legend key from a plot in ggplot2 To separate two groups of bar plot, I followed the method by How to control space between stack bars in ggplot2?
The main idea is making a dummy raw but shows NA label on x-axis.
The code I'm using:
Df %>%
  bind_rows(data_frame(var1 = "trt99")) %>%
  ggplot(aes(x=var1, y=value*100, fill = var3)) +

  geom_bar(stat='identity', width=0.3,
       position = position_dodge(width=1))+

  scale_x_discrete(expand=c(0.05,0),
                limits = c("Rho(-)", "Rho(+)", "trt99", "Artemia", "Aca(-)", "Aca(+)"),
                breaks = c("Rho(-)", "Rho(+)",    NA  , "Artemia", "Aca(-)", "Aca(+)"),
                labels = c("Rho(-)", "Rho(+)",     " ", "Artemia", "Aca(-)", "Aca(+)"))+

  theme(panel.border = element_blank(),
          legend.position = c(0.2,0.9))

And I get the figure like:

My question is: How can I remove the NA legend key from this plot?


text:
Q: 3-dimensional light up cube, # of rows/cols/diags in/on a 4 × 4 × 4 cube
Imagine a 3-dimensional cube (much like a 4 × 4 × 4 Rubik's cube) except the planes of the cube cannot be twisted individually and instead of faces with different colors, it is clear (see thru) but with a single light in each of the $64$ little cubes contained within the $1$ big cube.
The $64$ lights are connected to $64$ switches, all of them initially turned off.  We now turn on a light by choosing a switch uniformly at random, toggling it (so that the light turns on if it was off, and turns off if it was on), and repeat this lighting process for a total of $32$ times.
At the end, we therefore have at most half of the $64$ lights lit — but the actual number is likely to be less, since some lights may be toggled several times.
I'd like to confirm the answers to the following five questions:
$1$. What will be the average number of lights on after all $32$ random numbers are processed sequentially, meaning that the corresponding lights were toggled properly from them, possibly multiple times each?
$2$. At the end of the lighting process, we want to know what is the probability that only $1$ complete row, column, or diagonal will be illuminated.  That is, $4$ adjacent/connected lights that complete one of those.  It may help if you think about and answer question 3 first.
$3$. How many possible complete unique/distinct rows, columns, and diagonals are there in/on the cube?  Remember they can go thru the cube, not just along the faces.  Also, they can be on the inner planes such as planes $2$ and $3$ (of $4$). They must be collinear.  You cannot go around a corner for example and get $4$ in a row.  All $4$ lights must lie in a line segment of length $4$ with length (in this context) meaning # of adjacent lights illuminated in a collinear fashion.
$4$. What is the ideal number of lights on that will give us the highest probability of having exactly $1$ complete row/col/diag?
$5$. How many random lights (minimum) need to be on to guarantee that at least $2$ complete rows/cols/diags are illuminated?  That is, the probability of exactly $1$ complete row,col,diag becomes $0$.

I used computer simulation and got the following results so far:

*

*On average about $20.4$ lights will be on.

*I get about $31.89$%.  The result is somewhat surprising to me because of all the possible ways to get $1$ complete row/col/diag, you would think out of $20$ or so lights (on average), you would get multiple of those more often.  My simulation program is even telling me that getting $8$ complete is even possible, but very unlikely.  I don't know what the max is, maybe $20$ or so if all $32$ lights stay lit and they just happen to be perfectly placed for maximum lit rows/cols/diags.

*I counted $76$ distinct complete rows, columns, and diagonals (so far) of length $4$.

*It appears that the ideal # of lights on is $23$, which gives about a $39.5$% chance of exactly $1$ complete row/col/diag. $22$ was a close 2nd with a $39.3$% chance. $24$ came in 3rd with a $38$% chance.

*I think the minimum is $47$.  The algorithm I used is very simple and very fast. Obviously you cannot have any $4$ in a row, col, or planar diagonal, so I simply started with $48$ (of $64$) lights on, making sure to turn off $1$ in each row, col, and planar diagonal (but not checking 3D diagonals).  My simulation program told me I had $3$ complete "lines" at that point.  I then checked to see if I could get only $1$ line lit by testing each of the $48$ on lights by turning them off one at a time then putting them back on before the next test.  That dropped it to $2$ lines illuminated.  I then looped thru combinations of $2$ on lights (there are $48 \choose 2$ of them which is only $1128$).  That dropped it to only $1$ line lit.  F.Y.I. my program told me there were $27$ two light combos that (when turned off) dropped it to only $1$ line lit.  So with that info, we just take the penultimate distinct # of lit lights we tried (which was $47$) and that is our answer.
The correct answer for Question $2$ depends on getting Question $3$ correct, so that is why I am asking for some help, because I want to get this exactly right.
For the diagonals, I counted $2$ per face, so that is $12$ facial diagonals (imagine an X shape on each face), $12$ inner planar diagonals which are Xs also but on planes $2$ and $3$, twisting the cube in all $3$ dimensions.  I also count $4$ inner "3D" diagonals that go thru the "heart" of the cube.
Can someone please help me confirm these numbers?

A: Question 1
This is a simple Markov chain.
Let $o_i$ be the number of lights ON at step $i$, then
$$o_{i+1}=\begin{cases}
o_i-1,&p=\frac{o_i}{64}\\
o_i+1,&p=1-\frac{o_i}{64}\\
\end{cases}$$
And $o_0=0$
You can build the matrix for this (I'm not going to) and solve for 32 steps.
Question 2
For 4 specific lights in row, calculate the chance that each of them is "hit" an odd number of times and note how many of the 32 shots each combination uses up (hint: it can be $4, 6, \dots,32$).
Then for all other rows, calculate the chance that at least 1 of the bulbs is hit an even number of times (including 0) and allowing for the fact that some bulbs are common with the illuminated row.
Question 3
From each face there are 16 rows/columns. There are 3 independent faces. Therefore there are 48 rows/columns.
Diagonals that are 4 long can only start from the corners. There are 2 in each 1x4 block. There are $4+4+4$ of these. 24.
Plus there are 4 diagonals that go from corner of the cube through the "guts" to the other corner.
$48+24+4=76$

A: Question 1:
This one is actually pretty easy.
It helps to start by considering a single light.
The number of times the light is toggled is binomially distributed, with parameters $n = 32$ and $p = 1/64$, and the probability that it ends up being lit at the end of the process is the sum of the probabilities that it is toggled an odd number of times, i.e.:
$$P = \sum_{k=1}^{16} f(2k-1;32,\tfrac1{64}) = \sum_{k=1}^{16} {32 \choose 2k-1} \left( \frac1{64} \right)^{2k-1} \left( 1-\frac1{64} \right)^{33-2k},$$
where $f(k;n,p) = {n \choose k} p^k (1-p)^{n-k}$ is the probability mass function of the binomial distribution.  A laborious but straightforward evaluation of the sum, best carried out by a computer, then yields the result:
$$P = \frac{932357239278482603486754898815444262218545775615}{2923003274661805836407369665432566039311865085952} \approx 0.318972$$
Now, by the linearity of the expected value, the expected number of lit lamps is simply the total number of lamps times the probability of each lamp being lit, i.e. $64 P \approx 20.41423$.
Ps. I did the calculation in Maxima, but any language that has an arbitrary-precision rational type will do — or you can even use floats, if you only want an approximate numerical value.  Here's the code I used:
f(k,n,p) := binomial(n,k) * p^k * (1−p)^(n−k);
P: sum(f(2*k-1 , 32 , 1/64), k, 1, 16);
float(P);
float(64 * P);

Question 3:
The third question, is a simple exercise in 3D visualization and enumeration:

*

*For each of the three axes, there are 16 columns running parallel to the axis for a total of 3 × 16 = 48 columns.

*For each of the three axes, there are also 2 × 4 = 8 diagonals running perpendicular to that axis (from one edge of the cube to the opposite), for a total of 3 × 8 = 24 diagonals.

*Finally, there are 4 "inner diagonals" running from one corner of the cube to the opposite one.

Thus, the total number of ways you can arrange four sub-cubes in a row in a 4 × 4 × 4 cube is 48 + 24 + 4 = 76.

Question 5:
For this question, we can equivalently ask for the minimum number $n$ of unlit lamps needed to get at least one unlit lamp in every line of four lamps except one.  The minimum number of lit lamps needed to guarantee at least two fully lit lines of four lamps is then $k = 64 - n + 1$.
An upper bound for this is given by the fact that each 4×4×1 plane must contain at least four unlit lamps (as otherwise it would contain at least one fully lit row and one fully lit column).  Thus, it is clear that at least 16 unlit lamps are needed to keep the number of fully lit lines below two.  Thus, $n \ge 16$, and so $k \le 49$.
Conversely, the following configuration (0 = off, 1 = on; each square is one slice of the cube) demonstrates that $5 + 4 + 4 + 5 = 18$ unlit lamps can be arranged to leave only one fully lit line of four lamps (an inner diagonal from top left to bottom right):
1100  0111  1011  0110
1011  1110  1101  0111
1110  1011  0111  1101
0111  1101  1110  1011

Thus, the minimum number of lit lamps needed to guarantee at least two fully lit lines of four is at least 47, and no greater than 49.
In fact, it turns out that the configuration above is optimal (although not uniquely so), and that the minimum number of lit lamps needed to guarantee at least two fully lit lines of four is $k = 47$.  I have confirmed this by first generating all the 1636 possible 4 × 4 planes with 4 or 5 unlit lamps and 0 or 1 fully lit lines, and then searching all possible combinations of such planes for a combination with at most 17 unlit lamps and at most 1 fully lit line.  No such combination was found, proving that $n = 18$ unlit lamps is the minimum needed to achieve less than two fully lit lines.
(The trick that made the search feasible was making sure to prune early any partial configurations containing two fully lit lines or two planes with 5 unlit lamps, since no such combination can appear in an $n=17$ solution.  This pruning allowed me to only check 40,478,800 full cubes, which was easily doable in a few minutes even on my old laptop.)
Ps. The configuration above was found by noting that there are only 10 ways to arrange 12 lit lamps and 4 unlit ones on a 4 × 4 plane without getting any fully lit rows, columns or diagonals.  It further turns out there's a way to stack four such planes into a cube in such a way as to leave only three inner diagonals (and no other lines of four lamps) fully lit:
1101  0111  1011  1110
1011  1110  1101  0111
1110  1011  0111  1101
0111  1101  1110  1011

Turning off two more lamps then leaves only one of the diagonals fully lit.

Question 2:
Your even-numbered questions seem, at least to me, quite a bit harder than the odd-numbered ones.  I don't have an analytical solution for them, but I did run a stochastic simulation of my own to confirm your results.  It does appear that the probability of getting exactly one fully lit line of four lights with 32 toggles is about $0.318951 \pm 3\times10^{-6}$ (95% confidence interval, calculated using a normal approximation from 100 billion trials).  The proximity of this value to the probability of a single lamp being lit seems like a rather remarkable coincidence, but I can't really see any way it could be anything but a coincidence.
(The maximum number of fully lit lines of four lamps I observed in my simulation was 16, but the theoretical maximum obtainable is at least 20, achieved by lighting all 32 lamps in one half of the cube.  I suspect that's the best one can do with 32 toggles, although I haven't proven that.)

Question 4:
As for this question, my stochastic simulation confirms your result that 23 lights is optimal, with a probability of $0.3945 ±0.0001$ of getting exactly one line of four lit lamps.  For randomly toggled lamps, as in your first question, it appears that the optimum is either 36 or 37 toggles, both of which give a probability of $0.3297 ±0.0001$; I'd need to run more trials to tell if there's any difference between them, and if so, which way.
Interestingly, the expected number of lit lamps is only about 21.8 for 36 toggles, or 22.1 for 37 toggles, about one lamp short of the optimal fixed light count of 23, showing that the variance and higher moments of the light count distribution also play a role.


text:
Q: Installing Windows on Ubuntu I've 2 hard disks. I've installed Ubuntu on the HDA(0), but there are plenty of spaces. But On the HDA(0) there is only one partition.
My question
How can I edit / create another partition on HDA(0) to install Windows XP on the 2nd partition ?
How can I install Windows XP on HDA(1) and still be able to boot in Windows XP or Ubuntu ?

A: First you should use a live system to partition the disk with Gparted (it is included in Ubuntu live) and create a NTFS partition.
Remember to reserve the first partition to Windows (some versions of it don't recognize NTFS partitions if there's something else before them).
Then you should install Windows in that partition and, in the end, you have to recover GRUB, as described here: https://help.ubuntu.com/community/RecoveringUbuntuAfterInstallingWindows

A: You can use gparted to shrink partitions.
http://gparted.sourceforge.net/download.php
After you installed windows, you can use EasyBCD to edit the Windows boot manager for that it gives you the option to load Linux.
http://neosmart.net/EasyBCD/
I know it works, I have done it once.
If you put grub in the MBR, then you will get into trouble when some settings change (e.g. the kernel renames the /dev/sda1 to /dev/hda1 etc., and then it will boot neither Windows nor Linux.
I don't know whether you still need to move grub from the MBR to to /dev/hda1 or wherever your primary Linux partition is, but I think it works without that as well.
I would install a Windows driver that enables windows to read the ext3/4 fs.
I don't know whether something for ext4 exsts already, but ext3 was definitely supported, in order to access data on the Linux partition on Windows.


text:
Q: TypeInitializationException accessing MonoGame GraphicsAdapter.Adapters, could not load type 'SharpDX.Rectangle' Converting VB code from XNA 3.1 to MonoGame.
Any attempt to access class GraphicsAdapter throws the exception below. For example, trying to enumerate GraphicsAdapters. On this line:
For Each adapter As GraphicsAdapter In GraphicsAdapter.Adapters

Result is an exception:
System.TypeInitializationException occurred
  HResult=-2146233036
  Message=The type initializer for 'Microsoft.Xna.Framework.Graphics.GraphicsAdapter' threw an exception.
  Source=MonoGame.Framework
  TypeName=Microsoft.Xna.Framework.Graphics.GraphicsAdapter
  StackTrace:
       at Microsoft.Xna.Framework.Graphics.GraphicsAdapter.get_Adapters()
       at ...my code...
  InnerException:
       HResult=-2146233054
       Message=Could not load type 'SharpDX.Rectangle' from assembly 'SharpDX, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b4dcf0f35e5521f1'.
       Source=MonoGame.Framework
       TypeName=SharpDX.Rectangle
       StackTrace:
            at Microsoft.Xna.Framework.Graphics.GraphicsAdapter.CreateAdapter(Adapter1 device, Output monitor)
            at Microsoft.Xna.Framework.Graphics.GraphicsAdapter.PlatformInitializeAdapters(ReadOnlyCollection`1& adapters)
            at Microsoft.Xna.Framework.Graphics.GraphicsAdapter..cctor()

Note the inner exception:
Could not load type 'SharpDX.Rectangle' from assembly 'SharpDX, ...Version=4.0.1.0, ...

The project references these assemblies (among others):

*

*MonoGame.Framework version=3.6.0.1625
from NuGet "MonoGame.Framework.WindowsDX", file
packages\MonoGame.Framework.WindowsDX.3.6.0.1625\lib\net40\MonoGame.Framework.dll

*SharpDX version=4.0.1.0

*SharpDX.Direct2D1 version=4.0.1.0

*SharpDX.Direct3D9 version=4.0.1.0

*SharpDX.DXGI version=4.0.1.0

*SharpDX.Mathematics version=4.0.1.0

So I don't see why it would fail this way.
What could be wrong? Not compatible with this SharpDX version?
NOTE: These are all up-to-date packages from NuGet, in Visual Studio 2015. Targeting .Net 4.5.2.

UPDATE
To prove it isn't a problem with SharpDX, I put this line before that GraphicsAdapter line:
Dim testRect As SharpDX.Rectangle = New Rectangle()

This successfully created testRect. No Exception until attempt to access GraphicsAdapter.  Also tried all the other Shared (static) properties of GraphicsAdapter, such as GraphicsAdapter.DefaultDevice. Any one fails with same exception.

A: I posted the same question to MonoGame forums:
http://community.monogame.net/t/solved-typeinitializationexception-accessing-graphicsadapter-adapters-could-not-load-type-sharpdx-rectangle/9803
Cause of problem:
Current release of MonoGame.Framework for WindowsDX (Windows OS + DirectX drivers), 3.6.0.1625 is built against SharpDX 2.6.3, and is not compatible with more recent SharpDX versions.
(Interim) Solution:
The developer branch of MonoGame does target the current SharpDX. Builds can be obtained from MonoGame's teamcity (free registration required).
Tested MonoGame.Framework build 3.7.0.994; it worked with SharpDX 4.0.1:
http://teamcity.monogame.net/viewLog.html?buildId=56483&tab=artifacts&buildTypeId=MonoGame_PackagingWindows
That build installs most SharpDX dlls to
C:\Program Files (x86)\MonoGame\v3.0\Assemblies\Windows
However, SharpDX.Mathematics.dll is currently missing,
so I still install SharpDX from NuGet, rather than using those.

Standard location for MonoGame releases:
(look for at least 3.7, which is not there yet, as I write this):
http://www.monogame.net/downloads/
(If instead of NuGet packages for MonoGame and SharpDX, I had downloaded MonoGame 3.6 installer and used its version of SharpDX dlls at C:\Program Files (x86)\MonoGame\v3.0\Assemblies\Windows, then I would not have had this incompatibility. However, that was not recent enough SharpDX for my purposes.  This should be resolved by release of MonoGame 3.7)


text:
Q: What does this symbol mean (white circle connected with black bullet; both are linked by a horizontal line) and how can I write it in LaTeX? The symbol appears within the definition of the Fourier transform. The German text translates as follows:

The Fourier transform of a continuous, integrable function $s(t)$ is given as
Math stuff with ominous symbol.
The equivalence $e^{ix} = \cos(x) + j\sin(x)$ is called Euler's formula.

A: To write it in LATEX you need to include the package "txfonts" and use $\multimapdotbothA$.

A: I don't think it means anything distinctly mathematical. I think it is read "is defined by".
Try detexify.


text:
Q: Make password invisible to protect worksheets I have a simple code that I am wondering if there is a better way of hiding the password, besides from "Locking the project from viewing". I am setting the sheet in xlSheetVeryHidden, but still someone can see the pasword if they want to.
Here is the code:
Private Sub Workbook_Open()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("OpenLog")

If Not ws.Visible = xlSheetVeryHidden Then ws.Visible = xlSheetVeryHidden
ws.Protect Password:=1214, UserInterFaceOnly:=True

End Sub

Any help is appreciated
Nick.


text:
Q: "Permission Denied" trying to run Python on Windows 10 Seems as though an update on Windows 10 overnight broke Python. Just trying to run python --version returned a "Permission Denied" error.  None of the three updates; KB4507453, KB4506991, or KB4509096 look like they'd be the culprit but the timing of the issue is suspicious. Rather than messing with rolling back, I'm hoping there's a simpler fix that I'm missing.
The permissions on python are "-rwxr-xr-x" and I haven't changed anything besides letting the Windows update reboot machine after installing last night's patches.
According to the System Information, I'm running 10.0.18362
Should also note that this is happening whether I (try) to execute Python from git-bash using "run as administrator" or not, and if I try using PowerShell, it just opens the Windows store as if the app isn't installed so I'm thinking it can't see the contents of my /c/Users/david/AppData/Local/Microsoft/WindowsApps/ folder for some reason.
I've also tried to reinstall Python 3.7.4, but that didn't help either. Is there something else I should be looking at?

A: Adding the Local Python Path before the WindowsApps resolved the problem.

A: For people coming to this question wanting to use the Microsoft Store version of Python, and after the related "Manage app execution aliases" fix by @Zooba has likely happened, and are using Git for Windows git-bash (also known as BASH through msys2 mintty), the solution is likely simply to remember to make the call with winpty.'
winpty python3

However, if the system has had other versions of Python, make sure those copies have been removed (e.g. those installed from python.org) or are contained to their specific bundled application (e.g. OSGeo4W) (may require re-ordering environment variables).
Why, if winpty is forgotten, is it a permission error? For the first time it runs, the Microsoft Store stubs are conflicting with the permissions available to msys. A lot of the other answers go into the details of what is going on and why it feels weird. The short answer, is that the stub is trying to be a convenience short-cut to the Microsoft Store. If you launch it with winpty, it can do that. After that first time, it continues to need winpty for both related and unrelated reasons to the Microsoft Store.

A: It's not a solution with PowerShell, but I had the same problem except with MINGW64. I got around it by switching to Windows Subsystem for Linux (which I wanted to do anyways) as my terminal, just generally and in VSCode. This post describes it well:
How to configure VS Code (windows) to use Ubuntu App as terminal
In summary:
1) Install Ubuntu from the Windows App Store
2) Change the default bash from CMD -> wslconfig /setdefault Ubuntu
--- For VSCode
3) Restart VSCode
4) In VSCode change "terminal.integrated.shell.windows" to "C:\WINDOWS\System32\bash.exe" (for further details see the post above)
Running smoothly now in VSCode and WSL (Bash on Ubuntu on Windows). Might be at least a temporary solution for you.

A: For me, I tried manage app execution aliases and got an error that python3 is not a command so for that, I used py instead of python3 and it worked
I don't know why this is happening but It worked for me

A: As far as I can tell, this was caused by a conflict with the version of Python 3.7 that was recently added into the Windows Store. It looks like this added two "stubs" called python.exe and python3.exe into the %USERPROFILE%\AppData\Local\Microsoft\WindowsApps folder, and in my case, this was inserted before my existing Python executable's entry in the PATH.
Moving this entry below the correct Python folder (partially) corrected the issue.
The second part of correcting it is to type manage app execution aliases into the Windows search prompt and disable the store versions of Python altogether.

It's possible that you'll only need to do the second part, but on my system I made both changes and everything is back to normal now.

A: Research
All of the files in %USERPROFILE%\AppData\Local\Microsoft\WindowsApps are placeholders that point to files that are actually located somewhere in C:\Program Files\WindowsApps, which happens to be denied permissions completely.
It appears I was on the right track with my statement made in my duplicate of this problem:

"Seems like they didn't really think about the distribution method screwing with permissions!"

Source: Cannot install pylint in Git Bash on Windows (Windows Store)
Permissions are screwed up royally because of the WindowsApps distribution method:

Interestingly it says that the "Users" group can read and execute files, as well as my specific user, but the Administrators group can only List folder contents for some hilariously unfathomable reason. And when trying to access the folder in File Explorer, it refuses to even show the folder contents, so there's something fishy about that as well.
Interestingly, even though executing python in CMD works just fine, the "WindowsApps" folder does not show up when listing the files in the directory it resides in, and attempting to navigate into the folder generates a "Permission denied" error:

Attempting to change the permissions requires changing the owner first, so I changed the owner to the Administrators group. After that, I attempted to change the permissions for the Administrators group to include Full control, but it was unable to change this, because "access was denied" (duh, Micro$ucks, that's what we're trying to change!).

This permission error happened for so many files that I used Alt+C to quickly click "Continue" on repeat messages, but this still took too long, so I canceled the process, resulting in this warning message popping up:

And now I am unable to set the TrustedInstaller user back as the owner of the WindowsApps folder, because it doesn't show up in the list of Users/Groups/Built-in security principles/Other objects. *

*Actually, according to this tutorial, you can swap the owner back to TrustedInstaller by typing NT Service\TrustedInstaller into the object name text box.
Solution
There is no solution. Basically, we are completely screwed. Classy move, Microsoft.

A: This is due to the way Windows App Execution Aliases work in Git-Bash.
It is a known issue in MSYS2 failing to access Windows reparse points with IO_REPARSE_TAG_APPEXECLINK
As a workaround, you can alias to a function invocation that uses cmd.exe under the hood.
Add the following to your ~/.bashrc file::
function python { cmd.exe /c "python $1 $2 $3";}

For python, I'd recommend just toggling off app execution aliases as in the accepted answer, but for libraries that are distributed exclusively through the windows store like winget, this is your best option.
Further Reading

*

*bash: Local/Microsoft/WindowsApps/python3: Permission denied

*Permission Denied when running from bash

*winget does not run in WSL2 due to exec format error #234

A: This appears to be a limitation in git-bash. The recommendation to use winpty python.exe worked for me. See Python not working in the command line of git bash for additional information.

A: This issue is far too common to still be persistent. And most answers and instructions fail to address it. Here's what to do on Windows 10:

*

*Type environment variables in the start search bar, and open Edit the System Environment Variables.

*Click Environment Variables...

*In the System Variables section, locate the variable with the key Path and double click it.

*Look for paths pointing to python files. Likely there are none. If there are, select and delete them.

*Create a new variable set to the path to your python executable. Normally this is C:\Users\[YOUR USERNAME HERE]\AppData\Local\Programs\Python\Python38. Ensure this by checking via your File Explorer.
Note: If you can't see AppData, it's because you've not enabled viewing of hidden items: click the View tab and tick the Hidden Items checkbox.

*Create another variable pointing to the Scripts directory. Typically it is C:\Users\[YOUR USERNAME HERE]\AppData\Local\Programs\Python\Scripts.

*Restart your terminal and try typing py, python, python3, or python.exe.

A: Simple answer: replace python with PY everything will work as expected

A: Workaround: If you have installed python from exe follow below steps.
Step 1: Uninstall python
Step 2: Install python and check Python path check box as highlighted in below screentshot(yellow).
This solved me the problem.

A: The simplest thing to do would be to modify your PATH and PYTHONPATH environmental variables to make sure that the folder containing the proper python binaries are searched befor the local WindowsApp folder.  You can access the environmental variables by opening up the control panel and searching for "env"

A: I had this to Run /execute but was not working
python3 -m http.server 8080

after reading and trying some of the solutions above and did not worked , what worked for me was
python -m http.server 8080

A: make sure C:\Python39\ and C:\Python39\Scripts\ are added to both system path variables and user path variables

A: I experienced the same issue, but in addition to Python being blocked, all programs in the Scripts folder were too. The other answers about aliases, path and winpty didn't help.
I finally found that it was my antivirus (Avast) which decided overnight for some reason to just block all compiled python scripts for some reason.
The fix is fortunately easy: simply whitelist the whole Python directory. See here for a full explanation.

A: Add the path of python folder in environmental variable and it will work
1.search environmental variable
2.look for system variable section and find variable named path in it
3.double click on path and add new path which directs towards python folder and that's it.
the python folder is usually in
C:\Users["user name"]\AppData\Local\Programs\Python\Python39

A: May be you can try opening command prompt with Administrator privileges. (Run As Administrator). Works for me most of the time.

A: save you time :
use wsl  and vscode remote extension to properly work with python even with win10
and dont't forget virtualenv!
useful https://linuxize.com/post/how-to-install-visual-studio-code-on-ubuntu-18-04/

A: In Windows 10

*

*Open Control Panel

*Click System

*Click the Advanced system settings link

*Click Environment Variables button

*In the System Variables section find the PATH environment variable and select it

*Click Edit (If the PATH environment variable does not exist, click New)

*In the Edit environment variable window specify the value of the PATH environment variable

*Click OK

*Close all remaining windows by clicking OK

*Reopen Command prompt window and run python --version


text:
Q: Error trying to import between python files I have a basic parser app I'm building in Python.  I monitors a folder and imports files when they are dropped there.  I have a MongoDB that I'm trying to save the imports to.  There's almost nothing to it.  The problem happens when I try to include one of my class/mongo-document files.  I'm sure it's a simple syntax issue I don't understand.  I have all my requirements installed, and I'm running this in an virtual env.  This is my first python app though, so it's likely something I'm not seeing.
My file structure is
application.py
requirements.txt
__init__.py
-services
   parser.py
   __init__.py
-models
   hl7message.py
   __init__.py

Here is application.py
from mongoengine import connect
import os, os.path, time
from services import parser

db = connect('testdb')
dr = 'C:\\Imports\\Processed'

def processimports():
    while True:
        files = os.listdir(dr)
        print(str(len(files)) + ' files found')
        for f in files:
            msg = open(dr + '\\' + f).read().replace('\n', '\r')
            parser.parse_message(msg)

        print('waiting')
        time.sleep(10)

processimports()

requirements.txt
mongoengine
hl7

parser.py
import hl7
from models import hl7message

def parse_message(message):
    m = hl7.parse(str(message))
    h = hl7message()

hl7message.py
from utilities import common
from application import db
import mongoengine

class Hl7message(db.Document):
    message_type = db.StringField(db_field="m_typ")
    created = db.IntField(db_field="cr")
    message = db.StringField(db_field="m")

If I don't include the hl7message class in the parser.py it runs fine, but as soon as I include it I get the error, so I'm sure it has something to do with that file.  The error message though isn't to helpful.  I don't know if I've got myself into some kind of include loop or something.
Sorry, stack trace is below
Traceback (most recent call last):
  File "C:/OneDrive/Dev/3/Importer/application.py", line 3, in <module>
    from services import parser
  File "C:\OneDrive\Dev\3\Importer\services\parser.py", line 2, in <module>
    from models import hl7message
  File "C:\OneDrive\Dev\3\Importer\models\hl7message.py", line 2, in <module>
    from application import db
  File "C:\OneDrive\Dev\3\Importer\application.py", line 23, in <module>
    processimports()
  File "C:\OneDrive\Dev\3\Importer\application.py", line 17, in processimports
    parser.parse_message(msg)
AttributeError: module 'services.parser' has no attribute 'parse_message'

A: This is a circular import issue. Application.py imports parser, which imports h17 which imports h17message, which imports application which runs processimports before the whole code of the parser module has been run.
It seems to me that service modules should not import application. You could create a new module common.py containing the line db = connect('testdb') and import db from common both in application.py and in h17message.


text:
Q: Implement a listbox I need to implement a listbox for a mobile.  The only relevant controls are up and down arrow keys.  The listbox should display as many rows of items from a list as will fit on the screen (screen_rows), one row should be highighted (sel_row) and the display should wrap if the user hits up arrow when the first item is highlighted or down arrow if the last item is highlighted (that is, the last item should be displayed and highlighted if the user hits up when the first item is highlighted).  Up arrow highlights the previous item and down arrow highlights the next item.
I've put something together, but am concerned I've missed something in testing. There must be a standard way to do this, given the prevalence of listboxes out there.
def up_key(self):
    if self.sel_row > 0:
       self.sel_row -= 1

    elif self.top_item > 0:  # top_item is the index of the first list item
        self.top_item -= 1

    elif self.top_item == 0:
        if self.n_lines >= self.screen_rows: # n_lines is the number of items in the list
            self.top_item = self.n_lines - self.screen_rows
            self.sel_row = min(self.screen_rows-1, self.n_lines-1)
        else:
            self.top_item = 0
            self.sel_row = self.n_lines-1

def down_key(self):
    if self.sel_row < self.screen_rows-1 and self.sel_row < self.n_lines-1:
        self.sel_row += 1

    elif self.sel_row == self.screen_rows-1:
        bottom_item = self.top_item + self.screen_rows
        if bottom_item == self.n_lines:
            self.top_item = 0
            self.sel_row = 0
        if bottom_item < self.n_lines:
            self.top_item += 1

    elif self.sel_row == self.n_lines-1:
        self.top_item = 0
        self.sel_row = 0

def set_pos(self, pos):  # display item with index pos
    if pos < 0:
        pos = 0
    elif pos >= self.n_lines:
        pos = self.n_lines - 1

    if pos < self.screen_rows:
        self.top_item = 0
        self.sel_row = pos
    else:
        self.sel_row = min(self.screen_rows, self.n_lines)//2 - 1
        self.top_item = pos - self.sel_row
        if self.top_item >= self.n_lines - self.screen_rows:
            self.top_item = self.n_lines - self.screen_rows - 1
            self.sel_row = pos - self.top_item - 1

EDIT: after each function I call a redraw screen function, which redraws the screen with top_item at the top and sel-row highlighted.
I've added a pseudo-code tag, in case someone has a version in something that's not python.

A: Few Python programs implement listboxes from scratch -- they're normally just taken from existing toolkits.  That may explain why there's no real cross-toolkit "standard"!-)
Coming to your code, I imagine set_pos is meant to be called right after either up_key or down_key are finished (you don't make this entirely clear).
My main worry would be the repetitiousness and asymmetry between your two _key routines.  Surely given that your specs are so similar for up and down keys, you want to delegate to a single function which takes an "increment" argument, either +1 or -1.  That common function could first do self.sel_row += increment, then immediately return in the common case where sel_row is still fine, i.e if self.top_item <= self.sel_row < self.top_item + self.screen_rows; otherwise deal with the cases where sel_row has exited the currently displayed region, by adjusting self.top_item, exiting if that causes no need to wraparound, or finally dealing with the wraparound cases.
I'd be keen to apply "flat is better than nested" by repeatedly using constructs of the form "do some required state chance; if things are now fine, return" rather than logically more complex "if doing a simple thing will be OK, then do the simple thing; else if something a bit more complicated but not terrible is needed, then do the complicated something; else if we're in a really complicated case, deal with the really complicated problem" -- the latter is far more prone to error and harder to follow in any case.


text:
Q: How can I apply_filters from inside a function? I have this function in theme-child/functions.php that shows a different total value in cart depending on the category of the chosen product:
add_filter( 'woocommerce_calculated_total', 'change_calculated_total', 10, 2 );

function change_calculated_total( $total, $cart ) {

    $symbol = 'U$';
    $value = 1;

    $cat_ids = array();
    foreach ( wc()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $cat_ids = array_merge(
            $cat_ids, $cart_item['data']->get_category_ids()
        );
    }
    if (in_array(70, $cat_ids)) {
        $symbol = 'AR$';
        $value = $value * 100;
    }

    add_filter( 'woocommerce_currency', $symbol ); // this line should call the function that changes the currency symbol.

    return $value;
}

And this one to change the currency symbol:
add_filter( 'woocommerce_currency_symbol', function( $symbol ) {
    return $symbol;
}

So in the first one, depending on the category id, I need to change the total value (working) and the currency symbol but I don't know how to call it.
Any ideas?
Thanks!


text:
Q: Error: Actions may not have an undefined "type" property when submitting react form I was following a tutorial here on how to link react with redux to a django api.  I have the django API set up and confirmed working.  But trying to connect react to it I've run into an issue I cannot solve.
Note:  The code from the tutorial can be viewed on github.  I think the issue in in the Login.js file, the code of which is below:
const Login = (props) => {
    if (props.isAuthenticated) {
        return (
            <Redirect to='/'/>
        )
    }
    return (
        <div className="login-page">
            <FormHome {...props}/>
        </div>
    )
};

const mapStateToProps = (state) => ({
    errors: authErrors(state),
    isAuthenticated: isAuthenticated(state)
})

const mapDispatchToProps = (dispatch) => ({
    onSubmit: (username, password) => {
        dispatch(login(username, password))
    }
})

export default connect(mapStateToProps, mapDispatchToProps)(Login);

Every time I submit the form, I get an error

Error: Actions may not have an undefined "type" property. Have you
  misspelled a constant?

I've basically copy and pasted most of the code from that tutorial/repo.  Yet whenever I try to submit the form, it gives me that error.
login action:
export const login = (username, password) => ({
    [RSAA]: {
        endpoint: '/api/auth/token/obtain/',
        method: 'POST',
        body: JSON.stringify({username, password}),
        headers: { 'Content-Type': 'application/json' },
        types: [
            LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE
        ]
    }
});


text:
Q: Syzygy between covariants of pairs of ternary quadratic forms In the book Nonlinear Computational Geometry, Page 208 (or page 15 of the online version on the author's website: http://www.loria.fr/~petitjea/papers/imaconics.pdf), Remark 5.1, Petitjean states that
"The joint covariants $Q_S,Q_T ,Q_U$ and $G$ are not algebraically
independent. They satisfy a fundamental syzygy which, when $Q_S =
Q_T = 0$, reduces to $\displaystyle G^2 = Q_U^3.$"
He stated this without a clear reference. He cited something related in Grace and Young's book The Algebra of Invariants, a fairly old book. I was only able to find a much older version (1873 instead of the 1908 version cited by Petitjean) and I do not see an identity in the relevant chapter which could be the full version of the syzygy mentioned above. This could however be my inability to read the notation in that book as it is quite alien to me.
Does anyone have a more modern reference where this syzygy is written down explicitly?

A: I emailed Professor Sylvain Petitjean regarding the syzygy, and he replied with a link to Salmon's classical treatise on invariant theory. To state the result, we recall that for a given pair $(A,B)$ of ternary quadratic forms, the action of $\operatorname{GL}_3(\mathbb{Z})$ on $(A,B)$ yields four invariants $a_3, a_2, a_1, a_0$, given as the coefficients of the binary cubic form
$$\displaystyle f(x,y) = \det(Ax + By) = a_3 x^3 + a_2 x^2 y + a_1 xy^2 + a_0 y^3.$$
Then by Salmon (https://archive.org/details/treatiseonconics00salmuoft), page 362, one has:
$$\displaystyle G^2 = Q_U^3 - Q_U^2(a_2 Q_S + a_1 Q_T) + Q_U (a_0 a_2 Q_S^2 + a_1 a_3 Q_T^2) + Q_U Q_S Q_T(a_2 a_1 - 3 a_3 a_0)$$
$$\displaystyle -a_0^2 a_3 Q_S^3 - a_0 a_3^2 Q_T^3 + a_0(2a_3 a_1 - a_2^2)Q_S^2 Q_T + a_3(2a_0 a_2 - a_1^2)Q_S Q_T^2.$$


text:
Q: Using docker, scrapy splash on Heroku I have a scrapy spider that uses splash which runs on Docker localhost:8050 to render javascript before scraping. I am trying to run this on heroku but have no idea how to configure heroku to start docker to run splash before running my web: scrapy crawl abc dyno. Any guides is greatly appreciated!

A: From what I gather you're expecting:

*

*Splash instance running on Heroku via Docker container

*Your web application (Scrapy spider) running in a Heroku dyno

Splash instance

*

*Ensure you can have docker CLI and heroku CLI installed

*As seen in Heroku's Container Registry - Pushing existing image(s):

*

*Ensure docker CLI and heroku CLI are installed

*heroku container:login

*docker tag scrapinghub/splash registry.heroku.com/<app-name>/web

*docker push registry.heroku.com/<app-name>/web

*To test the application: heroku open -a <app-name>. This should allow you to see the Splash UI at port 8050 on the Heroku host for this app name.

*

*You may need to ensure $PORT is set appropriately as the EXPOSE docker configuration is not respected (https://devcenter.heroku.com/articles/container-registry-and-runtime#dockerfile-commands-and-runtime)

Running Dyno Scrapy Web App

*

*Configure your application to point to <app-host-name>:8050. And the Scrapy spider should now be able to request to the Splash instance previously run.

A: Run at the same problem. Finally, I succesfully deployed splash docker image on Heroku.
This is my solution:
I cloned the splash proyect from github and changed the Dockerfile.

*

*Removed command EXPOSE because it's not supported by Heroku

*Replaced ENTRYPOINT by CMD command.

CMD python3 /app/bin/splash --proxy-profiles-path
  /etc/splash/proxy-profiles --js-profiles-path /etc/splash/js-profiles
  --filters-path /etc/splash/filters --lua-package-path /etc/splash/lua_modules/?.lua --port $PORT

Notice that I added the option --port=$PORT. This is just to listen at the port specified by Heroku instead of the default (8050)
A fork to the proyect with this change its avaliable here
You just need to build the docker image and push it to the heroku's registry, like you did before.
You can test it locally first but you must pass the environment variable "PORT" when running the docker

sudo docker run -p 80:80 -e PORT=80 mynewsplashimage


text:
Q: Samsung Galaxy 7" (GT-P6210) not detecting for USB debugging? I am using ubuntu Linux 10.04 Pc in that my Samsung Galaxy 7" (GT-P6210) homeycomb 3.2 is not detecting for development its showing in eclipse as
DeviceMonitor] Failed to start monitoring ????????????  in console
and in device tab its showing ?????????????.
Except this 7' GT-P6210 Samsung tablet all other Samsung devices are showing fine.
When I switch off the tablet and connected to the USB its showing the number and online as status.
List of devices attached
4641199B0F8488AE    device
why? whats the problem any solution.
NOTE:
I already Added 51-android.rules
Samsung 04E8

and also I enabled the USB debugging mode.
Its working fine in Mac.
EDIT:
I got the product id thru $ lsusb command
Bus 001 Device 010: ID 04e8:6860 Samsung Electronics Co., Ltd

I added product id in my rules.d file also
SUBSYSTEM=="usb", ATTRS{idVendor}=="04E8", ATTRS{idProduct}=="6860", MODE="0666", GROUP="plugdev"

after that I restarted udev
padmakumar@padmakumar-desktop:~$ sudo restart udev

then I tried
   padmakumar@padmakumar-desktop:~$ adb kill-server
    padmakumar@padmakumar-desktop:~$ adb start-server
    * daemon not running. starting it now on port 5037 *
    * daemon started successfully *
    padmakumar@padmakumar-desktop:~$ adb devices
    List of devices attached
    ?    ???????????    offline

//no luck so far
I found that its not detecting in updated ADT r16 and r15, except all other ADT version device is detecting very fine.
and also when device is in switch off mode its showing
name 464119990CEDAB9E, status as online and the OS version 3.2 in eclipse  device tab.
and in terminal also as below.
padmakumar@padmakumar-desktop:~$ adb devices
List of devices attached
464119990CEDAB9E    device

any idea.  Much appreciated :-)?

A: If, when you run adb devices, you see ???????????? in the list of devices, try stopping (adb kill-server) and restarting (adb start-server) the adb daemon.
Note that Samsung 04E8 is not a valid entry in 51-android.rules for udev. The correct line is:
SUBSYSTEM=="usb", SYSFS{idVendor}=="04e8", MODE="0666"

Also, make sure that you update the udev daemon after making this rules file change (sudo restart udev).

A: I'm having the same problem.  Strangely, I can sometimes get the device to list correctly, but other times, it just won't work.  Restarting my Linux laptop resolves the issue.  What a pain!!
Today, I discovered that if I suspend my laptop, then turn it back on, it detects the device correctly again!  That really beats restarting the OS.

A: Just stop and start adb server as root. Permissions issue will go away. Also udev step can be skipped.

A: Try this way, 1.Close Eclipse (IDE) first.
              2.Execute this command on terminal " adb kill-server"
              3.Now connect device to system wait, 10-20 seconds.
              4.Execute this command on terminal " adb start-server", Check device status with "adb devices " command.
              5 .Now open eclipse.

A: Maybe adding the vendor ID in ~/.android/adb_usb.ini would help?
Add a line with just 0x<!!!Your Vendor ID here!!!>, then run adb kill-server and adb start-server.
See this answer here: https://askubuntu.com/a/341696/387779.
It just saved me after nights of searching/testing/editing/pluging in and out and in again... so I thought it might be worth sharing. Thanks to Uygar Y for his answer.

A: I am using Ubuntu, what I did is killing and restarting the ADB server with a sudo privilege.
sudo adb kill-server
sudo adb start-server


text:
Q: Error 502 in OpenOfficeSpreadsheet formula The formula failing is the following:
=IF(TIMEVALUE(C2 & ":00") > TIMEVALUE(B2 & ":00"); 0; C2-B2)

I previously tried
=IF(C2 > B2; 0; C2-B2)

but this also gives me "Error 502".
The cells it is referring to contains data in the format "12:30" (I formatted the columns with format "HH:MM").
I just want to calculate how much time lies between two times, respecting the special case where endtime < starttime.

A: Using OpenOffice.org 3.1.1 with the following data:
Start          End            Elapsed
12:30:00 PM    05:30:00 PM    05:00:00
08:30:00 AM    05:30:00 PM    09:00:00
08:30:00 AM    08:00:00 AM    00:00:00

I used the following formula for the Elapsed column:
=IF(B2 < A2; 0; B2-A2)

Start and End use the formatting:
HH:MM:SS

And for the Elapsed column, I used
[HH]:MM

This seems to give the results you want.


text:
Q: jQuery Remove LI elements inside UL I am trying to fetch stores depending on the state the user Selects from a drop down.
<select name="addressInput" id="state" class="mx-stateSelect" onchange='getRetailers()'>
    <option value=""> Choose State</option>
    <option value="Alberta"> Alberta Canada</option>
    <option value="Alaska"> Alaska </option>
    <option value="Alabama">Alabama</option>
    ...
    <option value="Washington"> Washington </option>
</select>

jQuery Function
function getRetailers() {
    var state = $('#state').val();
    var searchUrl = 'getRetailers.php?state=' + state;

    $.getJSON(searchUrl, function(data) {
        var items = [];

        $.each(data, function(key, val) {
            items.push('
' + val.name + '
' + val.address + ', ' + val.city + ', ' + val.zipcode + ' ' + val.stab + '
');
        });

        $('
', {
            'class' : 'mx-retailers',
            html : items.join('')
        }).appendTo('.mx-retailerResult');
    });
}

This is adding another set of UL LI to the code. Where as i want to replace the old LI with the new LI i fetch from the database.
HTML Code

I want to remove all the LI Element inside the UL and replace it with Fresh content from the database

A: This block of code you have is creating a new UL element with a class of mx-retailers:
$('
', {
            'class' : 'mx-retailers',
            html : items.join('')
        }).appendTo('.mx-retailerResult');

If you dont want to do this then replace it with the following:
items.join('').appendTo('.mx-retailerResult');

This will add all of your li elements into the ul with the class of mx-retailerResult

A: $('
', {
    'class' : 'mx-retailers',
    html : items.join('')
}).appendTo('.mx-retailerResult');

the above code creates a new ul element try
$('ul.mx-retailers').html(items.join(''));

A: $('.mx-retailerResult').html($('
', {
    'class' : 'mx-retailers',
    html : items.join('')
}));


text:
Q: My server keeps on putting mail in my user's home folder and I can't find the config to change it For some reason, my user's mailbox is inside my home folder. Full path looks like this: /home/$USER/var/mail.
What config file defines what folder my mailbox is in?
The mail server I'm using is whatever ubuntu's default is, I think it's postfix? It's literally just cron sending me mail.


text:
Q: XSLT moving items inside other tag at the same level I have this problem for xslt:
This is the input file:
  <root>
   <header/>
   <item/>
   … other n-1 <item/>
   <header/>
   <item/>
   … other m-1 <item/>
  </root>

so header and item are at the same level (/root).
it must be converted in something like:
<root2>
  <header2>
     <item2/>
     …<item2/> // the first n-items up
  </header2>
  <header2>
     <item2/>
     …<item2/> // the last m-items up
  </header2>
</root2>

so basically the first n-item must be moved in the first header while the second group of items must be moved in the second header. Any idea how to get this?
Thanks
Randomize

A: Sample XML:
<root>
    <header/>
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <header/>
    <item>5</item>
    <item>6</item>
    <item>7</item>
</root>

XSLT using grouping:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <xsl:key name="k" match="item" use="count(preceding-sibling::header)"/>

    <xsl:template match="/">
        <root2>
            <xsl:apply-templates select="root/item[generate-id(.) = generate-id(key('k', count(preceding-sibling::header)))]" mode="a"/>
        </root2>
    </xsl:template>

    <xsl:template match="item" mode="a">
        <header2>
            <xsl:apply-templates select="key('k', count(preceding-sibling::header))"/>
        </header2>
    </xsl:template>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Or simple particular XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <xsl:template match="/">
        <root2>
            <header2>
                <xsl:apply-templates select="root/item[count(preceding-sibling::header) = 1]"/>
            </header2>
            <header2>
                <xsl:apply-templates select="root/item[count(preceding-sibling::header) = 2]"/>
            </header2>
        </root2>
    </xsl:template>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Both produce the same output:
<root2>
  <header2>
    <item>1</item>
    <item>2</item>
    <item>3</item>
  </header2>
  <header2>
    <item>5</item>
    <item>6</item>
    <item>7</item>
  </header2>
</root2>

A: This is a simpler more efficient XSLT 1.0 solution, than counting all preceding siblings:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:key name="kFollowing" match="item"
  use="generate-id(preceding-sibling::header[1])"/>

 <xsl:template match="/*">
  <root>
   <xsl:apply-templates select="header"/>
  </root>
 </xsl:template>

 <xsl:template match="header">
  <heather2>
   <xsl:copy-of select="key('kFollowing', generate-id())"/>
  </heather2>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the following XML document:
<root>
    <header/>
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <header/>
    <item>5</item>
    <item>6</item>
    <item>7</item>
</root>

the wanted, correct result is produced:
<root>
   <heather2>
      <item>1</item>
      <item>2</item>
      <item>3</item>
   </heather2>
   <heather2>
      <item>5</item>
      <item>6</item>
      <item>7</item>
   </heather2>
</root>

Explanation:
A key is defined in such a way that for a header any of the immediately-following item elements is matched by the generate-id() of this header.
II. XSLT 2.0 solution:
<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/*">
  <root>
   <xsl:for-each-group select="item"
        group-adjacent=
         "generate-id(preceding-sibling::header[1])">
     <header2>
      <xsl:sequence select="current-group()"/>
     </header2>
   </xsl:for-each-group>
  </root>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the same XML document (above), the same correct result is produced:
<root>
   <header2>
      <item>1</item>
      <item>2</item>
      <item>3</item>
   </header2>
   <header2>
      <item>5</item>
      <item>6</item>
      <item>7</item>
   </header2>
</root>

Explanation: Use of xsl:for-each-group, group-adjacent, current-group()


text:
Q: What is the best way to plot 3d data in matlab? If i have data in NxN grid format (for example see figure) and each cell size is given by (Xmax/N) x (Ymax/N) and data given in each cell is the frequency data of that cell. What is the best way to graphically represent this data in MATLAB such that it is easy to view the frequency for each cell? If I would like to make it like in this example (see colormap), how can I do that what function should I used?

A: Your choice. Here I put several possibilities:

*

*bar3: if you the points are discrete by meaning

*

*surf or mesh : if the points are continuous by meaning

-imshow or image

*

*in MATLAB 2017b or newer, heatmap

-contour, if you have a sufficiently detailed data

There may be more, please feel free to add them to the post.


text:
Q: Convert information in a text file to a map using ArcGIS Runtime SDK? I am new to the ArcGIS Runtime SDK. What we are trying to do is to convert information in a text file (contains country name and some information) to a map (visualize the information as a heat map for example). Do we have to convert the text file to a shapefile?
If yes, does the Runtime SDK provide API's for it or we have to go back to Engine SDK?

A: No you do not need to convert your text file to a shapefile.  The ArcGIS Java Runtime SDK does not provide a tool to convert, although it does have an API to work with shapefiles.  Does the text file have geometry info, e.g. coordinates?  Essentially you can read the text file in Java then use the GraphicsLayer to add the graphic with geometry, symbol, attributes from the text file. If the text file is a CSV file you can use the ArcGIS Java API to work directly with it through CSVLayer.  How you work with the text file will depend on the format of the file, e.g. geoJSON, etc.


text:
Q: Android: Tabs at the BOTTOM I've seen some chatter about this, but nothing definite.
Is there a way to put the tabs in a TabWidget to the bottom of the screen?
If so, how?
I've tried the following, but didn't work:
a) setting the tabwidget below the framelayout
b) setting the tabwidget's gravity to "bottom"
Thanks!
llappall

A: Try it ;)
Just watch the content of the FrameLayout(@id/tabcontent), because I don't know how it will handle in case of scrolling... In my case it works because I used ListView as the content of my tabs. :)
Hope it helps.
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <FrameLayout android:id="@android:id/tabcontent"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent"
             android:layout_alignParentTop="true"
             android:layout_above="@android:id/tabs" />
    <TabWidget android:id="@android:id/tabs"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:layout_alignParentBottom="true" />
    </RelativeLayout>
</TabHost>

A: For all those of you that try to remove the separating line of the tabWidget, here is an example project (and its respective tutorial), that work great for customizing the tabs and thus removing problems when tabs are at bottom.
Eclipse Project: android-custom-tabs ;
Original explanation: blog;
Hope this helped.

A: Not sure if it will work for all versions of Android (especially those with custom UI stuff), but I was able to remove the gray bar at the bottom by adding
 android:layout_marginBottom="-3dp"

to the TabWidget XML...

A: There are two ways to display tabs at the bottom of a tab activity.

*

*Using relative layout

*Using Layout_weight attribute

Please check the link for more details.

A: Here's the simplest, most robust, and scalable solution to get tabs on the bottom of the screen.

*

*In your vertical LinearLayout, put the FrameLayout above the TabWidget

*Set layout_height to wrap_content on both FrameLayout and TabWidget

*Set FrameLayout's android:layout_weight="1"

*Set TabWidget's android:layout_weight="0" (0 is default, but for emphasis, readability, etc)

*Set TabWidget's android:layout_marginBottom="-4dp" (to remove the bottom divider)

Full code:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp">

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:layout_weight="1"/>

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:layout_marginBottom="-4dp"/>

    </LinearLayout>

</TabHost>

A: There is a way to remove the line.
1) Follow this tutorial:
    android-tabs-with-fragments
2) Then apply the RelativeLayout change that Leaudro suggested above (apply the layout props to all FrameLayouts).
You can also add an ImageView to the tab.xml in item #1 and get a very iPhone like look to the tabs.
Here is a screenshot of what I'm working on right now. I still have some work to do, mainly make a selector for the icons and ensure equal horizontal distribution, but you get the idea.
In my case, I'm using fragments, but the same principals should apply to a standard tab view.

A: This may not be exactly what you're looking for (it's not an "easy" solution to send your Tabs to the bottom of the screen) but is nevertheless an interesting alternative solution I would like to flag to you :
ScrollableTabHost is designed to behave like TabHost, but with an additional scrollview to fit more items ...
maybe digging into this open-source project you'll find an answer to your question. If I see anything easier I'll come back to you.

A: Yes, see: link, but he used xml layouts, not activities to create new tab, so put his xml code (set paddingTop for FrameLayout - 0px) and then write the code:
public class SomeActivity extends ActivityGroup {

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

    TabHost tab_host = (TabHost) findViewById(R.id.edit_item_tab_host);

    tab_host.setup(this.getLocalActivityManager());

    TabSpec ts1 = tab_host.newTabSpec("TAB_DATE");
    ts1.setIndicator("tab1");
    ts1.setContent(new Intent(this, Registration.class));
    tab_host.addTab(ts1);

    TabSpec ts2 = tab_host.newTabSpec("TAB_GEO");
    ts2.setIndicator("tab2");
    ts2.setContent(new Intent(this, Login.class));
    tab_host.addTab(ts2);

    TabSpec ts3 = tab_host.newTabSpec("TAB_TEXT");
    ts3.setIndicator("tab3");
    ts3.setContent(new Intent(this, Registration.class));
    tab_host.addTab(ts3);

    tab_host.setCurrentTab(0);

}

}

A: I was having the same problem with android tabs when trying to place them on the bottom of the screen. My scenario was to not use a layout file and create the tabs in code, I was also looking to fire activities from each tab which seemed a bit too complex using other approaches so, here is the sample code to overcome the problem:
adding-tabs-in-android-and-placing-them

A: I recomend use this code for stable work, it optimized for nested fragments in tab (for example nested MapFragment) and tested on "do not keep activities": https://stackoverflow.com/a/23150258/2765497


text:
Q: Detecting JComboBox editing I have a JComboBox, once every second I want to retreive a set of strings from a database and set those strings to the contents of the JComboBox, and one of them as the currently selected value.  But I also want the user to be able to edit the JComboBox and add a value to the database and set it as the current value.
I want to the be able to detect when characters are entered into the JComboBox, so I can reset a count down which prevents updating the JComboBox as long as it's not zero.  My first instinct was to use a KeyListener but the Java tutorial on combo boxes says this,

Although JComboBox inherits methods to register listeners for
  low-level events — focus, key, and mouse events, for example — we
  recommend that you don't listen for low-level events on a combo box.

And they go on to say that the events fired may change depending on the look and feel.

A: This is a little dicey, but it should work to listen to the Document updates on the Editor component (A JTextField).
    JComboBox cb = new JComboBox();
    Component editor = cb.getEditor().getEditorComponent();
    if (editor instanceof JTextField) {
        ((JTextField) editor).getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent documentEvent) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void removeUpdate(DocumentEvent documentEvent) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void changedUpdate(DocumentEvent documentEvent) {
                //To change body of implemented methods use File | Settings | File Templates.
            }
        });
    }

Those *Update(DocumentEvent documentEvent) methods should get called for every character typed/deleted from the JComboBox.

A: I would like to add that the changedUpdate method will not fire a notification for plain text documents.  If you are using a plain text text component, you must use insertUpdate and/or removeUpdate.
I recently had to use a document listener as a way of disabling/enabling a button if the user was editing the combo box.  I did something like this and worked very well:
public class MyDocumentListener implements DocumentListener
{

  @Override
  public void insertUpdate(DocumentEvent e)
  {
     setChanged();
     notifyObservers(true);
  }

  @Override
  public void removeUpdate(DocumentEvent e)
  {
     setChanged();
     notifyObservers(false);
  }

  @Override
  public void changedUpdate(DocumentEvent e)
  {
     // Not used when document is plain text
  }
}

Then, I added this listener to the combo box like this:
((JTextComponent) combobox.getEditor().getEditorComponent())
    .getDocument().addDocumentListener(new MyDocumentListener());

This works because the document associated with the combo box is plain text.  When I used changedUpdate it did not.


text:
Q: redirect_field_name DJANGO didn't work I would redirect the user to "admin" page if he is superuser, else to normal "profile" but it didn't work
urls.py
 url(r'^user/login/', LoginUserView.as_view(), name='login'),
 url(r'^user/profile/', UpdateUserView.as_view(), name='profile'),
 url(r'^user/admin/$', UpdateAdminView.as_view(), name='admin'),

views.py
class LoginUserView(auth_views.LoginView):
    template_name = "Login/login.html"
    #TODO
    def dispatch(self, request, *args, **kwargs):
        if self.request.user.is_superuser:
            self.redirect_field_name = reverse_lazy("admin")
        else:
            self.redirect_field_name = reverse_lazy("profile")
        return super(LoginUserView, self).dispatch(request, *args, **kwargs)

A: Setting redirect_field_name isn't going to work - it is the name of a parameter, by default 'next', not the url to redirect to.
If you want to the success url, you should override get_success_url.
class LoginUserView(auth_views.LoginView):
    template_name = "Login/login.html"
    def get_success_url(self):
        url = self.get_redirect_url()
        if url:
            return url
        elif self.request.user.is_superuser:
            return reverse("admin")
        else:
            return reverse("profile")

The get_redirect_url() call at the beginning of the method means that the default behaviour that tries to use the redirect field will still work.

A: "e" is missing in:
self.redirect_field_name = reverse_lazy("profile")


text:
Q: How to create surface from 3-D numpy array in Pyopengl? I have created a 3-d numpy array consisting of X, Y, and Z axis coordinates. Now I am trying to create a surface using these points in opengl but all I have got success is in creating wire model something like this below . Can anyone suggest changes in my code to form actual 3-D surface from data?
Data file used link https://drive.google.com/open?id=1PWbNIt3xbchtQ9HIIS96k7ZjblzPO_wO
Code:-
import OpenGL.GL as gl
import OpenGL.arrays.vbo as glvbo
from PyQt5.Qt import *
import numpy as np
import Backend_algo as Sb
import sys
import ctypes

def compile_vertex_shader(source):
    """Compile a vertex shader from source."""
    vertex_shader = gl.glCreateShader(gl.GL_VERTEX_SHADER)
    gl.glShaderSource(vertex_shader, source)
    gl.glCompileShader(vertex_shader)
    # check compilation error
    result = gl.glGetShaderiv(vertex_shader, gl.GL_COMPILE_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetShaderInfoLog(vertex_shader))
    return vertex_shader

def compile_fragment_shader(source):
    """Compile a fragment shader from source."""
    fragment_shader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
    gl.glShaderSource(fragment_shader, source)
    gl.glCompileShader(fragment_shader)
    result = gl.glGetShaderiv(fragment_shader, gl.GL_COMPILE_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetShaderInfoLog(fragment_shader))
    return fragment_shader

def link_shader_program(vertex_shader, fragment_shader):
    """Create a shader program with from compiled shaders."""
    program = gl.glCreateProgram()
    gl.glAttachShader(program, vertex_shader)
    gl.glAttachShader(program, fragment_shader)
    gl.glLinkProgram(program)

    result = gl.glGetProgramiv(program, gl.GL_LINK_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetProgramInfoLog(program))
    return program

VS = '''

attribute vec3 position;

uniform float right;
uniform float bottom;
uniform float left;
uniform float top;
uniform float far;
uniform float near;

void main() {

    mat4 testmat = mat4(
            vec4(2.0 / (right - left), 0, 0, 0),
            vec4(0, 2.0 / (top - bottom), 0, 0),
            vec4(0, 0, -2.0 / (far - near), 0),
            vec4(-(right + left) / (right - left), -(top + bottom) / (top - bottom), -(far + near) / (far - near), 1)
    );

    gl_Position = testmat * vec4(position, 1.);

}

'''
FS = '''
#version 450
// Output variable of the fragment shader, which is a 4D vector containing the
// RGBA components of the pixel color.
uniform vec3 triangleColor;
out vec4 outColor;

void main()
{
    outColor = vec4(triangleColor, 1.0);
}
'''

class GLPlotWidget3D(QGLWidget):

    def __init__(self, *args):
        # QGLWidget.__init__(self)
        super(GLPlotWidget3D, self).__init__()
        # self.parent = args[0]
        self.width, self.height = 100, 100
        self.right, self.left, self.top, self.bottom = 21000, -21000, 10, -10
        self.data = np.zeros((3, 10, 2))
        self.vbo = glvbo.VBO(self.data)

        self.showMaximized()

    def initializeGL(self):
        vs = Sb.compile_vertex_shader(VS)
        fs = Sb.compile_fragment_shader(FS)
        self.shaders_program = link_shader_program(vs, fs)
        self.e = np.load(('three.npy'), mmap_mode='r')
        self.e = np.array(self.e, dtype=np.float32)

        self.right, self.left, self.top, self.bottom, self.far, self.near = self.e[:, :, 1].min(), self.e[:, : , 1].max(), self.e[:, : , 0].min(), self.e[:, : , 0].max(), self.e[:, : , 2].max(), self.e[:, : , 2].min()

    def ortho_view(self):
        right = gl.glGetUniformLocation(self.shaders_program, "right")
        gl.glUniform1f(right, self.right)

        left = gl.glGetUniformLocation(self.shaders_program, "left")
        gl.glUniform1f(left, self.left)

        top = gl.glGetUniformLocation(self.shaders_program, "top")
        gl.glUniform1f(top, self.top)

        bottom = gl.glGetUniformLocation(self.shaders_program, "bottom")
        gl.glUniform1f(bottom, self.bottom)

        far = gl.glGetUniformLocation(self.shaders_program, "far")
        gl.glUniform1f(far, self.far)

        near = gl.glGetUniformLocation(self.shaders_program, "near")
        gl.glUniform1f(near, self.near)

    def paintGL(self):
        self.resizeGL(self.width, self.height)
        gl.glClearColor(0.2, 0.2, 0.2, 0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        gl.glUseProgram(self.shaders_program)

        buffer = gl.glGenBuffers(1)

        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffer)
        stride = self.e.strides[0]
        offset = ctypes.c_void_p(1)
        loc = gl.glGetAttribLocation(self.shaders_program, "position")
        gl.glEnableVertexAttribArray(loc)
        gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, stride, offset)
        gl.glBufferData(gl.GL_ARRAY_BUFFER, self.e.nbytes, self.e, gl.GL_DYNAMIC_DRAW)

        gl.glDrawArrays(gl.GL_LINE_LOOP, 0, self.e.shape[0])

        self.ortho_view()
        uni_color = gl.glGetUniformLocation(self.shaders_program, "triangleColor")
        gl.glUniform3f(uni_color, 0.9, 0.9, 0.9)

    def resizeGL(self, width, height):
        self.width, self.height = width, height
        gl.glViewport(0, 0, width, height)

def main():
    app = QApplication(sys.argv)
    editor = GLPlotWidget3D()
    editor.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

A: 'three.npy' contains a 3 dimensional array (7782 x 24 x3) with the vertex coordinates of a tube. The 3rd dimension with a size of 3 contains the x, y and z coordinates of the vertices. The vertices are organized in 7782 rings with 24 point around the circumference.
Read the vertex coordinates to a flatten buffer (the numpy array is flatten automatically by glBufferData).
Generate an array of indices (indices of the vertex buffer). The indices describe GL_TRIANGLE_STRIP primitives which stack up 7781 rings. Each ring consisting of 24 quads around the circumference.
self.e = np.load(('three.npy'), mmap_mode='r')
self.e = np.array(self.e, dtype=np.float32)

self.elems = []
ring_c = self.e.shape[1]
slice_c = self.e.shape[0]
for si in range(slice_c-1):
    self.elems += [si*ring_c, si*ring_c]
    for ri in range(ring_c+1):
        ie = ri % ring_c
        self.elems += [ie+si*ring_c, ie+(si+1)*ring_c]
self.elems = np.array(self.elems, dtype=np.int32)

The x  and y component of the vertices are in range [-10, 10], but the z component is in range [3, 29724672].
x min      x max     y min      y max     z min      z max
-10.589109 10.517833 -10.464569 10.594374 29724672.0 3.1618009

I recommend to define a scale for the z coordinate:
self.scaleZ = 0.000001

Create a Vertex Buffer Object (GL_ARRAY_BUFFER) for the vertices and an Index buffer Object (GL_ELEMENT_ARRAY_BUFFER) for the indices:
self.vertexbuffer = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertexbuffer)
gl.glBufferData(gl.GL_ARRAY_BUFFER, self.e, gl.GL_DYNAMIC_DRAW)

self.elementbuffer = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.elementbuffer)
gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, self.elems, gl.GL_DYNAMIC_DRAW)

Specif the array of vertex coordinates. See Vertex Specification.
The stride and offset parameter of glVertexAttribPointer have to be 0.
stride specifies the byte offset between consecutive generic vertex attributes it has to be either 3*self.e.itemsize (12) or 0. 0 has a special meaning and and interprets the attributes as to be tightly packed. If stride is 0 it is computed by the size and type parameter.
offset hast to be ctypes.c_void_p(0) or None, because the offset of the 1 attribute in the array is 0.
In any case the unit of stride and offset is bytes.
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertexbuffer)
stride = 0 # 3*self.e.itemsize
offset = None # ctypes.c_void_p(0)
loc = self.attrib['position']
gl.glEnableVertexAttribArray(loc)
gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, stride, offset)

The primitive type is GL_TRIANGLE_STRIP and the index buffer has to be bound before the elements are drawn by glDrawElements:
gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.elementbuffer)

self.perspective_view()
gl.glUniform3f(self.uniform['triangleColor'], 1, 1, 1)
gl.glDrawElements(gl.GL_TRIANGLE_STRIP, self.elems.size, gl.GL_UNSIGNED_INT, None)

Instead of specifying an Orthographic projection matrix in the vertex shader, I recommend to use matrix Uniform variable for the projection, respectively model and view transformation.
The projection matrix defines the projection of the 3 dimensional viewing volume to the 2 dimensional viewport. The view matrix defines the viewing position of view and viewing direction onto the scene. The model matrix defines the scale and animation of the mode.
attribute vec3 position;

uniform mat4 u_proj;
uniform mat4 u_view;
uniform mat4 u_model;

void main() {

    gl_Position = u_proj * u_view * u_model * vec4(position, 1.0);
}

Get the attribute index and uniform locations after the shader program is linked:
vs = compile_vertex_shader(VS)
fs = compile_fragment_shader(FS)
self.shaders_program = link_shader_program(vs, fs)
self.attrib = { a : gl.glGetAttribLocation (self.shaders_program, a) for a in ['position'] }
print(self.attrib)
self.uniform = { u : gl.glGetUniformLocation (self.shaders_program, u) for u in ['u_model', 'u_view', 'u_proj', "triangleColor"] }
print(self.uniform)

For a 3D look, I recommend to use Perspective projection rather than Orthographic projection.
Use numpy.array or numpy.matrix to set the matrices.
# projection matrix
aspect, ta, near, far = self.width/self.height, np.tan(np.radians(90.0) / 2), 0.1, 50
proj = np.matrix(((1/ta/aspect, 0, 0, 0), (0, 1/ta, 0, 0), (0, 0, -(far+near)/(far-near), -1), (0, 0, -2*far*near/(far-near), 0)), np.float32)

# view matrix
view = np.matrix(((1, 0, 0, 0), (0, 0, -1, 0), (0, 1, 0, 0), (0, 0, -30, 1)), np.float32)

# model matrix
c, s = math.cos(self.angle), math.sin(self.angle)
model = scale

gl.glUniformMatrix4fv(self.uniform['u_proj'], 1, gl.GL_FALSE, proj)
gl.glUniformMatrix4fv(self.uniform['u_view'], 1, gl.GL_FALSE, view)
gl.glUniformMatrix4fv(self.uniform['u_model'], 1, gl.GL_FALSE, model)

Full example:
(The fragment shader tints the fragments dependent on their depth)

import OpenGL.GL as gl
import OpenGL.arrays.vbo as glvbo
from PyQt5.Qt import *
import numpy as np
#import Backend_algo as Sb
import sys
import ctypes
import os
import math

sourceFileDir = os.path.dirname(os.path.abspath(__file__))

def compile_vertex_shader(source):
    """Compile a vertex shader from source."""
    vertex_shader = gl.glCreateShader(gl.GL_VERTEX_SHADER)
    gl.glShaderSource(vertex_shader, source)
    gl.glCompileShader(vertex_shader)
    # check compilation error
    result = gl.glGetShaderiv(vertex_shader, gl.GL_COMPILE_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetShaderInfoLog(vertex_shader))
    return vertex_shader

def compile_fragment_shader(source):
    """Compile a fragment shader from source."""
    fragment_shader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
    gl.glShaderSource(fragment_shader, source)
    gl.glCompileShader(fragment_shader)
    result = gl.glGetShaderiv(fragment_shader, gl.GL_COMPILE_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetShaderInfoLog(fragment_shader))
    return fragment_shader

def link_shader_program(vertex_shader, fragment_shader):
    """Create a shader program with from compiled shaders."""
    program = gl.glCreateProgram()
    gl.glAttachShader(program, vertex_shader)
    gl.glAttachShader(program, fragment_shader)
    gl.glLinkProgram(program)

    result = gl.glGetProgramiv(program, gl.GL_LINK_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetProgramInfoLog(program))
    return program

VS = '''
attribute vec3 position;

uniform mat4 u_proj;
uniform mat4 u_view;
uniform mat4 u_model;

void main() {

    gl_Position = u_proj * u_view * u_model * vec4(position, 1.0);
}
'''

FS = '''
#version 450
out vec4 outColor;

uniform vec3 triangleColor;

void main()
{
    float d = 1.0 - gl_FragCoord.z;
    outColor = vec4(triangleColor * d, 1.0);
}
'''

class GLPlotWidget3D(QGLWidget):

    def __init__(self, *args):
        # QGLWidget.__init__(self)
        super(GLPlotWidget3D, self).__init__()
        # self.parent = args[0]
        self.width, self.height = 100, 100
        self.right, self.left, self.top, self.bottom = 21000, -21000, 10, -10
        self.data = np.zeros((3, 10, 2))
        self.vbo = glvbo.VBO(self.data)

        self.showMaximized()

    def initializeGL(self):

        vs = compile_vertex_shader(VS)
        fs = compile_fragment_shader(FS)
        self.shaders_program = link_shader_program(vs, fs)
        self.attrib = { a : gl.glGetAttribLocation (self.shaders_program, a) for a in ['position'] }
        print(self.attrib)
        self.uniform = { u : gl.glGetUniformLocation (self.shaders_program, u) for u in ['u_model', 'u_view', 'u_proj', "triangleColor"] }
        print(self.uniform)

        self.e = np.load((os.path.join(sourceFileDir,'three.npy')), mmap_mode='r')
        self.e = np.array(self.e, dtype=np.float32)
        print(self.e.shape)

        self.elems = []
        ring_c = self.e.shape[1]
        slice_c = self.e.shape[0]
        for si in range(slice_c-1):
            self.elems += [si*ring_c, si*ring_c]
            for ri in range(ring_c+1):
                ie = ri % ring_c
                self.elems += [ie+si*ring_c, ie+(si+1)*ring_c]

        self.elems = np.array(self.elems, dtype=np.int32)

        self.vertexbuffer = gl.glGenBuffers(1)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertexbuffer)
        gl.glBufferData(gl.GL_ARRAY_BUFFER, self.e, gl.GL_DYNAMIC_DRAW)

        self.elementbuffer = gl.glGenBuffers(1)
        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.elementbuffer)
        gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, self.elems, gl.GL_DYNAMIC_DRAW)

        self.scaleZ = 0.000001
        self.right, self.left, self.top, self.bottom, self.far, self.near = self.e[:, :, 1].min(), self.e[:, : , 1].max(), self.e[:, : , 0].min(), self.e[:, : , 0].max(), self.e[:, : , 2].max(), self.e[:, : , 2].min()
        print(self.right, self.left, self.top, self.bottom, self.far, self.near)
        self.far *= self.scaleZ
        self.near *= self.scaleZ
        self.angle = 0.0

        self.GLtimer = QTimer()
        self.GLtimer.setInterval(10)
        self.GLtimer.timeout.connect(self.redraw)
        self.GLtimer.start()

    def redraw(self):
        self.angle += 0.01
        self.update()

    def perspective_view(self):

        # projection matrix
        aspect, ta, near, far = self.width/self.height, np.tan(np.radians(90.0) / 2), 10, 50
        proj = np.matrix(((1/ta/aspect, 0, 0, 0), (0, 1/ta, 0, 0), (0, 0, -(far+near)/(far-near), -1), (0, 0, -2*far*near/(far-near), 0)), np.float32)

        # view matrix
        view = np.matrix(((1, 0, 0, 0), (0, 0, -1, 0), (0, 1, 0, 0), (0, 0, -30, 1)), np.float32)

        # model matrix
        c, s = math.cos(self.angle), math.sin(self.angle)
        scale = np.matrix(((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, self.scaleZ, 0), (0, 0, 0, 1)), np.float32)
        rotZ = np.array(((c, s, 0, 0), (-s, c, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)), np.float32)
        rotY = np.matrix(((0, 0, 1, 0), (0, 1, 0, 0), (-1, 0, 0, 0), (0, 0, 0, 1)), np.float32)
        trans = np.matrix(((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, (self.near - self.far)/2, 1)), np.float32)
        model = scale * trans * rotY * rotZ

        gl.glUniformMatrix4fv(self.uniform['u_proj'], 1, gl.GL_FALSE, proj)
        gl.glUniformMatrix4fv(self.uniform['u_view'], 1, gl.GL_FALSE, view)
        gl.glUniformMatrix4fv(self.uniform['u_model'], 1, gl.GL_FALSE, model)

    def paintGL(self):
        self.resizeGL(self.width, self.height)
        gl.glClearColor(0.2, 0.2, 0.2, 0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glUseProgram(self.shaders_program)

        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertexbuffer)
        stride = 0 # 3*self.e.itemsize
        offset = None # ctypes.c_void_p(0)
        loc = self.attrib['position']
        gl.glEnableVertexAttribArray(loc)
        gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, stride, offset)

        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.elementbuffer)

        self.perspective_view()
        gl.glUniform3f(self.uniform['triangleColor'], 1, 1, 1)
        #gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE)
        gl.glDrawElements(gl.GL_TRIANGLE_STRIP, self.elems.size, gl.GL_UNSIGNED_INT, None)

    def resizeGL(self, width, height):
        self.width, self.height = width, height
        gl.glViewport(0, 0, width, height)

def main():
    app = QApplication(sys.argv)
    editor = GLPlotWidget3D()
    editor.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


text:
Q: Does AWS Educate allow the creation of NAT gateways? I am trying to have quick access to the internet from a private subnet. I get this error message when creating a NAT gateway:
There was an error creating your NAT gateway
You are not authorized to perform this operation. Encoded authorization failure message: PhLNSSs-pGaEXTXgy-Xfa-MWP2msuWBlj5q4xpM3DPEhewnsJ3pTcuVIQftrI_FaPsDU74zDPp9pg8O_hdq39bTOoKBh-hKIg9Cp4EElcPOCLzXeFtFpuLYegNGXg2I-hH1dhqI-wkARlwEaUS3shD0XNCuxHoKKUpf5dyFKxKUWlSKtxPKw6rSXkvySCJ8Eq3tdTmkaFC3zUiuSCkAd_DmJRvAzD_kPlwaE_NvUi-kaGBYZOvFe4Ba6KuhDf3QkRpfnD5x-JqzjjNwaBbEOz9wUmpPzCB1HbNrDCPvvyQ5Eo9veXypMKBlZyxv7JSO7Q1QQ3PTfyRT3VSQ9_E0A8dvcN-xo4y-5r8weHgZleQz22t7uN-67bSWFkdCbKet-mPJc1gsBrO3yc-EuQL7Kz-BD8qK4xcCS8XvdFR-ue4n7zgQPnS35nvlXSBdxPk9RS05BvFWmAbrU8Q09eW83OnW03zwOrRQbYfostQ45QOnagSOK8MxEK_UFNBtBCYN7zFY8XB-7ovvbfaMqrQnsT5UPKreRL80CnGt7JLotD1mJ3A2RRzyuKNgAfe0KD6PkFxXY0ZaNRDL2LNCO5vv8qxcz_dx7e1s8kjuExyWN9phCeMRdxxuUpVMTuGAewDw37Z5FWluWYfCXf-8MfccGruQW2KuIzkTrd1CGj9x2EL5fqu38WHcOtKILILLWt6JiHNH8s2_HMrlpKxOXUHC-NiPVbcVSjbylfEa55l0-jtZRNw2C1LKGMZwjXYxWM7sJtMisYp-Xqprwh-1CwDfVygn9RwFC-49SiicPNUjOAhuHUMVqUTtZOA3117FZkY2ZsaJP29W0xC5j91AUVlYjHrkpzCdmAvNn-1F5l4NKoA6XSoOgPBkQny-JAVmwek90zUmWB1zTS7LRloG7Rm7NEpRtIQp2pBRtMG8kI9wKOo5gCvK-gWq6_jdj4KRxHHr4x_e-J2z7ozFNCC9NucbWVBeLgYY5kwivQsXqt6bgQBVZ0mtbKVHacRt3PToXwUSzgGTZwwJAVpIATBs58uF97kbGbyxz2A3UUbaUMXlxoUjD5DDZTd8yVScN7S82_L-YknHIMTFgaeSEdiOtvNASYisQEEs3cVIMesjQov-DhtQd7X_itMXt1pmT87uQLCXwsOhQ49EZlSCL_I51yKIVMPEzOyWA5poiw5AwJig

is there an alternative way to do so with an AWS educate account?