File Path as Command Line Argument

Question: This is very common thing but i am very confused to get around this.
Taking file path as command line argument in c#.
If i give input "F:\\" then this works perfect.
But when i give input "F:\" it gives output like F:".
I know this is because of backslash escape character.
But my problem is how to get around this without modifying user input because logically user input is correct.
Is it possible without modifying user input get correct path in this situation?
I also know that there is @ character which can be used.
But as i said this is command line argument so the string is already in variable.
I also read some blogs but still i remain unable to resolve my problem.
C# Command-Line Parsing of Quoted Paths and Avoiding Escape Characters
EDIT :Actually my program is to list all the files inside directory so i am first checking for Directory.Exists(command line arguments) and then getting list of all the files if directory exist.
Ok so in that case when user gives Command line argument as i shown above logically the drive exist but just because of escape character it returns false.
Just think about printing the command line argument as follow.
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("{0}", args[0]);

        Console.Read();
    }
}

I am having very less knowledge of c# thanks for helping.
Comment: You should post some code for us to see.
Comment: Can you post the relevant part of your code?
Comment: "I am having no knowledge of c# thanks for helping." - with that in mind, are you sure you are in the correct position to be working on a program rather than reading tutorials and programming teaching books?
Comment: Please, do not include information about a language used in a question title unless it wouldn't make sense without it. Tags serve this purpose.
Comment: That notwithstanding, like the others said, you will need to show us the code where this is a relevant problem. Usually, user strings do not feature any escape characters; that is just their representation when writing them down within C# source code. In particular, I am not sure what kind of an operation is described by "when i give input" - are you invoking an application from within C#, passing strings as command line arguments to that other application?
Comment: Please see the Edits.
Comment: Have you used MS .NET? It would work correct.
Comment: @HamletHakobyan yes..
Comment: I think you have XY problem. Have you checked exactly same code as you have posted here?
Comment: @HamletHakobyan sorry but i don't understand what you mean to say? when i give command line argument "F:\\" it prints F:\ and when i give argument "F:\" it prints F:" while i want F:\.
Answer: Im not sure why your having a problem here. In M$ Windows, a directory can be specified with or without a back-slash so all of these are correct: c: and c:\ and c:\media and c:\media\. This is the same for Directory.Exists(path) and other functions like Directory.GetFiles(path).
Ths following is a very simple app to list directory files and in my environment it works regardless of whether I put a slash on the end. So c:\media\ gives me all my media files.
class Program
{
    static void Main(string[] args)
    {
        string path = args[0];
        Console.WriteLine("trying path: " + path);
        if (Directory.Exists(path))
            Directory.GetFiles(path).ToList().ForEach(s => Console.WriteLine(s));
        else
            Console.WriteLine("path not found");
    }
}

One thing to note is that in visual studio, when using the debugger such as Quick Watch, it will show the escape character with backslashs. So if user enters c:\media\ the string will be stored as c:\media\ but when you quick watch the path in VS you'll see c:\\media\\; look deeper with the Text Visualisation feature and you'll see the path correctly shown as c:\media\.
Comment: @NiravKamani I see, the problems just clicked :) So why can't you trim the quote? eg `string path = args[0].TrimEnd('"');`
Comment: Just think "C:\ME DIA\" as input now what will happen?
Comment: Well as with all command line apps in Windows the input should be wrapped with quotes. So you'd make a call like this `listdir.exe "c:\my media"` or `listdir.exe "c:\my media\"`. You'll find that the c# console app will interpret it correctly and put `c:\my media\` into your path variable.
Comment: Just consider second case in that case your print line will print c:\my media". and Directory.Exist() will return false even also the directory exist just because of double quotes at the end.
Comment: Any other solution? This is working but is it possible without modifying user input?
Comment: @NiravKamani why is it so important to not modify the input? Sometimes you just have to make-do and get on with writing the rest of the app.
Comment: BTW Did you know that you can also use forward-slash, which won't casue problems but its not the convention so not really relevant.
Comment: I don't want to modify user input because logically user input is correct but it is the problem of backslash character.
Answer: You should use Path class and specifically Path.GetFullPath method to get correct full path.
class Program
{
    static void Main(string[] args)
    {
        string path = Path.GetFullPath(args[0]);
        Console.WriteLine("trying path: " + path);
        if (Directory.Exists(path)){
            var files = Directory.GetFiles(path);
            foreach (var file in files) Console.WriteLine(file);
        }
        else
            Console.WriteLine("path doesn't exist");
    }
}

UPD. Paths with spaces should be passed in quotes. Or you should concat all your command line arguments, if path is the only input.
Comment: Path throws ArgumentException because of double quotation mark at last.
Answer: Use Environment.GetCommandLineArgs(). It will clean up the path.
See this link for more info: http://msdn.microsoft.com/en-us/library/system.environment.getcommandlineargs(v=vs.110).aspx
Answer: Well, if I understand correctly. You can use string.Format . There are overload methods that could help you without modifying much user input.
Sample code:
string[] inputs = ...
string output = string.Format("F:\\{0}\\{1}", inputs[0], inputs[1]);

Answer: C# interprets \ as an escape character. So \" is interpreted as "
Possible way to fix it (if you are sure that there is no " inside arguments:
string a = args[0].Replace('"', '\\');

Comment: Another way: you can set command line parameter without quotes.
Answer: I think your over thinking this.  Logically that isnt valid input.  \ is an escape character on the command prompt just as it is in c# inside of a string.  What you have entered ("F:\") is an invalid value and it IS on the user to correct.  The user is saying at this point that they want the quote.
Answer: Note that when you pass the filename in parameters, you need to have the access rights in the directory where file is placed, otherwise some parts of your application might fail unexpectedly and it might took you much time to figure out what's wrong there.
    var args1 = Environment.GetCommandLineArgs().Skip(1);
    if (args1 != null && args1.Count() > 0)
    {
        //do stuff
    }

File Path as Command Line Argument


Stuck translating a Python algorithm into C++

Question: I am trying to translate a Fibonacci algorithm I have in Python into C++, I have most of it working except I am screwing up somewhere on the syntax.
This is the Python version I currently have:
if n == 0:
    return (0, 1) *****
else:
    a, b = _fib(n // 2)
    c = a * (b * 2 - a)
    d = a * a + b * b
    if n % 2 == 0:
        return (c, d) *****
    else:
        return (d, c + d) *****

This is how I translated it into C++
int fib2(int n) {
 if (n == 0) {
    return (0, 1); *****
 }
 else {
    int a = fib2(n/2);
    int b = fib2(n/2);
    int c = a*(2*b-a);
    int d = a*a + b*b;
    if (n % 2 == 0) {
        return (c, d); *****
    }
    else {
        return (d, c + d); *****
    }
 }
}

I have put 5 stars where the error is coming from. If I understand it correctly, in the Python version, it is returning two Fibonacci numbers as a pair. However, when I try the same syntax in C++, it says "Expected expression".
I understand why this is happening, does anyone know how I could correct my C++ code so that it could return a tuple of two Fibonacci numbers as well?
Comment: @RNar No need for pointers here, `std::pair` or `std::tuple` or `std::array` would each do the job nicely. Especially the array.
Comment: the problem is that you cant return multiple values as a tuple in c++. best way to implement something like this is to use pointers
Comment: Make the return type a tuple or pair, and return {0, 1}
Comment: ^ or that. I'm not too well-versed in standard C++ types
Comment: @BaummitAugen Hi, thanks for your suggestion! It worked for the most part and I am no longer getting a compilation error regarding the return of the pair of numbers. Now I am getting an error saying that there is no viable conversion for 'int' to 'array' when it is trying to calculate a and b. I get that it is having trouble because fib2 now returns an array but I declared a as an int. Is there an easy way to fix this?
Comment: @cursayer You can probably extend the answer below to arrays, or just use the answer with the pairs (although I would prefer the array, but the pair is not bad).
Answer: The following is a result using std::pair
#include <iostream>
#include <utility>

using namespace std;

typedef pair<int,int> myPair;

myPair fib2(int n)
{
    if (n == 0)            return make_pair(0, 1);
    myPair r = fib2(n/2);
    int a = r.first;
    int b = r.second;
    int c = a*(2*b-a);
    int d = a*a + b*b;
    if (n % 2 == 0)        return make_pair(c, d);
    else                   return make_pair(d, c + d);
}

int main()
{
    myPair result = fib2(12);
    cout << "result:" << result.first << endl;
}


To check differentiability of multivariable function at origin

Question: To check function is differentiable or not
$$f(x,y) = \left\lbrace\begin{array}{cr}
          \frac{xy}{|x|} ,& x \neq 0\\
           0  ,  & x=0
\end{array}\right.
$$
I think due to modulus function f is not differentiable. But i am not sure
Thanks
Comment: Look at $x \mapsto f(x,1)$. Is this continuous? Can $f$ be differentiable?
Comment: I don't want to sound unhelpful, but that should be pretty obvious, I think...
Comment: What? To me, that sounds completely bizarre! How on earth...? But well, whatever makes you happy. Then you just have to go for the algebraic approach: determine $f'_x(0,0)$ and $f'_y(0,0)$ to begin with (using the definition of partial derivative), then investigate the limit that's in the definition of differentiability, and the answer should present itself to you. But I find it *much* easier to just look at the graph.
Comment: Differentiable where?
Comment: @GoodDeeds at origin
Comment: Have you checked continuity of partial derivatives? Suppose they are continuous then you can say it is differentiable at $0$
Comment: @copper.hat no f cannot be differentiable. am i right ?
Comment: @TaylorTed: If a function is differentiable at a point then it is continuous there. So if it is not continuous at a point, it cannot be differentiable there.
Comment: @copper.hat So what is answer
Comment: @copper.hat f is continuous at origin but is it differentiable.please let me know
Comment: Sorry, my comments were misleading, I missed the origin part.
Comment: @copper.hat just tell me if it is differentiable at origin and i will think proof
Comment: @copper.hat then my textbook is wrong
Comment: Just plot the function (with Google or Wolfram Alpha, or whatever). Does it *look* like the graph has a tangent plane at the origin...?
Comment: @HansLundmark i plotted graph but how to check(from graph) whether it has tangent plane at origin.
Comment: @HansLundmark i have never studies differentiability geometrically. Just tell me what is answer as per you
Answer: One way of checking is to look at the directional derivative,
$df(x,h) = \lim_{t \to 0} {f(x+th)-f(x) \over t}$. If the function is
differentiable, we have $df(x,h) = Df(x)h$, where $Df(x)$ is the
derivative.
Then $df((0,0),(1,1)) = \lim_{t \to 0} { t^2 \over |t|t}= \lim_{t \to 0} \operatorname{sgn} (t) $, however this limit does not exist.
Answer: The function is not differential along x direction at (0, y) where $y \ne 0$. $f(x, y) = y$ for x > 0, $y \ne 0$, and $f(x, y) = -y$ for $x < 0)$ f is discontinuos at (0, y) where $y \ne 0$
Comment: The question (according to the title) concerned differentiability at the *origin*, and then this is not relevant.


Which service is executing ebextensions

Question: A basic question. What is executing my files in ebextensions?
We use Cloudformations and elastic beanstalk to setup a windows server. In a step of ebextensions I'm executing restart-service ec2config. After that the ec2config service is going in stoppending mode and it's stuck for ever.
So my question: is ec2config executing ebextensions and is it stuck/broken because I tried to restart it inside my ebextensions?
Answer: I'm afraid this is only annecdotal but yes, for Windows it does appear that any bootstrapping like user-data and ebextensions is performed by ec2config.

Which service is executing ebextensions


Join VM to domain

Question: I am using arm template to build Azure VM. Once the vm provisioning is complete it then join to domain. However, the join operation fails.

I tired to add the vm manually to the domain. It work with out any issue.
Please see the link for the template https://drive.google.com/open?id=1cUIIIFJpQHhesZXtf7-pfX_oTTq_C0NH
The c:\windowsazure\logs\plugins(or extensions)\domainjoin log file shows the following error

Thanks
Comment: i dont think its template related, can you login to the vm and grab logs `c:\windowsazure\logs\plugins(or extensions)\domainjoin` and paste into the question?
Comment: Sorted. The OU was wrong. In AD all computers are  under Computers container.
Answer: in this case the error was due to attempt to join vm to a wrong OU.

Join VM to domain


How to find users with password same as their username

Question: How do I find users which their password is equal to their username in Drupal 7?
Comment: In case at the registration you can validate.
Answer: If you are trying to do this while they are registering, there are good modules for the task, a simple search finds Password policy module, It is also on S.O:

A password policy can be defined with a set of constraints which must be met before a user password change will be accepted. Each constraint has a parameter allowing for the minimum number of valid conditions which must be met before the constraint is satisfied.

However for already registered users, you have to hash their username as a password and compare it to their actual hash stored in database, if they are the same, you have cracked their password!
Hashing the passwords, The Druapl way user_hash_password()like this:
<code>$user = user_load($id_of_user);
if($user->pass == user_hash_password($user->name)) {
  block_and_punush_lazy_user($user);
}

// maybe use it like this:
for($uid=2; $uid< MAX_UID_IN_DB; $uid++) { // FROM 2 ONLY!!
  if($user = user_load($uid) {
    if($user->pass == user_hash_password($user->name)) .... // Punish
  }
}
</code>
A more quick solution is to do it solely in database using it's hashing functions. You should check the password.inc in user module and extract the hashing algorithm. implement the same function in mysql and do a:
<code>SELECT `uid` FROM `users` WHERE `pass` = MY_CUSTOM_HASH_FUNC(`name`);
</code>
And DO make a backup of your database before doing these stuff.


Bullet 3 dynamics not working for non-sphere

Question: I have a simple program spawning balls to drop on some terrain which works perfectly. But trying to add a box yields extreme performance drop and a box that doesn't fall.
Here's the full extent of the bullet code
  // create the physics world
  auto collisionConfiguration = new btDefaultCollisionConfiguration();
  auto dispatcher = new btCollisionDispatcher(collisionConfiguration);
  auto broadphase = new btDbvtBroadphase();
  auto solver = new btSequentialImpulseConstraintSolver;

  auto dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
  dynamicsWorld->setGravity(btVector3(0, 0, -10));

  // create terrain
  auto terrainIndices = std::vector<int>(terrainModel.faceData.size() / 11);
  std::iota(terrainIndices.begin(), terrainIndices.end(), 0);
  auto terrainVertices = terrainModel.faceData;
  auto terrainMesh = new btTriangleIndexVertexArray(terrainIndices.size() / 3, terrainIndices.data(), 3 * sizeof(int), terrainVertices.size() / 11, terrainVertices.data(), 11 * sizeof(int));
  auto terrainShape = new btBvhTriangleMeshShape(terrainMesh, false);
  auto terrainMotionState = new btDefaultMotionState();
  auto terrainBody = new btRigidBody(0.0, terrainMotionState, terrainShape);
  dynamicsWorld->addRigidBody(terrainBody);

  // vvvvvvvvvvvvvvvvvvv new code

  // create box
  auto boxShape = new btBoxShape(btVector3(0.3, 0.3, 0.3));
  //auto boxShape = new btSphereShape(0.3); // this works just fine
  auto boxMotionState = new btDefaultMotionState(btTransform(btMatrix3x3(), btVector3(0, 0, 5)));
  auto boxBody = new btRigidBody(1.0, boxMotionState, boxShape);
  dynamicsWorld->addRigidBody(boxBody);
  // bind body to renderable

  // ^^^^^^^^^^^^^^^^^^^

  // create balls (called later on key press)
  auto ballShape = new btSphereShape(0.1);
  auto spawnBall = [&]() {
    auto ballMotionState = new btDefaultMotionState(btTransform(btMatrix3x3(), btVector3(0, 0, 5)));
    auto ballBody = new btRigidBody(1.0, ballMotionState, ballShape);
    ballBody->setCcdMotionThreshold(0.1);
    ballBody->setCcdSweptSphereRadius(0.2);
    dynamicsWorld->addRigidBody(ballBody);

    // bind body to renderable
  };

  while(...)
  {
    // process input

    dynamicsWorld->stepSimulation(1.0f / 144.0f);

    // render
  }

I've also tried using a capsule with the same effect.  To be clear, the issue is that the new object doesn't seem to behave dynamically if its a box or a capsule, it works as expected if its a sphere. The initial position is well above the terrain height.
Curiously, the performance drop only happens after newly spawned balls have dropped for a bit.
This is running on Bullet 3 v2.87 compiled from source running in debug mode in Visual Studio 2017.
Answer: Wow, I figured it out. btMatrix3x3() doesn't create an identity matrix (its either zeroes or uninitialized). So the rotation/transformation wasn't right. Using btMatrix3x3::getIdentity() fixed the problem.
So, it appears that a proper rotation transform is not required for physics calculations on spheres (kinda makes sense in a way) which only added to my confusion.


How do I model interaction of three boolean variables for logistic regression when there are empty cells?

Question: I collected data to find whether the presence or absence of vision, sound, and touch during a task affected the successful completion of that task. However, there were no samples collected where all three senses were absent. So the dependent variable is boolean success but I have a question about how to model the independent variables in a logistic regression.
My initial analysis used a single categorical variable with seven levels representing each combination of senses (seven because there were no cases where all three senses were absent).
summary( glmer( Success ~ Condition + ( 1 | Participant ), family=binomial, data=trials))

When I tried to build a model with the Vision, Sound, and Touch as separate variables, the analysis fails. I believe this is because I have empty cells when including the vision*sound*touch interaction because we did not collect results where all senses were absent.
summary( glmer( Success ~ Vision + Sound + Touch + Vision*Sound + Vision*Touch +
                Sound*Touch + Vision*Sound*Touch + ( 1 | Participant ),
                family=binomial, data=trials))

I followed the suggestion linked above to use the interaction function to drop the unused factor (all three senses absent). However, this seems to create a variable that looks like my original single categorical variable.
senses <- interaction( trials$Vision, trials$Sound, trials$Touch, drop=TRUE )
summary( glmer( Success ~ senses + ( 1 | Participant ), family=binomial, data=trials))

As I try to refine this analysis, is there a way to model the senses as separate variables to make the interaction between these variables clearer? That is, to appropriately model the contribution of vision in the vision, vision*sound, vision*touch and vision*sound*touch conditions. From the initial analysis, the vision*sound*touch interaction is the most interesting.
Answer: You could run a series of analyses, with different combinations of the levels. This would, I think, essentially duplicate what a typical analysis would do. You can then compare the results of the different models. So
M1, M2, M3 - each have only two levels for the IV, corresponding to the three dichotomous IVs.
M4, M5, M6 - each have four levels of the IV corresponding to pairs of variables
M7 is your original model.
Comment: I was able to create the seven models you described. However, in this dataset, the `Vision*Sound*Touch` interaction seemed to dominate the M4, M5 and M6 models. That is, the negative impact on the odds of success observed in that condition results in these pair models showing a negative effect when the raw counts are higher than the individual conditions. Thank you for suggesting this analysis, I did learn something from trying the series of models.


Solving a triangle by angle, circumradius, and area

Question: The problem itself is as follows.

Consider a triangle $ABC$. The cosine of one of its interior angles is $m$, its circumradius is equal to $R$, and its area is equal to $S$. Solve this triangle: find its sides and angles.

By applying the sine theorem, I've got that the length of a side, opposite to the angle with the known cosine, which is $2R\sqrt{1-m^2}$. But I had no luck in advancing further, as it either results in too many unknowns. Most I could do is getting the product of sines of two unknown angles, from the formula $S=2R^2\sin\angle A\sin\angle B\sin\angle C$.
I'm looking for proofs that such triangle exists and is clearly defined, as well as the way to solve it if it is.
Comment: Try using the best known formula for triangle area.
Comment: @AaronGoldsmith Half the product of two sides and sine of the angle between these sides? I've tried using it, but isn't $0.25abc/R = 0.5ab\sin\angle C$ resulting in too many unknowns?
Comment: After a round of thinking, it gives precisely nothing because what we want to find actually vanishes.
Comment: I was thinking $A=bh/2$
Answer: This is a sketch of a solution. Let's say wlog that $\cos \angle A=m$. We have $a=2R\sqrt{1-m^2}$. We also have $2A=bc \sqrt{1-m^2}$ and $b=2R\sin \angle B$, $c=2R\sin \angle C$. On the other hand, $a^2=c^2+b^2-2bc \cdot m$. Thus, $4R^2(1-m^2)=4R^2\sin^2 \angle B+4R^2\sin^2 \angle C-\frac{4A\cdot m}{\sqrt{1-m^2}}$. Finally, $\sin \angle C=\sin (\angle A+\angle B)=m\sin \angle B+\sqrt{1-m^2}\cos \angle B$. Substituting this into above will give us equation to find $\sin \angle B$.
Comment: Thanks! I've elaborated your solution in my answer, too
Answer: Below is my own answer on the problem I came up with. There may exist more elegant ways, but this is the most straightforward way of which I know.
Consider a triangle $ABC$ with circumradius $R$, area $S$, and $\cos\angle C=m$.

Find the sine of $\angle C$ by using the famous trigonometric identity $\sin^2\alpha+\cos^2\alpha=1$. As all interior angles of the triangle have positive sines, we take the positive value, thus $\sin\angle C=\sqrt{1-\cos^2\angle C}=\sqrt{1-m^2}$.
Find the length of side $AB$, opposite to $\angle C$, by using the law of sines. Thus, $AB=2R\sin\angle C=2R\sqrt{1-m^2}$.
Find the product of two other sides. For that, find the altitude of triangle $ABC$ to side $AB$ by using the formula $h_{AB}=\dfrac{2S}{AB}$. Now, if we equate two formulas for the area of a triangle, we get $\dfrac{AB\cdot BC\cdot AC}{4R}=\dfrac{1}{2}AB\cdot h_{AB}$, which we can transform further:
$$\begin{align*}
\dfrac{AB\cdot BC\cdot AC}{4R} = \dfrac{1}{2}AB\cdot h_{AB}\ \ &\Leftrightarrow\ \ \dfrac{BC\cdot AC}{2R} = h_{AB} \\
&\Leftrightarrow\ \ \dfrac{BC\cdot AC}{2R} = \dfrac{2S}{AB} \\
&\Leftrightarrow\ \ BC\cdot AC = \dfrac{4RS}{AB}
\end{align*}$$
Thus, $BC = \dfrac{4RS}{AB\cdot AC}$.
By using the law of cosines, we get $AB^2=BC^2+AC^2-2\cdot BC\cdot AC\cos\angle C$. Here, we can substitute $BC\cdot AC = \dfrac{4RS}{AB}$, and $BC = \dfrac{4RS}{AB\cdot AC}$. We get:
$$\begin{align*}
AB^2=\left(\dfrac{4RS}{AB\cdot AC}\right)^2+AC^2-2\cdot \dfrac{4mRS}{AB}
\end{align*}$$

Here, we know everything except $AC$, and we can find both unknown sides by simplifying the last formula into the biquadratic equation, positive roots of which are sides $BC$ and $AC$. Finally, to find the other angles, one can use the law of cosines if the given angle is obtuse ($m < 0$), as there is only one obtuse angle in the triangle, or the law of cosines in all other cases.


NHibernate tries to create indexes for a view

Question: I'm writing a C# application that uses NHibernate to access the database. One of my data sources is a view (not a table) named content_profile. I have created the following sample class using NHibernate Attributes:
[Class(Table = "content_profile")]
public class ContentProfile
{
    [Id(0, TypeType = typeof(int), Name = @"Id"), Generator(2, Class = @"identity"), Column(1, Name = @"Id")]
    public virtual int Id { get; set; }

    [NotEmpty]
    [MinLength(1)]
    public virtual string Name { get; set; }

    [Property]
    public virtual DateTime? CreationDate { get; set; }

    [ManyToOne(Lazy = Laziness.False, Column = @"author_id")]
    public virtual User Owner { get; set; }
}

When trying to update schema I get the following error:
NHibernate.Tool.hbm2ddl.SchemaUpdate [(null)] - Unsuccessful: alter table public.content_profile add constraint FK280FFEFD6A68A1F9 foreign key (author_id) references public.users

Npgsql.NpgsqlException:
"content_profile" - is not a table

How do I tell NHibernate that it is indeed a view, not a table, and indexes must not be created on schema update?
Answer: You can specify that there should not be done any action on the schema of a certain class map by adding SchemaAction.None, never really used attributes because it lacks features but it should have something like [Class(SchemaAction="None")]


Theme a taxonomy terms page

Question: How do I theme the tag/taxonomyterm page on my site? Can I use a  panels page for this?
Answer: You could use panels. Heres a good guide to setting up page manager with panels.
http://drupal.org/node/1582906
or you could use templates...

taxonomy-term--[vocabulary-machine-name|tid].tpl.php
base template: taxonomy-term.tpl.php

Theme hook suggestions are made based on these factors, listed from
  the most specific template to the least. Drupal will use the most
  specific template it finds:
taxonomy-term--tid.tpl.php
taxonomy-term--vocabulary-machine-name.tpl.php
taxonomy-term.tpl.php

Note that underscores in a vocabulary's machine name are replaced by
  hyphens.

See: http://drupal.org/node/1089656

Theme a taxonomy terms page


Find an ideal in $K[x,y]$ that is maximal but not principal.

Question:
Let $K$ be a field. Find an ideal of $K[x,y]$ that is maximal but not principal. Prove your claims.(Here we are working in a commutative ring with $1\neq 0.$)

My idea:

Choose $K=\mathbb{Q}.$ Then we claim that an ideal $I\subset K[x,y]$ which is maximal but not principal is $I=(x,y)$.
First I will prove that $(x,y)$ is a prime ideal of $\mathbb{Q}[x,y]$. Let $a,b\in (x,y)$ be such that $p=ab\in (x,y)$. Any element in $(x,y)$ is going tobe of the form: $p=Ax+By$ where $A,B\in \mathbb{Q}[x,y].$ If $a'b'=0$ where $a',b'$ are constant terms of $a$ and $b$ respectively then since $\mathbb{Q}[x,y]$ is an integral domain either $a'=0$ or $b'=0.$ Hence either $a$ or $b$ is of the form $Ax+By$ where $A,B\in \mathbb{Q}[x,y]$ which in turn means that either $a\in (x,y)$ or $b\in (x,y)$.
Now since $(x,y)$ is a prime ideal , $\mathbb{Q}[x,y]/(x,y)$ is an integral domain. Now if we can show that $\mathbb{Q}[x,y]/(x,y)$ is a field then we are done. Not sure how to show this. If $1\in \mathbb{Q}[x,y]/(x,y)$ then we can conclude that it is a field right? So, observe that $1-f(x,y)\in \mathbb{Q}[x,y]$ and $f(x,y)\in (x,y)$ then $1-f(x,y)+f(x,y)=1\in \mathbb{Q}[x,y]/(x,y)$.
$(x,y)$ is not principal in $\mathbb{Q}[x,y]$. Observe that $(x,y)=\{xp(x,y)+yq(x,y)| p(x,y),q(x,y)\in \mathbb{Q}[x,y]\}$. Assume by way of contradiction that $(x,y)=(a(x,y))$ for some $a(x,y)\in \mathbb{Q}[x,y].$ Since $x\in (a(x,y))$ there must be $p(x,y)$ such that $x=p(x,y) a(x,y).$ Since degree $x$= degree $p(x,y)$+degree $a(x,y)$ we conclude that $p(x,y)$ must be a constant polynomial. I don't know how to continue from here.

Also, if there is a simple proof for this problem please share it with me. Thank you.
Answer: First, your solution should work for every field, not a particular one, so you should not "choose $K=\mathbb{Q}$.
Second: it's easier to prove that $(x,y)$ is a maximal ideal by showing that $K[x,y]/(x,y)$ is a field (which is very easy).
Third: to show that $(x,y)$ is not principal, note that if $(x,y)=(a)$, then $a$ divides $x$ and $a$ divides $y$. What are the elements that divides $x$ and what are the elements that divide $y$? The only elements that divide $x$ are nonzero constants and nonzero constant multiples of $x$; the only elements that divide $y$ are nonzero constants and nonzero constant multiples of $y$. So then $a$ would have to be a nonzero constant, but then $(a)=(1)$, which is impossible since $(x,y)\neq (1)$.
Answer: First, you are probably being asked to show this for any field $K$, rather than some particular field $K$. But the proof should be the same for general $K$ as when $K=\mathbb Q$.
Second, you can show $(x,y)$ is maximal (hence prime) by noting that $K[x,y]/(x,y)\cong K$, as each $k+xp(x,y)+yq(x,y)\in K[x,y]$ is mapped to the equivalence class of $k$ when you pass to the quotient, and for $k\neq k'$ the equivalence classes of $k$ and $k'$ are distinct (prove this, and don't over-think it).
Third, to see that $(x,y)$ is not principal, suppose $(x,y)=(f)$. Then there is some $p$ such that $x=fp$, and since $x$ has degree $1$, $f$ has either degree $1$ (in which case it is of the form $kx$ for $k\in K$) or is a unit. Similarly, $y=fq$ so $f$ has either degree $1$ (in which case it is of the form $k'y$ for $k'\in K$) or is a unit. Since $f$ cannot both have the form $kx$ and $k'y$, we conclude $f$ is a unit. But then $1\in (f)=(x,y)$, a contradiction (show this, again it is easy). Hence $(x,y)$ is not principal.
Answer: Hint $\ $ If $\rm\,(x,y) = (g)\,$ then $\rm\:g = gcd(x,y).\,$ But $\rm\:x\:$ is irreducible (by degree or primality), hence $\rm\,g= gcd(x,y) = x\, $ or $1,\,$ up to units. But $\rm\,g = 1\:$ $\Rightarrow$ $\rm\,(x,y) = (g) = (1),\,$ contra $\rm\,(x,y)\,$ maximal. Therefore $\rm\,g=x,\,$ hence $\rm\,x\:|\:y,\,$ which implies  $\,0\:|\: 1\,$ by evaluating at $\rm\,x,y=0,1,\,$ contradiction.


Alterar diretório das fotos do fileupload

Question: Estou usando o Fileupload para o cadastramento de fotos para um cliente meu. Está funcionando corretamente. O problema é que ele encontra-se dentro do diretório:

http://controle.sitecliente.com.br

E quando cadastro as fotos, ele armazena no seguinte diretório:

http://controle.sitecliente.com.br/server/php/files/

Essas fotos serão visíveis no site dele para o público e não me sinto confortável em mostrar o diretório do gerenciador nas fotos. Tem algum meio de trocar o diretório de armazenamento?
O código segue abaixo:
No arquivo uploadhender.php, próprio do uploadfile, tem esse método:
protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
            $index = null, $content_range = null) {
        $file = new \stdClass();
        $file->name = $this->get_file_name($uploaded_file, $name, $size, $type, $error,
            $index, $content_range);
        $file->size = $this->fix_integer_overflow((int)$size);
        $file->type = $type;
        if ($this->validate($uploaded_file, $file, $error, $index)) {
            $this->handle_form_data($file, $index);
            $upload_dir = $this->get_upload_path();
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, $this->options['mkdir_mode'], true);
            }
            $file_path = $this->get_upload_path($file->name);
            $append_file = $content_range && is_file($file_path) &&
                $file->size > $this->get_file_size($file_path);
            if ($uploaded_file && is_uploaded_file($uploaded_file)) {
                // multipart/formdata uploads (POST method uploads)
                if ($append_file) {
                    file_put_contents(
                        $file_path,
                        fopen($uploaded_file, 'r'),
                        FILE_APPEND
                    );
                } else {
                    move_uploaded_file($uploaded_file, $file_path);
                    $metodos = new metodos();
                    $mostrar = $metodos->cadastrarFotos($file->name);
                }
            } else {
                // Non-multipart uploads (PUT method support)
                file_put_contents(
                    $file_path,
                    fopen('php://input', 'r'),
                    $append_file ? FILE_APPEND : 0
                );
            }
            $file_size = $this->get_file_size($file_path, $append_file);
            if ($file_size === $file->size) {
                $file->url = $this->get_download_url($file->name);
                if ($this->is_valid_image_file($file_path)) {
                    $this->handle_image_file($file_path, $file);
                }
            } else {
                $file->size = $file_size;
                if (!$content_range && $this->options['discard_aborted_uploads']) {
                    unlink($file_path);
                    $file->error = $this->get_error_message('abort');
                }
            }
            $this->set_additional_file_properties($file);
        }
        return $file;
    }

Incluí essa linha para chamar o meu método:
$metodos->cadastrarFotos($file->name);

Que segue abaixo:
public function mostrarFotos()
  {
      $sql = mysqli_query($this->conexao,"SELECT Fotos FROM album_fotos WHERE NomeAlbum = '".$_SESSION["NomeAlbum"]."'");
      $array = array();
      while($jm = mysqli_fetch_assoc($sql))
      {
            array_push($array,$jm["Fotos"]);
      }
      return $array;
  }

Ele funciona perfeitamente, mas só preciso trocar o diretório onde é armazenado as fotos sem impactar na funcionalidade desse plugin.
Comment: O que tem em `get_upload_path()`? Altere a linha `$file_path = $this->get_upload_path($file->name);` para um diretório que deseja e faça o teste, exe: `$file_path = "images/{$file->name}";`
Comment: Olá NoobSaibot. Consegui resolver de outra forma. Vou colocar como resposta.
Answer: Consegui resolver da seguinte forma. No arquivo server/php/UploadHandler.php, vá no método:
function __construct($options = null, $initialize = true, $error_messages = null) {

e troque:
'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/files/',
'upload_url' => $this->get_full_url().'/files/',

Pelo diretório desejado. Ex.:
'upload_dir' => '../fotos-produtos/',
'upload_url' => '../fotos-produtos/',


Can't create an instance of ViewModel when using Hilt with Compose

Question: I'm using Hilt with Jetpack Compose.
@HiltViewModel
class HomeViewModel @Inject constructor(
    private val homeRepository: HomeRepository
): ViewModel() {

fun getCarDetails(): Car {
    return homeRepository.getCarDetails()
}
}

That's how I inject the repo.
@Module
@InstallIn(SingletonComponent::class)

abstract class DataModule {

    @Binds
    @Singleton
    abstract fun bindHomeRepository(
        homeRepository: HomeRepositoryImpl,
    ): HomeRepository
}

And that's my composable.
@Composable
fun HomeScreen(viewModel: HomeViewModel = viewModel()) {
    val carData = viewModel.getCarDetails()
    Column(
        Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        TopBar(carData = carData, modifier = Modifier)
        CarImage(carData = carData, modifier = Modifier)
    }
}

I've annotated my Activity with @AndroidEntryPoint. Can't figure out what's the problem. It crashes with a message:
java.lang.RuntimeException: Cannot create an instance of class com.example.carcontroller.ui.HomeViewModel

My library versions for compose is 1.2.1 and for hilt 2.43.2. Compose ViewModel version is 2.5.1.
EDIT: I fixed the crash and below answered how. Hope that will help someone.
Answer: Well, the developer's page isn't updated yet.
There's a library called hilt navigation compose:
implementation "androidx.hilt:hilt-navigation-compose:1.0.0"

After syncing we need to use hiltViewModel() instead of viewModel() like this
fun HomeScreen(viewModel: HomeViewModel = hiltViewModel())

Now it's not crashing. Thank you.


fixing critical issues after npm audit

Question: I am trying to fix some issues prompted by npm audit command.
The project has just been upgraded to angular 15.
According to npm audit:
"hermes-engine  <=0.9.0
Severity: critical.
Access of Resource Using Incompatible Type in Hermes - https://github.com/advisories/GHSA-7mhc-prgv-r3q4.
fix available via npm audit fix.
node_modules/hermes-engine
react-native  <=0.0.0-ffdfbbec0 || 0.61.0-rc.0 - 0.67.5
Depends on vulnerable versions of hermes-engine
node_modules/react-native"
I should be able to fix one of the critical issues with npm audit fix commmand. But when I do so, it doesn't fix anything and the critical issue remains.
Any idea on how I can fix it?
My package.json file looks like this :
{
  "name": "my-app",
  "version": "1.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^15.2.4",
    "@angular/cdk": "^13.2.0",
    "@angular/common": "^15.2.4",
    "@angular/compiler": "^15.2.4",
    "@angular/core": "^15.2.4",
    "@angular/forms": "^15.2.4",
    "@angular/localize": "^15.2.4",
    "@angular/material": "^13.2.0",
    "@angular/platform-browser": "^15.2.4",
    "@angular/platform-browser-dynamic": "^15.2.4",
    "@angular/router": "^15.2.4",
    "@ng-bootstrap/ng-bootstrap": "^14.0.1",
    "aws-amplify": "^4.3.13",
    "bootstrap": "^4.6.2",
    "chart.js": "^2.9.4",
    "luxon": "^1.25.0",
    "ng2-charts": "^2.4.2",
    "ngx-toastr": "^13.2.0",
    "rxjs": "~6.6.0",
    "tslib": "^2.0.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^15.2.4",
    "@angular/cli": "^15.2.4",
    "@angular/compiler-cli": "^15.2.4",
    "@types/jasmine": "~3.6.0",
    "@types/node": "^12.11.1",
    "codelyzer": "^6.0.0",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "^6.3.13",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "karma-junit-reporter": "^2.0.1",
    "ng2-charts-schematics": "^0.1.7",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~4.8.4"
  },
  "browser": {
    "crypto": false
  }
}

Now when I look at hermes-engine, it seems to be related to react native.. Why would i have react native dependencies in my package-lock.json and would it be safe to remove them?
Comment: can you post the result of `npm ls hermes-engine` ? (or `yarn why hermes-engine`)
Comment: The result of npm ls hermes-engine :
firstname.lastname@example.com -->  @email@example.com --> @email@example.com --> @email@example.com --> firstname.lastname@example.com -->  firstname.lastname@example.com -->  firstname.lastname@example.com
Comment: There you go you have it. `aws-amplify` is responsible for pulling `react-native`.
Comment: Asuming that I can remove hermes-e,gine or even the react native related dependencies.
How would you proceed in order not to break aws-amplify?
Answer: Per your deps tree,
@firstname.lastname@example.com --> email@example.com --> firstname.lastname@example.com --> firstname.lastname@example.com

middleware-retry doesn't pull react-native-get-random-values since 3.12.0.
You best solution would be to update aws-amplify !

fixing critical issues after npm audit


Com funciona a propriedade Position?

Question: Já li sobre a propriedade position, mas ainda não conseguir entender o proposito dela. Os valores absolute e relative não entraram na minha cabeça. Também queria saber quando eu devo utilizar essa propriedade.
Comment: Da uma lida nesse link se puder: http://pt.stackoverflow.com/questions/38215/quando-usar-position-absolute-ou-relative-em-css, talvez ajude.

Aliás, nela tem as respostas para a sua pergunta.
Answer: Existem quatro valores para a propriedade Position: Static, Relative, Fixed e Absolute
Static
O position: static; não tem por base as propriedades top, left, bottom ou right, ele simplesmente fica no lugar onde você o colocou "estático" e acompanha no fluir normal da página.
Relative
O valor relative faz com que o elemento seja posicionado relativamente de acordo com o valor informado em top, left, bottom ou right.
Ex.: se você configurar um elemento assim:
position: relative;
left: 10;

Ele ficará na posição normal no fluir da página acrescentado +10px de distância da lateral esquerda.
Fixed
Um elemento configurado com fixed, ficará fixo na tela, não importando o quanto você desça a página para baixo. Quando você vê um site que tem um menu superior que fica sempre no topo, independente de você descer a barra de rolagem para baixo, provavelmente está marcado como position: fixed;.
Absolute
O elemento com position: absolute; fica posicionado relativamente ao elemento "superior" a ele (caso esteja dentro de um outro elemento), ou relativamente ao body (caso não esteja dentro de outro elemento). Se você o configurar assim:
position: absolute;
left: 10;
top: 20;

Ele se manterá na posição "10, 20", e diferente do fixed, quando você descer o scroll da tela, ele irá se mover, mantendo sempre a posição absoluta em relação ao elemento "superior".
Caso ele esteja dentro de uma outra div, a posição "10, 20" que citei antes, seria referente à ela.
Ex: se a div pai estiver na posição "20, 30", a div absoluta estaria na "20, 50".

Com funciona a propriedade Position?


How do I link a page in a template?

Question: If there is a basic page with the route '/about', how can I link it in a template file?

Comment: ``
Answer: Let assume the page is a node whose ID is 4. You can use the following code, in a template file.
About us"

Comment: @crayden What if a month from now someone decides to change it to /about-us? What do you think will happen if the alias changes?
Comment: Is there no way to specify using a path based on the URL alias? Such as '/about'?
Comment: @crayden in the case above, `path()` will automatically get the URL, the alias if there is one, based on the node id.
Answer: You can use the path function to call specific routes
My link

Or of course, you can do it the old-fashioned way
My link

How do I link a page in a template?


Why shift the mean of a bootstrap distribution when conducting a hypothesis test?

Question: I'm wondering about why we do a particular thing (and not another) when conducting bootstrapped hypothesis tests.
My understanding of bootstrapped hypothesis tests is this (based on this helpful explanation):

State a null and alternative hypothesis. H0: mean =  50 and Ha: mean <> 50, for example
Collect a sample of data. Let's say the mean of this sample is 62.
From each of the observations in our sample, subtract the mean of our sample. So in this example, subtract 62 from each observation. Then add the mean value under the null hypothesis to each of our observations. So in this example, add 50 to each of our observations. Now we've got a sample that's centered on our null hypothesis mean.
Resample this shifted sample with replacement a bunch of times. Each time, recalculate the mean, so we have a bunch of bootstrapped means. This is our bootstrapped distribution under the null hypothesis.
Compare our original observed sample mean (62) to our bootstrapped null distribution. See how many bootstrapped means are at least as extreme as 62 is. This gives us a p-value.

Ok here's my question:
Is it ok to do what I'm about to describe below? If not, why not? And if not, is there a version of this that's ok to do?

State a null and alternative hypothesis. H0: mean =  50 and Ha: mean <> 50, for example. Same as before.
Collect a sample of data. Let's say the mean of this sample is 62. Same as before
Resample our original sample with replacement a bunch of times. Each time, recalculate the mean, so we have a bunch of bootstrapped means. This creates a bootstrapped distribution (but not one centered on the null hypothesis value). This is different from above
Compare our null hypothesis mean (50) to our bootstrapped distribution (centered roughly on 62). See how many bootstrapped means are at least as extreme as 50 is. This gives us a p-value. This is different from above

Again: Is it ok to do that? If not, why not? And if not, is there a version of this that's ok to do?
Any help would be much appreciated. Happy to clarify anything. Thanks so much!
PS: I've read this related post, but my question is why it's not acceptable to use the empirical distribution as the reference distribution when calculating the pvalue.
Answer: The idea is to emulate the sampling distribution under the null hypothesis (from which you get an approximate p-value).
So you make a sample that's shaped like the one you have but with a mean like the hypothesized one and see how unusual the sample is relative to that (this is suitable for a shift alternative). This emulates as near as we can how the null sampling distribution would behave.
By doing it the way around you're suggesting you end up answering a quite different question to the one you're testing.
Imagine for example, we look at a sample from a right skewed distribution.
Let us further consider that we are interested in testing whether the population mean is 100 against the 1-tailed alternative that it's greater than 100, and we get the following observations:
<code> 99.84 100.47  99.97 100.62 101.48 100.28 100.18 100.09  99.99  99.73
</code>
The sample mean is 100.265
Here's the two comparisons you'd be making under the two resampling schemes:

Under the correct scheme (the sampling distribution is as it was but with the hypothesized mean, how unusual is the sample), we look at an upper tail area; the upper tail is heavy, so this has a relatively high p-value.
Under your proposed scheme we have to look in the left tail, but it's shorter tailed, suggesting the hypothesized value is inconsistent. This has a lower p-value because we end up looking in the short tail, when it was the long right tail under the null that "produced" the high sample mean.
When the sample mean is above the hypothesized mean, it should tend to be far above, and when it's below it should tend to be close by. We have switched those two around and miscalculate.
In the case of a simple two-sided test where we look in both tails which we do should make no difference, but the difference in such a simple case as the one above makes it clear that this won't correspond in general. We should try to do it the right way around rather than relying on it working out in some cases.
Comment: This is great, thanks. I'm still grappling a little with the idea that bootstrapping is predicated on "believing our sample data represent the population," but then turning around and modifying the sample data to conform to a null hypothesis we have. From my naive perspective, that seems a little inconsistent. (We're assuming the bootstrapped variance is correct, for example, even though we think the bootstrapped mean needs to be subject to testing/regarded with skepticism). Thanks again for the thorough answer!
Comment: While the distribution of the data is indeed our best estimate of the distribution of the population (absent distributional assumptions), the data *aren't necessarily consistent with the null hypothesis* (that's why we're testing in the first place!) -- but in order to compute a p-value we need the sampling distribution of the test statistic *given the null is true*. So we do what we can to make it true before we sample - if we don't, we're not computing a p-value.
Comment: Is there some statistical procedure where we do compare a hypothesized value to the empirical distribution, rather than a null distribution?
Comment: That sounds like a new question
Comment: Gotcha--posted a new question here: https://stats.stackexchange.com/questions/388830/is-there-an-inductive-version-of-a-traditional-hypothesis-test
Thanks again for your thorough answer.


How to get term from alias

Question: I've to get the taxonomy_term tid from the alias ('/alias/of/my/term')
Is there a way to do this without making a query on url_alias table?
Answer: The only way to avoid a query is if the alias is already in the cache. Rather than worry about that yourself, it's best to use the API (even more so in Drupal 8 as path alias storage is pluggable and may not be in the database):

Drupal 7, using drupal_get_normal_path() :
$system_path = drupal_get_normal_path($path_alias, $langcode);

Drupal 8, using the path alias manager service:
$system_path = \Drupal::service('path.alias_manager')->getPathByAlias($path_alias, $langcode);

As always it's preferable to inject the service into the consuming class if context allows.

Both methods will get you the system path, e.g. taxonomy/term/1, from which you can extract the term ID.

How to get term from alias


When a football match goes to extra time, when is full time?

Question: The events in a hypothetical football match are:

45 mins - half-time (score 1-1)
90 mins - end of normal time (score 2-2)
120 mins - after extra time (score 3-2)

Would it be correct to say that score was 2-2 at full-time?
Answer: There's no reference to specific term to be used in the Laws of the Game, especially in the Law 7: the Duration of the Match. Your best bet would be to refer to the rules/regulations of the particular tournament that you're interested in, but again it's unlikely that any tournament rules would include such terminology definitions.
Answering your question, I would say yes. By "full-time" people usually mean the score at the end of 90 minutes but it adds some ambiguity, so the terms "regulation time" or "the end of regulation time" are more preferred. Here's the WikiPedia article explaining respective terms.
To refer to the end of 120 minutes, people use "after extra time" (a.e.t.). Here's an example from UEFA Champions League 2013/14 Final match report.
To refer to the end of game after 120 minutes and penalty shootouts, people use "after penalties" or "on penalties". Here's an example from UEFA Champions League 2015/16 Final match report.
But again, there's no central repository which stores respective definitions of minor football terms. In Russian, for instance, to refer to the end of 90 minutes people mostly use "в конце основного времени" which means "at the end of main time", so what I'm saying is such non-regulated terms can have many different forms.
Answer: Yes, the following statements would be correct:

The score was 2-2 at full time OR The score was 2-2 at the end of regulation time
The score was 3-2 at the end of extra time

Here is a quote from a wikipedia page for terms used to describe overtime in sports:

In association football knock-out competitions or competition stages, teams play an extra 30 minutes, called extra time, when the deciding leg (or replay of a tie) has not produced a winner by the end of regulation or full-time.

Now of course, there are plently of different valid ways of referring to the score at either the end of regulation or extra time and there isn't a single correct way, but at least with these terms people will probably know what you are talking about and not be confused.
Comment: Sorry, but to me it's just a copy-paste of the previous answer. Besides that, downvoting other answers (which have the same content as yours) just to promote yours is not what we usually do in this community.
Comment: This answer doesn't bring in any additional information to the previous answer. It's always good to read other answers, before posting yours.
Comment: @gdrt I wrote this answer because it is more concice and goes straight to the point by directly answering with a yes/no, as I thought he simply wanted to know the right way of specifying the score at the end of a game without confusing people when talking about football.
Comment: @gdrt Sorry about that mate you are right, but regarding the answer I still believe that mine isn't a copy/paste of yours and that it directly answers his question more clearly by telling him what he can say in an explicit way.


How to create an Entity Framework edmx file for an existing database with .NET Standard and Entity Framework Core?

Question: In the past, I've been using .NET Framework 4.6 with Entity Framework 6 to generate an edmx file and the associated model files. For one of my projects, I'd like to switch to ASP.NET Core MVC as front end and, therefore, want to change my DAL from .NET Framework 4.6 and EF 6 to .NET Standard 2.
Since the project files were initially created with VS 2012, they still use the old syntax and I somehow can't change the target framework via Visual Studio itself. I've read that is probably easier to just recreate the project with Visual Studio 2017 and target .NET Standard 2 and just step-by-step insert the old code. The first thing that I want to recreate is my Entity Framework mapping with a DBContext. So far, I've added some EF Core dependencies from NuGet, but I fail to create an edmx file that is comparable to what I'm used to from .NET Framework 4.6. Visual Studio does not seem to offer a specific wizard for that in 'add new file'.
What am I missing here? So far, I've checked some previous Stackoverflow posts (such as Trying to set-up Entity Framework core in .Net Standard project) and multiple Udemy courses, but I still don't understand how I can use an equivalent of EF 6 (e.g., an edmx file) in .NET Standard.
Comment: EDMX is no more, your'll have to use a 3rd party tool like [Entity Developer](https://www.devart.com/entitydeveloper/) for similar functionality.
Comment: Possible duplicate of [ADO.NET entity data model (.edmx) in ASP.NET MVC core 1.0](https://stackoverflow.com/questions/38684368/ado-net-entity-data-model-edmx-in-asp-net-mvc-core-1-0)
Answer: Per Microsoft:
"EF Core does not support the EDMX file format for models. The best option to port these models, is to generate a new code-based model from the database for your application."
https://learn.microsoft.com/en-us/ef/efcore-and-ef6/porting/port-edmx


How to go back to the beginning of a loop in python?

Question: My code:
b="y"

ol=[]

#operations list

OPERATIONS = ["-", "+", "*", "/"]

op = input ("Please enter your first calculation\n")

while b=="y":

    ops = op.split(" ")

    #add arguments to list

    for x in ops:
        ol+=x

    if ol[1] in OPERATIONS:

        #make sure operator is an operator

        print()

        #make sure not dividing by zero

        if ol[1] == "/" and ol[2] == "0":

            print("Error")

            b = input("Would you like to do another calculation (y/n)?\n")

            if b == "y":

                op = input("Please enter your calculation:\n")

                continue

            else:
                break
        else:

            n1 = float(ol[0])
            n2 = float(ol[2])

            #calculations done here

            if ol[1] == '-':

                calc = n1-n2

            if ol[1] == '+':

                calc = n1+n2

            if ol[1] == '/':

                calc = n1/n2

            if ol[1] == '*':

                calc = n1*n2

            print("Result: " + str(calc))

            b = input("Would you like to do another calculation (y/n)?\n")

            if b == "y":

                op = input("Please enter your calculation:\n")

                continue

            else:
                break

    else:
        print("Error")

How do I ensure that the program takes the new operation to the beginning of the loop instead of continuing to print the original calculation?
Comment: are you sure your indents are right on your code snippet?
Comment: yes the indents are right
Answer: You need to reset your ol=[] within the while loop
Comment: Thanks do you mind also letting me know how to ensure that the program doesn't give an invalid operator error all the time (now it does)
Comment: What do you mean? The code seems to work on this end... Could you post a use-case?
Answer: Your calculation is performed using a list of operations ol generated from the variable ops which is taken by splitting input ops by a space.
You can achieve this by moving the ol=[] into the loop:
b="y"
# Remove ol=[]

#operations list
OPERATIONS = ["-", "+", "*", "/"]

op = input ("Please enter your first calculation\n")

while b=="y":
    ol = [] # Add here

However, there is a simpler approach. The variable ops contains a list of operations from the split (str.split generates a list), and you're then copying this value into the list ol. Instead you can split the string straight into the variable ol as follows:
b="y"

#operations list
OPERATIONS = ["-", "+", "*", "/"]

op = input ("Please enter your first calculation\n")

while b=="y":
    ol = op.split(" ")

This is neater, as you then don't require the extra ops variable.


Train and Validation vs. Train, Test, and Validation

Question: I am embarking on a new job that will give me the opportunity to do some cool machine learning stuff.  I haven't touched this stuff on a deeper level since graduate school and I wanted to get some clarification on some concepts.
The way I was taught ML is that you split up your data (80/20) into training and validation datasets.  You fit your model to the 80% training split and get an error rate, loss, etc. through cross validation.  Then, you take the fitted model you constructed with the training data and pop in the 20% validation dataset to compare if the error rates, loss, etc are similar.  If so, the model is good.
I have been doing some research to refresh my knowledge, and I've been noticing 3-way splits now (training/test/validation) where the split is usually (70/20/10).  I'm so confused on how this 3-way split is different from the 2-way split I was taught in school.  Also, I'm pretty sure I've been interchanging test with validation when referring to the 2-way split methodology.
Can someone verify if my understanding of the 2-way split is correct and explain the difference between that and the 3-way split?
Thank you!
Answer: In your two-way split, as you also mentioned, your validation set is actually your test set. In your way, you haven't mentioned about hyperparameter optimisation (HPO), but it's a key step in many machine learning algorithms. When you need HPO, you'll either need to have a separate validation set to tune the HPs or tune them using cross validation over the training set. In the end, the model is trained over the whole training dataset and tested over the test set.
In your ML algorithm, if you don't need to optimise HPs, you can obtain loss metrics using cross-validation over the training set as you did, but this could have been done by using the entire dataset as well, i.e. you have five 80-20 splits, and average the loss across folds. You don't need a two-level test.
Answer: The two methods you are describing are essentially the same thing. When you describe using cross validation, this is analogous to using a train test split just repeated multiple times. Train/validation/test and train/test with cross validation on the training set are exactly the same but using cross validation repeats for different splits of train/test.
Answer: In general, you need a split of your data set into test/training whenever there is danger of using information from the test set on the trainig set. The information might flow through you as a modeller. Let this sink in for a moment.
For example, if you build one model with one method, use a 80/20 split or cross validation. If you compare many methods on a 80/20 split you implicitly use information from performance on the test set in your modelling. Add a validation data set in this case. If you choose some of these models for hyperparameter optimization, you need an additional test test, or optimize models when they are built (this is hard). And so on.
In any case, keep the validation data set off the table for as long as possible and use it as little as possible.
Answer: "All models are wrong, but some are useful". George E. P. Box
When we build a model, our main materials is data. But it is ultimate goal that probably will never be achieved is to use our model to different data and performs like we trained with our trained data. But we can obviously try and then comes this split.
Now I will not discuss the size of the split. But I will focus on whether we should split 2 ways or 3 ways. To me, it is unnecessary to split three part for the data you control. For example you have ECG data from 100 patients. You can train to see whether your model works by spliting 80/20 as train and test. If it performs well in test set, there is no need for validation as your test set was different tan your train set.
Question is when you need a validation set. For example, clinicians have extra 20 patients ECG data that were not used in you train and test set. You trained your model, tuned your parameters through your test set. But now you have completely different data which clinician has. They will try your model for validation. So the intuition can be, doctors want to have some model. They have 120 patients data. They give you 100 data. You split them as train and test. And after that doctors use your model in validation set.
In any competition for example kaggle, data probably divided this way.


WPF - How to get SelectedIndex of a ComboBox defined in a DataTemplate?

Question: In my WPF app I have a data import function which imports data from an Excel file into a database.
In order to allow user to map the columns from their Excel file to the columns in my database table I am displaying the list of Excel columns in a ComboBox next to database table column names allowing the user to select the matching Excel column from the ComboBox.
This is displayed in a ListBox with each item containing a ComboBox and a TextBlock.
The ListBox is Data Bound to a Dictionary<ColumnsClass, List<string>> where ColumnsClass is a simple object containing database column names and other details and the List<string> is just a list of column names found in the Excel file. In order to display the List<string> in the ComboBox I have a  DataTemplate defined as such:
<DataTemplate x:Key="ColumnList">
    <Grid>
        <Grid.ColumnDefinitions>
    <ColumnDefinition Width="1*"></ColumnDefinition>
    <ColumnDefinition Width="1*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
       <ComboBox Grid.Column="0" ItemsSource="{Binding Value, Mode=OneWay}">
   </ComboBox>
   <TextBlock Grid.Column="1" Text="{Binding Key, Mode=OneWay}"/>
    </Grid>
</DataTemplate>

Once the user maps the Excel columns to database column names and starts the import I need to be able to get the database column name and the matching 'ComboBox' 'SelectedIndex' value of each item in the ListBox but the each item in the ItemsSource is actually a KeyValuePair<ColumnsClass, List<string>> so I don't see how to get the 'ComboBox' 'SelectedIndex' value while iterating through the ListBox.Items collection...
Any ideas?
Comment: Note that you don't have to specify width of `ColumnDefinition` in this case, since `1*` is the default value.
Comment: Right, this is modified code, there are more columns defined and `1*` is not the value in actual code...
Answer: If you use the Dictionary just as a IEnumerable<KeyValuePair<ColumnsClass, List<string>>>, you could create a custom class to hold the two values and add a value specifying user's choice:
class ViewModel
{
    public ColumnClass ColumnClass { get; set; }
    public List<string> ColumnNames { get; set; }
    public string SelectedColumn { get; set; }
}

Then use List<ViewModel> (or any other collection) instead of your Dictionary and bind to SelectedColumn in your XAML:
<DataTemplate x:Key="ColumnList">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <ComboBox Grid.Column="0" ItemsSource="{Binding ColumnNames, Mode=OneWay}"
            SelectedItem="{Binding SelectedColumn}" />
        <TextBlock Grid.Column="1" Text="{Binding ColumnClass, Mode=OneWay}"/>
    </Grid>
</DataTemplate>

If, for some reason, you didn't want to create a separate class and you're on .Net 4, you could use Tuple<ColumnClass, List<string>, string> instead of ViewModel.
Comment: Looks like a good solution will give it a shot tomorrow and let you know if it worked... thanks.
Comment: Just brain cramping yday trying to get around what was the wrong approach in the first place. Thanks.


How do i deactivate "Your comment has been posted." after user posted a comment

Question: How do I deactivate -Your comment has been posted- after user posted a comment.
Is it possible to deactivate the message above with out touching the core?
Answer: you can add a custom submit handler to the comment form using hook_form_alter():
function yourmodule_form_alter(&$form, &$form_state, $form_id){
  if( $form_id == 'comment_form' ) { // find and use the actual form ID
    $form['#submit'][] = 'yourmodule_your_custom_comment_submit_function';
  }
}

Then in that submit function check to see if the message exists using drupal_get_messages():
function yourmodule_your_custom_comment_submit_function(){
  $message = drupal_get_messages('status', false);
  if( $message['status'] == 'Your comment has been posted' ) { // Or what is the actual message
    drupal_get_messages('status');
  }
}

This is for Drupal 7 but these functions exists in older drupal versions. Check api.drupal.org for details.
Comment: There are some problems with this. 1) `$message['status']` is an array, not a string, so the if-test will allways fail. 2) String may not be 'Your comment has been posted' if site's language is not English. 3) `drupal_get_messages('status')` will flush the entire status message queue, so any additional messages queued for display will be lost.
Answer: For a no-code solution that disables all messages with specific language, install the Disable Messages module, and under configuration you should enable filtering. Under "messages to be disabled" add
Your comment has been posted.

... or if your comment message differs, cut and paste your exact message into the field.
You can also use regular expressions or filter by user.


Customize Android AChartEngine PieChart (show text inside chart)

Question: Is there a way to update the text inside a Pie Chart (generated through the achartEngine API). I want to show the percentage there. In the picture below, I have it updated manually (i.e. 60%, 30% and 10%) to show you.

I could not find relevant method in the SimpleSeriesRenderer class. Here is the code I am using.
CategorySeries categorySeries = new CategorySeries("Chart");

for (int i = 0; i < series.size(); i++) {
    categorySeries.add(series.get(i), series_data.get(i));
}

DefaultRenderer defaultRenderer = new DefaultRenderer();

defaultRenderer.setBackgroundColor(Color.BLACK);
defaultRenderer.setShowLabels(true);
defaultRenderer.setShowLegend(true);
defaultRenderer.setShowTickMarks(true);
defaultRenderer.setLabelsTextSize(40f);
defaultRenderer.setLegendTextSize(40f);
defaultRenderer.setApplyBackgroundColor(true);

for (int i = 0; i < series_data.size(); i++) {

    SimpleSeriesRenderer simpleSeriesRenderer = new SimpleSeriesRenderer();
    simpleSeriesRenderer.setColor(  chartColor[i]);
    defaultRenderer.addSeriesRenderer(simpleSeriesRenderer);
}

Answer: You can create custom class, which extends PieChart and override it's drawLabel() (and may be draw()) method:
public class AdvancedPieChart extends PieChart {

   @Override
   protected void drawLabel(Canvas canvas, String labelText, DefaultRenderer renderer, List<RectF> prevLabelsBounds, int centerX, int centerY, float shortRadius, float longRadius, float currentAngle, float angle, int left, int right, int color, Paint paint, boolean line, boolean display) {
      // do what You want with Label text, e.g. just
      canvas.drawText(labelText, xLabel, yLabel, paint);
   }

}

and use your AdvancedPieChart class instead of "standard" PieChart.
Update:
For example, this implementation:
public class AdvancedPieChart extends PieChart {

    public AdvancedPieChart(CategorySeries dataset, DefaultRenderer renderer) {
        super(dataset, renderer);
    }

    @Override
    protected void drawLabel(Canvas canvas, String labelText, DefaultRenderer renderer, List<RectF> prevLabelsBounds, int centerX, int centerY, float shortRadius, float longRadius, float currentAngle, float angle, int left, int right, int color, Paint paint, boolean line, boolean display) {
        super.drawLabel(canvas, labelText, renderer, prevLabelsBounds, centerX, centerY, shortRadius, longRadius, currentAngle, angle, left, right, color, paint, line, display);

        String additionalText = "Hello";
        Paint textPaint = new Paint();
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(18 * Resources.getSystem().getDisplayMetrics().densityDpi / 160f);
        textPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
        Rect bounds = new Rect();
        textPaint.getTextBounds(additionalText, 0, additionalText.length(), bounds);
        canvas.drawText(additionalText, this.mCenterX - bounds.width() / 2, this.mCenterY - bounds.height() / 3, textPaint);
    }
}

draw text "Hello" in the center of chart:

Layout (activity_main.xml) for that:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/activity_main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="ua.com.omelchenko.chartapplication.MainActivity">

    <RelativeLayout
        android:id="@+id/chart_holder"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </RelativeLayout>

</RelativeLayout>

(of course You don't need nested layouts)
and MainActivity.java is:
public class MainActivity extends AppCompatActivity {

    private RelativeLayout mPieChartHolder;
    private GraphicalView mChartView;
    private PieChart mPieChart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String[] names = new String[] { "Category 1", "Category 2", "Category 3" };
        double[] values = { 20, 30, 50 };
        int[] colors = { Color.RED, Color.GREEN, Color.BLUE };

        CategorySeries categorySeries = new CategorySeries("Pie Chart");
        for (int i = 0; i < names.length; i++) {
            categorySeries.add(names[i], values[i]);
        }

        DefaultRenderer defaultRenderer = new DefaultRenderer();
        for (int i = 0; i < values.length; i++) {
            SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
            seriesRenderer.setColor(colors[i]);
            defaultRenderer.setBackgroundColor(Color.BLACK);
            defaultRenderer.setLabelsTextSize(20f);
            defaultRenderer.setLegendTextSize(20f);
            defaultRenderer.setApplyBackgroundColor(true);
            defaultRenderer.addSeriesRenderer(seriesRenderer);
        }

        mPieChart = new AdvancedPieChart(categorySeries, defaultRenderer);
        mChartView = new GraphicalView(this, mPieChart);

        mPieChartHolder = (RelativeLayout) findViewById(R.id.chart_holder);
        mPieChartHolder.addView(mChartView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    }

}

(of course it's just demo).
And if You press Ctrl+LeftMouseButton when mouse pointer is on PieChart word in AndroidStudio 2.0 and above You can find many interesting things about inner organization of PieChart, for example coordinates of pies centers etc.
Comment: Thanks, but labels are already appearing in this chart A:AA, B:BB & C:CC. I want to keep them, but additionally want to show text inside chart..Is it possible with your approach ?   Still this a good pointer, I will  check , if something is available with custom class.
Comment: Just add what You need e.g.: `canvas.drawText("My text", 100, 200, newPaint);` - You can change everything in `drawLabel()` and `draw()` methods.


What's a "slider" and an "off the seam" bowling?

Question: I've heard these terms being used during commentary, but then quite unclear of what those actually represent.
What I assumed on slider is that, the bowler bowls with some side-spin on top of off-spin or leg-spin. Off the seam bowling still sounds like a mystery to me.
Would be appreciated if anyone could elaborate on these.
Answer: What is a Slider?
The slider or back spinner is the reverse of the top-spinner. Instead of bouncing and kicking as the top-spinner does, the back spinner delivery will skid onto the batsman. (Sources:1, 2)
This article from cricket.com.au will help in understanding slider. Youtube
What is off the seam bowling?
Seam is the raised stitching around the circumference of the ball. While seam bowling is, using the seam of the ball to cause the ball to bounce in an unpredictable fashion when it hits the pitch.
Off the seam term is used by commentators to describe the ball that bounce unevenly or deviates from the length of the bowling (movement of the ball), after seam of the ball strikes the pitch.Need citation
Sources:1, 2, 3
Comment: [This answer](https://sports.stackexchange.com/a/4726/6126) is also worth reading for the difference between the various leg spin deliveries.


Windows 2019 IIS webserver redirect

Question: I have 1 IIS web server (Main) and 5 other IIS web servers behind it (1-5). The applications are all different and there are 125 of them. They are split up between the 5 servers. I'm wanting to use a wildcard cert and use sub domains for the different applications to keep them separate.
Is it possible to have the main web servers web page have links that are all the different sub-domain URL's?
When you click on one, the main IIS web server would then redirect it to the correct server behind it. That server would use host name bindings to deliver the site.
Due to high traffic I want to distribute the applications across multiple servers. Or is there a better way to handle the sub domains from a single web page to multiple IIS servers?
Everything I have researched so far are rewrites and redirects on the same IIS server.
Answer: You need a reverse proxy: something that can act a front end for all your web sites and can contact the correct server for the requested URL.
There are lots of reverse proxy solutions around; if you want to do this with a Windows server, have a look at Application Request Routing.
Comment: Ok I thought it was more for server farms serving the same content. So the setup would be the web server then the  ARR server and then the application servers? Or ARR server hosting the website then the applications servers behind it?
Comment: A server with ARR (which works on top of IIS) receives requests from clients and then calls the internal server which actually hosts the web site.
Comment: But you only need this if the internal servers are not directly reachable from the Internet; otherwise, you can just set up your DNS to map each site name to the server that is hosting it.
Comment: To clarify: if you have a single IP and you want to publish `sitea.domain.com` and `siteb.domain.com`, you map the names in DNS to the IP of the ARR server, and then configure the ARR server to call internal server A  for `sitea.domain.com` and internal server B for `siteb.domain.com`; but if you have instead an IP for each server, you only need to map each name to the correct IP and the clients will directly call the servers.

Windows 2019 IIS webserver redirect


Heroku crashes with error "bash: line 1: app/main:app: No such file or directory"

Question: I have a Django app that I am hosting on Heroku connected via Github.  However, every time I try to start the app, I am receiving the error app[uvicorn.1]: bash: line 1: app/main:app: No such file or directory.
Looking up the problem, it seems that it is in the wrong directory, but even changing the app/main:app location still gives the same error.
The Procfile contents are: uvicorn app/main:app --reload --host 0.0.0.0 --port=${PORT}.
I have attached a screenshot of the file hierarchy as well to help understand the structure.

I tried changing the Procfile to uvicorn main:app --reload --host 0.0.0.0 --port=${PORT} but still received the error: bash: line 1: main:app: command not found
Answer: After more research, I found that I had formed the Procfile incorrectly.  The correct format is web: uvicorn app.main:app --host=0.0.0.0 --port=${PORT:-5000}
The following article was helpful.
https://towardsdatascience.com/how-to-deploy-your-fastapi-app-on-heroku-for-free-8d4271a4ab9


New MDI child resizes other maximized Forms

Question: I have a project with a main MDI form.  There is a child MDI form inside that is always present and cannot be closed (Is it possible to hide the close button while keeping the min and max buttons?).  Because the child form is such an important part of the program, users like to have it maximized.  When another MDI child pops up, the maximized form returns to its original size.
Is there a way to keep an MDIchild maximized with other forms floating around in front?  Or can only the active form be maximized at any particular time?
EDIT - I'm specifically looking for whether or not VB6 supports such an operation.  Although work-arounds may be helpful, I'd prefer a simple yes or no answer.  So far it seems like 'no'.
Answer: If the child MDI form in question is "always present" and users like to keep it maximized, then it really shouldn't be a child form.  Instead, move the GUI features from this form to the main form.  You can put these controls on a panel (or other docking control) so that users can hide it and show it as required.
Comment: That sounds like a reasonable solution. However, I am not responsible for the design of the project and I think the transfer of the controls would be too large of a task for such a simple issue.  If there's simply no way to keep the form maximized in the presence of other forms, then that would be the answer to my question.
Answer: I had a similar issue a while back, I'm pretty sure that what you're describing is the normal way this things should be handled.  What I'd do is open that important form up so that it fills the whole MDI child area, but doesn't put its minimize-maximize buttons in the toolbar. Lock and anchor it there then handle the closequery method to not allow it to be closed.


Install MS Office on Windows Server 2008 - in support of Quickbooks RemoteApp

Question: How can I install MS Office on Windows Server 2008?  The purpose would be to enable Quickbooks to be able to export to Excel.
Quickbooks is set up to run as a RemoteApp in a Terminal Server environment.  The Quickbooks applicaiton senses whether or not Excel is installed and will not allow the user to create an Excel report unless Excel is actually installed on the client running Quickbooks.
Since the client and the server are the same machine in a Terminal Server environment, Excel must be installed on Windows Server for the Quickbooks Excel exporting feature to work in this setup.
There is no need to actually use Excel in a Terminal Services environment.  We only need to generate the Excel files using the server, then we can use an installed version Excel on a regular Windows 7 machine to work with the Excel file.
MS Office does not normally install on Windows Server.  Is there any way to buy a special license?  Could we somehow fool Quickbooks into thinking Excel is installed, if that would work?
Comment: Office installs on Windows Server just fine and pretty much always has since Microsoft added Terminal server/Remote Desktop support.  Older versions of office (2000,XP,2003) did need a special transform to be passed to the MSI though.  Office 2007,2010 work out of the box.
Answer: Excel will install just fine, but you need to be aware of the licensing requirements.  The upshot is that you need

a non-retail, non-OEM license of office for every computer that will be connecting to your terminal server and using the excel function.
A remote desktop CAL for every device (or every user) that will connect remotely

Please see the following for more info on the thrice-benighted world of MS RDS Licensing:  http://www.microsoft.com/licensing/about-licensing/briefs/remote-desktop-services.aspx
Comment: Just to clarify:  The site license worked, and the site license allowed office to install and run on Windows Server.  However, Windows Server disables the retail and OEM versions of MS Office after installation on the server.  This is how Microsoft forces you to purchase the site license for MS OFfice on Windows Server.
Comment: We have the CAL licenses for all of the users who currently use Quickbooks in the TS environment.  So we just need to obtain the non-retail, non-OEM copy of MS Office.  If 10 users already have an MS Office license on the desktop, do they each need a second license for the server?
Comment: It depends on the type of office license that they have on the desktop.  The retail and OEM licenses specifically prohibit network use, so if the office on their computers came from Best Buy or came pre-installed, you will need to buy additional licenses under an Open or select license scheme.  If you already bought the licenses under an open license, you should be all set.
Answer: Excel definitely installs on Server OSes, including 2008.  No fooling the OS, or special licenses required.
The rub is you're doing this on a Terminal Services environment, which does require a key that forgoes the product activation.  If you have a volume license agreement, the good news is that it should work.  (Does for us.)  Just make sure you're actually licensed for the number of users and TS/RD sessions that will using it, or you could end up in violation of your licensing agreement.
Comment: None of the users will actually be using Excel on the server, but the Quickbooks client may use some of the libraries to create the export file.  We don't have a volume license for MS Office, we just buy retail copies on Amazon.
Comment: @steampowered  It doesn't matter if the users actually use it, if it is used in their TS session, then a license (or CAL) is typically required.
Answer: To the best of my knowledge MS Office does indeed install on Server 2008 instances, I've got  [redacted] such installs right now. We didn't have any problems getting it on there, at least with Office 2010. Such installs are common in TS environments, so it is quite possible.
Comment: I think there may be some special licensing requirements, mentioned [here](http://social.technet.microsoft.com/Forums/en-US/office2007deployment/thread/a545c9f2-e449-4029-af04-11eaa5b40084/)  .  I am not too familiar with the world of MS licensing.   I'm looking for any info to get pointed in the right direction for a small business to solve this Quickbooks problem.
Answer: Office 2010, 2013, and 2016 does NOT install on Server 2008 STANDARD, but it does just fine on R2. I am trying to find a workaround or some way I can make that happen after I mistakenly took Office 2007 off a barely-used 2008 Std RDP server (oops) only to realize that nothing newer will install on it, but it seems an in place upgrade to 2008 R2 might be my only option, provided I actually have a license key for it.


How to include c++ libraries so that node-gyp can link?

Question: I am writing nodejs code and want to use C++ code (backend.cpp which includes 'mysql/mysql.h')  using node-gyp to compile. I am getting this error while building:
module.js:356
  Module.extensions[extension](this, filename);
                               ^
Error: ____/build/Release/backend.node: undefined symbol: mysql_init
Can anyone help? How can I instruct node-gyp to link mysql.h to the target backend.node?
Answer: Have you added it in the libraries list in your binding.gyp file?
Here's a short example:
{
  "targets": [
    {
      "target_name": "backend",
      "sources": [<comma separated source names>],
      "include_dirs":[<comma separated include dirs>],
      "libraries": [<comma separated library paths>]
    }
  ]
}

You should also take a look at the complete Gyp Language Specification


Is port channeling/LACP needed with kubernetes?

Question: I have a 6 server setup. Each server has 4 NICs with port channeling setup to my switch for redundancy and speed. My question is simply: Can kubernetes handle this without the port channeling? Or should I stay with the port channeling?
So if I do not use port-channeling:

Can kubernetes benefit by 4 NICs speedwise when communicating between servers?
If one NIC breaks, will kubernetes handle all traffic over the working NICs automatically?
Answer: It doesn't matter for kubernetes what kind of backend network you have: it works on top of existing OS interfaces.
Kubernetes expects you give it a reliable and fault tolerance network, hence if your hosts are communicating each other with all 4 NICs, Kubernetes will do that too.
If you don't use port channeling, then you have to avoid network loop; for example by using STP or a bonding algorithm like round-robin or active/passive. So answers are:

Depends on your network setup at OS level.
Not Kubernetes itself but the OS do the job.


Can't get state with react-router. (maybe not working react-redux connect())

Question: const mapStateToProps = (state)=>{
    return {
        userData: state.userData
    }
}

export default connect(mapStateToProps, null)(Init);

connected component like this.
btw when I read this.props, it doesn't have userData.
this.props is like below
http://prntscr.com/iypnvj

update with detail
route file
import * as React from 'react'
import { Route, IndexRoute } from 'react-router'
import {Layout} from "../components/layout/Layout";
import {Dashboard} from '../components/Dashboard/Dashboard';
import {User} from '../components/User/User';
import {UserEdit} from '../components/User/Edit';
import {Role} from '../components/Role/Role';
import {RoleEdit} from '../components/Role/Edit';
import {Register} from '../components/Register/Register';
import {Init} from '../components/Init/Init';

export default (store) => {
    return (
        <Route>
            <Route component={Layout}>
                <Route path="/" component={Init} />
                <Route path="/dashboard" component={Dashboard} />
                <Route path="/user" component={User} />
                <Route path="/user/create" component={UserEdit} />
                <Route path="/user/edit/:id" component={UserEdit} />
                <Route path="/role" component={Role} />
                <Route path="/role/create" component={RoleEdit} />
                <Route path="/role/edit/:id" component={RoleEdit} />
            </Route>
            <Route path="/register" component={Register} />
        </Route>
    )
}

layout file
import * as React from "react";
import NavBar from './NavBar';
import {bindActionCreators} from 'redux';
import { connect } from 'react-redux';
import { update_user_data } from '../../actions';
export class Layout extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
        };
    }
    render() {
        return (

                <NavBar />
                {this.props.children}

        );
    }
}

const mapStateToProps = (state)=>{
    return {
        userData: state.userData
    }
}

const mapDispatchToProps = (dispatch)=>{
    return bindActionCreators({
        update_user_data: update_user_data
    }, dispatch)
}

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

Navbar file
import * as React from "react";
import axios from 'axios';
import {
    Collapse,
    Navbar,
    NavbarToggler,
    NavbarBrand,
    Nav,
    NavItem,
    NavLink,
} from 'reactstrap';
import {User} from '../../models/user';
import Avatar from 'react-avatar';
import {bindActionCreators} from 'redux';
import { connect } from 'react-redux';
import { update_user_data } from '../../actions';

export class NavBar extends React.Component<any, any> {
    constructor(props) {
        super(props);
        this.toggle = this.toggle.bind(this);
        this.state = {
            isOpen: false,
            // user: new User()
        };
        axios.get('/api/users/me').then(resp=>{
            // this.setState({ user: resp.data[0] });
            this.props.update_user_data(resp.data[0])
        })
    }
    toggle() {
        this.setState({
            isOpen: !this.state.isOpen
        });
    }
    logout(){
        axios({
            method: 'post',
            url: 'api/users/logout',
            baseURL: '/'
        })
        .then(resp => {
            window.location.pathname = '/home'
        });
    }
    render() {
        return (

                <Navbar light expand="md" style={navbarStyle} fixed="top">
                    <NavbarBrand href="/">xxxxxxx</NavbarBrand>

                        Hi, {this.props.userData.name}

                            {
                                this.props.userData.avatar?
                                <Avatar round={true} size={40} src={"/api/avatar/"+this.props.userData.avatar} />
                                :
                                <Avatar round={true} size={40} name={this.props.userData.name} />
                            }

                        <NavbarToggler onClick={this.toggle} />

                    <Collapse isOpen={this.state.isOpen} navbar>

                            <NavItem>
                                <NavLink  onClick={this.logout.bind(this)}>Logout</NavLink >
                            </NavItem>

                    </Collapse>
                </Navbar>

        );
    }
}

const navbarStyle={
    boxShadow: '0px 0px 10px 2px rgba(0, 0, 0, 0.25)',
    background: 'white'
}

const mapStateToProps = (state)=>{
    return {
        userData: state.userData
    }
}

const mapDispatchToProps = (dispatch)=>{
    return bindActionCreators({
        update_user_data: update_user_data
    }, dispatch)
}

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

in navbar, I can get store http://prntscr.com/izpcfv
but in layout, same problem http://prntscr.com/izpcne
Answer: With no other details, I think it would more be related to react-redux than react-router. The way you try to display the state, from where or the error you have may be helpful.
If you decide to check your state in your <Init /> component, you could write something like this:
import store from './store.js';

const Init = (props) => {
  console.log(store.getState());
  return (
    //your JSX
   )
}

Also, be sure to have your routes inside <Provider store={store}></Provider>. Only the components rendered by the routes inside <Provider></Provider> can be connected to redux store.
Feel free to add some details if you are still stuck.
Comment: Thanks for your reply, but I have to use react-redux. I updated detail so would you take a look again?
Comment: You need to create a store first like "const store = createStore(yourReducer)" and then use this store in the Provider tag that should encapsulate all your routes. Without this, you can't access redux store. (Don't forget to import createStore from react-redux package.


Adding comments to user profiles

Question: I would like users on my site to write "feedback" of other users.
My thought is to have a content type called Feedback, and create a view of it, to preview at the foot of the user page. I can also put the main display of comments on its own views page.
Well, that's the display of them covered, but how do I enable them to be written? ie, link from the profile to create Feedback, and have it relate to that profile.
Also, Profile2 looks lacking, because you cannot control URL output.
Comment: So do you want to reference of other users on feedback ? Please describe your question in detail, though i have added answer based on my understanding of your question.
Comment: Have you tried http://drupal.org/project/reply
Answer: You can use the entity reference field. Entity Reference module provides the autocomplete field for the user reference.
Add an entity reference field on the feedback content type. This field is autocomplete field. So whenever you create a feedback you can select the name of the user for which you want to add the feedback and refer the same.
Still if you are unclear then provide me some more info so i can help you out..
Update: In your case you have to create a link on the user profile page and add the name of the user being viewed in the query string. So if you are viewing the profile of user1 then on the user profile you can generate the link $base_url/node/add/feedback?name = user1
Now when any one clicks on that page you will be redirected on the node creation page and you can get the argument value from the URL. You can set this argument value in the form field using hook_form_alter() hook.
Update 2: I found something like your question here
Comment: I don't want users to select the name of other users they wish to review.

I was hoping to have a link on user profile pages, like "leave feedback about this user", which would lead to a page to create the review.

I hope this makes sense.
Comment: Check the update of the answer :)

Adding comments to user profiles


Find/Prove Compact Subspace that is Non-Closed

Question: Let $\tau = \{\varnothing\} \cup \{G \subseteq \mathbb R: \mathbb R-G \ $is finite $\} $ and  $(\tau,\mathbb R)$ is the topology of the cofinite space.
Find a compact set $K \subseteq \mathbb R $ that is not closed.
We have just started topology and I am a bit stumped.
My ideas: As I need to find a set $K \subseteq\mathbb R $ whereby $K^{C}$ is finite. I would naturally suggest $\mathbb R-\{0\}$ or excluding some other finite subset, but then I get trouble in proving that it is compact. Any hints?
Answer: Take any countable subset $C$ of $\mathbb R$. Since it is neither $\mathbb R$ nor a finite set, it is not closed.
However, it is compact. Let $(A_\lambda)_{\lambda\in\Lambda}$ is an open cover of $C$. Take $c\in C$. Then there is a $\lambda_0\in\Lambda$ such that $c\in A_{\lambda_0}$. In particular, $A_{\lambda_0}\neq\emptyset$. SInce it is an open set, $\mathbb{R}\setminus A_{\lambda_0}$ is finite. So, only finitely many elements $c_1,\ldots,c_n$ of $C$ don't belong to $a_{\lambda_0}$. For each $k\in\{1,2,\ldots,n\}$, take $\lambda_k\in\Lambda$ such that $c_k\in A_{\lambda_k}$. Then $\bigl\{A_{\lambda_k}\,|\,k\in\{0,1,\ldots,n\}\bigr\}$ is a finite subcover of $(A_\lambda)_{\lambda\in\Lambda}$.
Comment: Because $A_{\lambda_0}\in\tau$ means that $A_{\lambda_0}=\emptyset$ or that $\mathbb{R}\setminus A_{\lambda_0}$ is finite. Since $A_{\lambda_0}\neq\emptyset$, $\mathbb{R}\setminus A_{\lambda_0}$ is finite
Comment: Thank you very much. One question though: What is the relevance of the definition of the topology $\tau$? I would have thought my subset $C$ would have to be $\in \tau$. But clearly a countable set $C$ is not $\in \tau$
Comment: Without the topology $\tau$, asking whether a set is closed or asking whether it is compact would make no sens. And the question was whether there is a subset **of the reals** which is compact but not closed.
Comment: I'm just missing something: why is $\mathbb R - A_{\lambda_{0}}$ finite as a result of $A_{\lambda_{0}}$ being open?
Comment: Of course, thanks!