text:
Q: Where to learn the syntax of mathematics? Since I started university, almost every exam I've had in mathematics have ended up as failed mostly due to my lack of using proper "syntax" on paper, written by hand.
Where can I learn the standard way of writing mathematics, beginning with the basics? Does this make sense? Is there a standard "uniform" syntax, or does it depend on locale - country from country?
EDIT: With syntax I mean the way you write down your logic on paper - for instance, how you should put up a solution for display; what format to use, when to use deduction/implication arrows, how your answer should be represented etc. When to tell whether you are you allowed to skip mental steps and so on?
Very simple example:
x(x + 3)(x + 7) =
= x(x^2 + 10x + 21) =
= x^3 + 10x^2 + 21x
Answer: x^3 + 10x^2 + 21x

vs
x(x + 3)(x + 7) = x^3 + 10x^2 + 21x

and so on... Hope this makes it a bit more clear?

A: Read your textbook and then use the syntax in your textbook when you take the exam.

A: Learning to write mathematics properly is much like learning to write any language properly, only more so because such a premium is placed on logical organization and clarity.
Mathematics, both the part that is written in words and the part that is written in symbols, is attempting to convey meaning. When you write and read symbols, think about what they say when you read them out loud. Every time you see the symbol $=$, remember that the symbol has a pronunciation when you read it, and it says "is equal to". So if you write things like
$$2x = 4 = \frac{4}{2}=2,$$
(which I see far too often on exams) then you are saying "twice $x$ is equal to four, which is equal to four halves, which is equal to $2$", which of course is false and liable to cost you points, even though you probably don't actually think that $4$ and $\frac{4}{2}$ are equal. Remember, first and foremost, that every symbol has a meaning and a pronunciation. Unless you recognize that, you won't be able to get very far.
So first you need to be clear on what you want to say, and then make sure that what you wrote actually conveys that meaning and not other meanings. If you can do that, even if it is with "plain English", you will have gotten over more than half the problem.
That said, mathematics is also a technical language with a number of conventions and jargon. The very best thing you can do to become familiar with, and good at using those conventions, is to read a lot of mathematics, with an eye towards understanding what is written and how the language helps that understanding (just like doing a lot of reading is one of the best ways to improve one's spelling).
A close second is to read books that are meant to help introduce you to proofs and logical arguments, usually with subtitles like "first course in advanced mathematics" or "introduction ot abstract/advanced mathematics". Find out what the "Intro to proofs" course is at your school, and look at the textbook they use.
One important thing is not to simply try to mimic the language you see: that will result in the mathematical equivalent of saying "Buenos días. Yo quiero estación de tren ser, por favor"  when trying to ask for directions to the train station ("Good morning. I want be train station, please.") You want to keep an eye on the meaning that the words are conveying, and how that particular choice of words (and even the order of the words) matters. Notice, for instance, that saying "For every $x$ there is a $y$" is not the same thing as saying "There is a $y$ such that for every $x$...", even though they may seem very similar when thought of in English.
So: always think first about what you are trying to say and make sure you say that. Read what you've written, pronouncing every symbol to yourself to make sure you aren't saying that you "want to be train station". And read your books and professors' notes to see how the language works and become familiar with it.
Added: It seems I rather badly misinterpret the true thrust of your question (despite the fact that you seem to have "accepted" my answer). In so far as what steps to add or what steps to skip, as has been pointed out, it depends on your level. I would not object to a student in my graduate abstract algebra class going from $x(x+1)(x+2)$ directly to $x^3+3x^2+2x$ (or even not writing out the computations before using it!) but I would definitely request a precalculus student to write out how he got to that final answer. If you have to stop and think carefully about what the answer is, then you should not skip the step and write it down. For a particular class, look at the textbook and which steps it works out explicitly and which steps it skips. Look at what steps your professor works out explicitly and which steps he skips. You'll want to not stray too far from them as far as skipping more steps (though of course you can always skip fewer steps if you are unsure about a calculation/argument).

A: It is not clear what you mean with "syntax".
Assuming you by "syntax" mean your way of reasoning, i.e. your "path" via logical connectives to the result, my best tip is to carefully read all proofs in your math book. Not only read through them, but understand them.
You must be able to prove things correctly, i.e. using only valid deductions. They way they do it in your math book is not a "local" thing, but "global" (no pun!). As long as your reasoning is understandable by anyone else reading it, it should be fine.
If you could be more spesific with what you mean by "syntax", I'm sure somebody could give a clearer answer.

A: The level of allowed ellipsis depends very much of your reader. It is part of the style, not syntax.
Some mathematicians like Laplace, are very boring to read because they spend so much time on tiny details. Some others are very difficult to follow because some of the most critical piece of reasoning are left as an exercise to the reader.
A famous example was written by Fermat in 1637: «cuius rei demonstrationem mirabilem sane detexi. Hanc marginis exiguitas non caperet» [I have discovered a truly marvelous proof of this, which this margin is too narrow to contain.] It took 358 years to rebuilt the missing steps. In facts, almost every work of Fermat was first rejected by the mathematical community,... before he had a chance to work out and publish the details.
So, don't lose hope, even master mathematicians fail the exam.


text:
Q: Expected amount of time until Fred buys a new computer
Fred's beloved computer will last an $Expo(λ)$ amount of time until it has a malfunction. When that happens, Fred will try to get it fixed. With probability $p$, he will be able to get it fixed. If he is able to get it fixed, the computer is good as new again and will last an additional, independent $Expo(λ)$ amount of time until the next malfunction (when again he is able to get it fixed with probability p, and so on). If after any malfunction Fred is unable to get it fixed, he will buy a new computer. Find the expected amount of time until Fred buys a new computer. (Assume that the time spent on computer
  diagnosis, repair, and shopping is negligible.)

$T$~$Expo(λ)$; Let $X$ be the time untill he buys a new computer:
$E[X]=E[X|I_p=1]p+E[X|I_p=0]q$, where the first term in the right by meaning says that with prob. $p$ computer on average lasted $E[T]$ time untill it get broken +$E[X]$ after being repaired till the moment of being replaced.
But this logic is wrong. Can you give me a hint?

A: Let $N$ be the number of malfunctions until Fred buys a new computer and $\{T_1,T_2,\ldots,T_N\}$ be the time intervals between malfunctions. Given $\mathbb{E}[T_i] = \dfrac{1}{\lambda}$ and $\mathbb{E}[N] = \dfrac{1}{1-p}$. The time to buy a new computer is $ X = \sum_{i=1}^N T_i$. Using Wald's lemma, the expected time is $\mathbb{E}[X] = \mathbb{E}[T]\mathbb{E}[N] = \dfrac{1}{\lambda(1-p)}$.

A: Slick approach using Poisson process splitting/superposition:
The problem can be viewed as a Poisson process with rate $\lambda$, with each malfunction (arrival) being independently labeled "fixable" or "unfixable" with probability $p$ or $1-p$ respectively. By Poisson splitting, the fixable malfunctions form a Poisson process of rate $p\lambda$, and and the unfixable malfunctions form a Poisson process of rate $(1-p)\lambda$, and these two processes are independent. You are then asking for the expected time until the first unfixable malfunction, which is the expectation of an $\text{Expo}((1-p)\lambda)$ random variable, i.e. $\frac{1}{(1-p) \lambda}$.

Direct approach:
Let $T_1$ be the time until the first malfunction, and let $X$ be the time until the first unfixable malfunction. Let $I_1$ be the indicator for the event that the first malfunction is fixable.
$$E[X] = (1-p) E[X \mid I_1=0] + p E[X \mid I_1 = 1].$$
Note $E[X \mid I_1 = 0] = E[T_1]$. Note also that $E[X \mid I_1 = 1] = E[X] + E[T_1]$, since after this malfunction the process is identical to the original process. Thus
$$E[X] = (1-p) E[T_1] + p(E[X] + E[T_1]).$$
Solving for $E[X]$ yields the same answer as above.

A: Using your defined variables, we have
$$E(X)=(1−p)E(T)+p(E(X)+E(T))$$
What this means is that, if the computer malfunctions and is not successfully fixed, the lifetime is simply the value of $T$. If the computer is fixed, time elapsed is that of $T$ and further time is reset so it's back to $E(X)$. Solving this is surely not an issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can MWAA requirements.txt be automatically set to the latest version? We have an automated upload system for our DAG's to MWAA.
Is there a way to have the requirements.txt in the S3 bucket be automatically set to its latest version?
I cannot find an option for this in the AWS console.

A: It's in the setup of MWAA. Edit MWAA instance, in the requirements.txt field, set the version to the latest.
Also,
MWAA uses requirements file to create the container image. So when you upload requirement file and specify it in the edit options and save, images are created(it takes couple of minutes to do it). Ideally image should only be updated when you have new python libraries to add. if you still want to automate, try to use lambda S3 trigger and use mwaa cli to trigger the update-environment command.


text:
Q: NewLateBinding.LateSet to reflection call Assume I have an Excel.PivotField, and I need to setHiddenItemsList on my object.
With VB.NET and Option Strict Off & Option Explicit Off this would result in:
Dim field as Excel.PivotField = MyFunctionCall()
field.HiddenItemsList = GetHiddenItems()
While this works with this security setting, it obviously doesn't work when you set Option Strict On and Option Explicit On.
The IDE cannot resolve the HiddenItemsList property on my PivotField (first problem).
But when using late binding, it works perfectly.
Now the next step is to enable Option Strict and Explicit (we are going to convert to C# in the future).
So I look how the code is compiled:
NewLateBinding.LateSet(field , Nothing, "HiddenItemsList", New Object() { GetHiddenItems() }, Nothing, Nothing)

Easy right?
But this code relies on the Microsoft.VisualBasic namespace. And ofcourse, we don't want that.
So I tried converting it to a plain Reflection call:
GetType(Excel.PivotField).GetProperty("HiddenItemsList").SetValue(field , GetHiddenItems() , Reflection.BindingFlags.SetProperty, Nothing, Nothing, Nothing)
Unfortunatly the first part (GetType(Excel.PivotField).GetProperty("HiddenItemsList")) already returns Nothing, so I'm stuck there.
And help? ;-)

A: Always nice to answer your own question.
Since GetType(Excel.PivotField).GetProperty("HiddenItemsList") returns Nothing, we need another way.
There is a method on Type, namely InvokeMember, and with the right properties the method works!
Here's the answer for other SO-ers :D
GetType(Excel.PivotField).InvokeMember("HiddenItemsList", Reflection.BindingFlags.SetProperty, Nothing, field, New Object() {GetHiddenItems() }, Nothing, Nothing, Nothing)
Cheers


text:
Q: Angular JS: ng-click scope set doesn't work in ng-if Today, I have seen a bug in angularjs:
When you try to set a scope value directly in a ng-click, it doesn't work when your ng-click is in a ng-if which test the same scope value -> http://jsfiddle.net/9j2TL/26/
angular.module('test', [])
.controller('testCtrl', function($scope) {
    $scope.step = 1;

    $scope.setStep = function(step) {
         $scope.step = step;
    };
});

                <button class="btn btn-primary btn-lg" ng-click="step = 2">Without ngif block</button>

 1">

                <button class="btn btn-primary btn-lg" ng-click="step = 3">with ngif block</button>

 1">

                <button class="btn btn-primary btn-lg" ng-click="setStep(3)">With ngif block and scope function</button>

        step value : {{ step }}

To solve it, you should create a scope function...
If somebody have a explication for this problem, I would be happy to understand it !
thx :)

A: It's not a bug, i think that "ng-if" creates its an own scope, so when you do here: "step = 3", you're creating and assign this variable in a separate scope than your controller

 1">

                <button class="btn btn-primary btn-lg" ng-click="step = 3">with ngif block</button>

And here you still in a separate scope but when you call a function, probably angular will look for this function inside your scope, but when angular doesn't find it, it will look for the function in your parent scope, and when find it, it will assign to your step parent scope variable, that's why it work here and not in your code above.

 1">

                <button class="btn btn-primary btn-lg" ng-click="setStep(3)">With ngif block and scope function</button>

I think that it is what is happening, if anyone could confirm it would be great!

A: I don't think this is a bug.  You are just auto-creating properties and confusing scopes in the view.
Updated Fiddler.
This does work:

 1">

        <button class="btn btn-primary btn-lg" ng-click="$parent.step = 3">with ngif block</button>

This is happening because self inside of the ng-if is creating a new scope.

A: ng-if creates its own scope, which can complicate things.
Changing ng-if to ng-show should solve the problem.


text:
Q: Create cross terms in pandas dataframe How should I generate the data2 from data1?
The columns (start & end) of data2 should be the corss terms of data1. The corresponding values will be assigned to each cross term.
Thanks in advance!

    data = pd.DataFrame([['EU', ('a b'), ('d e'), ('1 2 3 4')],
                         ['NA', ('g h i'), ('j k l'), ('11 12 13 14 15 16 17 18 19')]],
                        columns=['region', 'start', 'end', 'values'])

      region  start    end                      values
    0     EU    a b    d e                     1 2 3 4
    1     NA  g h i  j k l  11 12 13 14 15 16 17 18 19

  data2 = pd.DataFrame([['EU', 'a', 'd', 1], ['EU', 'a', 'e', 2], ['EU', 'b', 'd', 3], ['EU', 'b', 'e', 4],
                          ['NA', 'g', 'j', 11], ['NA', 'g', 'k', 12], ['NA', 'g', 'l', 13],
                          ['NA', 'h', 'j', 14], ['NA', 'h', 'k', 15], ['NA', 'h', 'l', 16],
                          ['NA', 'i', 'j', 17], ['NA', 'i', 'k', 18], ['NA', 'i', 'l', 19]],
                         columns=['region', 'start', 'end', 'values'])

   region start end  values
0      EU     a   d       1
1      EU     a   e       2
2      EU     b   d       3
3      EU     b   e       4
4      NA     g   j      11
5      NA     g   k      12
6      NA     g   l      13
7      NA     h   j      14
8      NA     h   k      15
9      NA     h   l      16
10     NA     i   j      17
11     NA     i   k      18
12     NA     i   l      19

A: You can split the strings, explode start and end successively, then use groupby.transform to explode the values per group in place:
out = (data
 .assign(start=data['start'].str.split(),
         end=data['end'].str.split(),
         values=data['values'].str.split(),
        )
 .explode('start').explode('end')
 .assign(values=lambda d: d.groupby(level=0)['values']
                           .transform(lambda g: g.iloc[0]))
 .reset_index(drop=True)
)

NB. this requires that the number of values after splitting is equal to the product of the number of start and end values.
output:
   region start end values
0      EU     a   d      1
1      EU     a   e      2
2      EU     b   d      3
3      EU     b   e      4
4      NA     g   j     11
5      NA     g   k     12
6      NA     g   l     13
7      NA     h   j     14
8      NA     h   k     15
9      NA     h   l     16
10     NA     i   j     17
11     NA     i   k     18
12     NA     i   l     19


text:
Q: $c$ is the value of $x^3+3x-14$ where $x=\sqrt[3]{7+5\sqrt2}-\frac{1}{\sqrt[3]{7+5\sqrt2}}$.Find the value of $a+b+c$ $a=\sqrt{57+40\sqrt2}-\sqrt{57-40\sqrt2}$ and $b=\sqrt{25^{\frac{1}{\log_85}}+49^{\frac{1}{\log_67}}}$ and $c$ is the value of $x^3+3x-14$ where $x=\sqrt[3]{7+5\sqrt2}-\frac{1}{\sqrt[3]{7+5\sqrt2}}$.Find the value of $a+b+c$.

I tried to solve and simplify this problem but no luck.Please help me.Thanks.

A: $$a^2=57+40\sqrt2+57-40\sqrt2-2\sqrt{57^2-40^2\cdot2}=2\cdot57-2\sqrt49=100$$
$$a=10$$
$$b=\sqrt{5^{2\log_5 8}+7^{2\log_7 6}}=\sqrt{8^2+6^2}=\sqrt100=10$$
$$x=a-\frac1a,\quad a=(7+5\sqrt2)^{\frac13}$$
$$x^3+3x-14=\left(a^3-3a+\frac3a-\frac1{a^3}\right)+3\left(a-\frac1a\right)-14\\
=a^3-\frac1{a^3}-14=7+5\sqrt2-\frac1{7+5\sqrt2}-14=7+5\sqrt2-\frac{7-5\sqrt2}{-1}-14\\
=0=c$$

A: (1) $a=(5+4\sqrt{2})-(4\sqrt{2}-5)=10$
(2) $b=\sqrt{25^{\log_5{8}}+49^{\log_7{6}}}=\sqrt{8^2+6^2}=10$
(3) $x=\sqrt[3]{7+5\sqrt2}-\frac{1}{\sqrt[3]{7+5\sqrt2}}=(\sqrt{2}+1)-\frac{1}{\sqrt{2}+1}=(\sqrt{2}+1)-(\sqrt{2}-1)=2$, $c=8+6-14=0$


text:
Q: Parsing CSV File with \" in C# I'm using VB's TextField in C# to parse a CSV file. But I am getting an error when it gets to \"
using (TextFieldParser csvReader = new TextFieldParser(csvFilePath)) {
    csvReader.SetDelimiters(new string[] { "," });
    csvReader.HasFieldsEnclosedInQuotes = true;
    string[] colFields = csvReader.ReadFields();
    foreach (string column in colFields)
    {
        DataColumn datacolumn = new DataColumn(column);
        datacolumn.AllowDBNull = true;
        csvData.Columns.Add(datacolumn);
    }
    while (!csvReader.EndOfData)
    {
        string[] fieldData = csvReader.ReadFields();
        for (int i = 0; i < fieldData.Length; i++)
        {
            if (fieldData[i] == "")
            {
                fieldData[i] = null;
            }
        }
        csvData.Rows.Add(fieldData);
    }
}

And this is the line in the csv that is causing the error:
"101","Brake System","Level should be between \"MIN\" and \"MAX\" marks."

I don't know how to deal with the \" in C# using TextFieldParser

A: If the csv file will fit into memory, you could read it in, replace each \" with "", and use a MemoryStream as the input to the the TextFieldParser:
string data = File.ReadAllText(@"C:\temp\csvdata.txt").Replace("\\\"", "\"\"");

//TODO: Use the correct Encoding.
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data)))
{
    using (TextFieldParser csvReader = new TextFieldParser(ms))
    {
        csvReader.SetDelimiters(new string[] { "," });
        csvReader.HasFieldsEnclosedInQuotes = true;
        string[] colFields = csvReader.ReadFields();
        foreach (string s in colFields)
        {
            Console.WriteLine(s);
        }
    }
}

Which, for your example data, outputs

101
  Brake System
  Level should be between "MIN" and "MAX" marks.

A: Here's how to do it using two different methods without using TextFieldParser.  TextFieldParser is very slow and not recommended for use in an actual production application.
Here's the simpler method using just String methods, and assuming that it's delimited with , without any quotes or any other special CSV formatting.
FileInfo file = new FileInfo("myfile.csv");
using (TextReader reader = file.OpenText())
{
    for(String line = reader.ReadLine(); line != null; line = reader.ReadLine())
    {
         string[] fields = line.Split(new[] {','});
         foreach(String f in fields)
         {
             //do whatever you need for each field
          }
     }
 }

Now if you want to use CsvHelper (available on nuget) becaues you have a more complicated CSV file with things like quoted field, headers, or if the rows of your CSV can map directly to an object that you have then this library might help you.
Not Mapped Example:
FileInfo file = new FileInfo("myfile.csv");
using (TextReader reader = file.OpenText())
using (CsvReader csv = new CsvReader(reader))
{
     csv.Configuration.Delimiter = ",";
     csv.Configuration.HasHeaderRecord = false;
     csv.Configuration.IgnoreQuotes = true; //if you don't use field quoting
     csv.Configuration.TrimFields = true; //trim fields as you read them
     csv.Configuration.WillThrowOnMissingField = false; //otherwise null fields aren't allowed

     while(csv.Read())
     {
          myStringVar = csv.GetField<string>(0); //gets first field as string
          myIntVar = csv.GetField<int>(1); //gets second field as int
          ... //etc, you get the idea

     }
}

Mapped Example:
Mapping Class- Assumes you have a class named MyClass with the fields named field1, field2, field3
public sealed class MyClassMap : CsvClassMap<MyClass>
{
     public MyClassMap()
     {
         Map(m => m.field1).Index(0);
         Map(m => m.field2).Index(1);
         Map(m => m.field3).Index(2);
     }
 }

Parsing Code
FileInfo file = new FileInfo("myfile.csv");
using (TextReader reader = file.OpenText())
using (CsvReader csv = new CsvReader(reader))
{
     csv.Configuration.Delimiter = ",";
     csv.Configuration.HasHeaderRecord = false;
     csv.Configuration.IgnoreQuotes = true; //if you don't use field quoting
     csv.Configuration.TrimFields = true; //trim fields as you read them
     csv.Configuration.WillThrowOnMissingField = false; //otherwise null fields aren't allowed
     csv.Configuration.RegisterClassMap<MyClassMap>(); //adds our mapping class to the reader

     while(csv.Read())
     {
         myObject = csv.GetRecord<MyClass>();
         //do whatever here
     }
}

Both of these methods won't care that you have any strange characters like \ in your csv file.
Disclaimer: I have no relation to CsvHelper, but have had success with it in a few projects in the past in which it has made my life much easier

A: If you don't mind using a different library, Ctl.Data has a mode (parseMidQuotes: true) specifically to allow parsing broken CSV like this.
using (StreamReader sr = new StreamReader("data.csv"))
{
    var reader = new CsvReader<Record>(sr, parseMidQuotes: true, readHeader: false);

    while (reader.Read())
    {
        Record rec = reader.CurrentObject.Value;
        rec.Description = rec.Description.Replace("\\\"", "\"");

        // use record...
    }
}

And define your Record object:
(Normally it would match the header of the file to the properties, but in your case with a headerless file you need to specify the order with the Column attribute.
class Record
{
    [Column(Order = 0)]
    public int Id { get; set; }

    [Column(Order = 1)]
    public string Category { get; set; }

    [Column(Order = 2)]
    public string Description { get; set; }
}

(Disclaimer: I'm the author of said library)


text:
Q: Edit NSPredicate using NSPredicateEditor I have a NSPredicateEditor from which I want to extract the predicate as a string. I'm using the following code:
[[predicateEditor objectValue] description]

and it extract the predicate in a form like this:
"Author" MATCHES "John"

the problem is that in this predicate I can't find any hint about the first part of the NSPredicateEditor, the ANY/ALL part.

How can I extract it in NSString form? Thanks

A: The issue here is that for a single case the predicate intrinsically/logically contains "ALL" behavior, without the "ALL" string  actually needing to be set in the predicate.
Logically "author matches john" is the same as "ALL(author matches john").
If you create an NSCompoundPredicate and set it as the NSPredicateEditor's objectValue the "All" row should be displayed automatically, even if the predicate format string itself does not contain the string "ALL". But setting a standard NSPredicate (rather than NSCompoundPredicate) may not give you the ALL row.


text:
Q: code crashes after exit? for whatever reason my code crashes but only AFTER I exit out of the program (by hitting "X") anyone know why it is doing this? here is my code.
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <windows.h>
#include <time.h>

#include <SDL/SDL.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glext.h>
using namespace std;

/*
const int AIR = 0;
const int STONE = 1;
const int DIRT = 3;
const int GRASS = 4;
*/

float SCALE = .5;
const int chunkSize = 16;
const int chunkSizeY = 256;
const int blocksTotal = 4;
int chunk[chunkSize][chunkSizeY][chunkSize];
time_t seconds;
int seed = 0;
int quads;

struct block {
  bool Solid;
  int DepthMAX;
  int DepthMIN;
  int R;
  int G;
  int B;
  int id;
} AIR, STONE, DIRT, GRASS;

    block * blockType = new block[3];

void buildChunk();
void renderChunk();
void countFaces();
void render();
void logic();

void drawCube(float size,int x,int y,int z,float redValue,float greenValue,float blueValue)
{

    float halfSize = size / 2;
    float xSize = x * size;
    float ySize = y * size;
    float zSize = z * size;

    glBegin(GL_QUADS);
glColor3f(redValue,greenValue,blueValue);

///     front face
    if(z+1 < chunkSize)
    {
        if(chunk[x][y][z+1] == AIR.id)
        {
            // front face
            glNormal3f(0.0,0.0,1.0);
    //glColor3f(0,200,255);
    glTexCoord2f(1.0,1.0);
    glVertex3f(xSize + halfSize, ySize + halfSize, zSize + halfSize);
    glTexCoord2f(0.0,1.0);
    glVertex3f(xSize - halfSize, ySize + halfSize, zSize + halfSize);
    glTexCoord2f(0.0,0.0);
    glVertex3f(xSize - halfSize, ySize - halfSize, zSize + halfSize);
    glTexCoord2f(1.0,0.0);
    glVertex3f(xSize + halfSize, ySize - halfSize, zSize + halfSize);
                quads++;

        }
    }
    else
    {
        //glColor3f(1,0,0);
        if(z+1 >= chunkSize)
        {
            glNormal3f(0.0,0.0,1.0);
    //glColor3f(0,200,255);
    glVertex3f(xSize + halfSize, ySize + halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize + halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize - halfSize, zSize + halfSize);
    glVertex3f(xSize + halfSize, ySize - halfSize, zSize + halfSize);
                quads++;
        }
    }

    // left face
    if(x-1 > -1)
    {
        if(chunk[x-1][y][z] == AIR.id)
        {
            //glColor3f(0.0,1.0,0.0);
            glNormal3f(-1.0,0.0,0.0);
            glVertex3f(xSize - halfSize, ySize + halfSize, zSize + halfSize);
            glVertex3f(xSize - halfSize, ySize - halfSize, zSize + halfSize);
            glVertex3f(xSize - halfSize, ySize - halfSize, zSize - halfSize);
            glVertex3f(xSize - halfSize, ySize + halfSize, zSize - halfSize);
            quads++;
        }
    }
    else
    {
        //glColor3f(1,1,1);
        if(x-1 < 0)
        {
            glNormal3f(-1.0,0.0,0.0);
            glVertex3f(xSize - halfSize, ySize + halfSize, zSize + halfSize);
            glVertex3f(xSize - halfSize, ySize - halfSize, zSize + halfSize);
            glVertex3f(xSize - halfSize, ySize - halfSize, zSize - halfSize);
            glVertex3f(xSize - halfSize, ySize + halfSize, zSize - halfSize);
            quads++;
        }
    }

    // back face

    if(z-1 > -1)
    {
        if(chunk[x][y][z-1] == AIR.id)
        {
            //glColor3f(0.0,0.0,1.0);
            glNormal3f(0.0,0.0,-1.0);
            glVertex3f(xSize + halfSize, ySize + halfSize, zSize - halfSize);
            glVertex3f(xSize - halfSize, ySize + halfSize, zSize - halfSize);
            glVertex3f(xSize - halfSize, ySize - halfSize, zSize - halfSize);
            glVertex3f(xSize + halfSize, ySize - halfSize, zSize - halfSize);
            quads++;
        }
    }
    else
    {
        //glColor3f(0,1,1);
        if(z-1 < 0)
        {
            glNormal3f(0.0,0.0,-1.0);
            glVertex3f(xSize + halfSize, ySize + halfSize, zSize - halfSize);
            glVertex3f(xSize - halfSize, ySize + halfSize, zSize - halfSize);
            glVertex3f(xSize - halfSize, ySize - halfSize, zSize - halfSize);
            glVertex3f(xSize + halfSize, ySize - halfSize, zSize - halfSize);
            quads++;
        }
    }

    // right face
    if(x+1 < chunkSize)
    {
        if(chunk[x+1][y][z] == AIR.id)
        {
            //glColor3f(1.0,1.0,0.0);
            glNormal3f(1.0,0.0,0.0);
            glVertex3f(xSize + halfSize, ySize + halfSize, zSize + halfSize);
            glVertex3f(xSize + halfSize, ySize - halfSize, zSize + halfSize);
            glVertex3f(xSize + halfSize, ySize - halfSize, zSize - halfSize);
            glVertex3f(xSize + halfSize, ySize + halfSize, zSize - halfSize);
            quads++;
        }
    }
    else
    {
        //glColor3f(0,1,0);
        if(x+1 >= chunkSize)
        {
            glNormal3f(1.0,0.0,0.0);
            glVertex3f(xSize + halfSize, ySize + halfSize, zSize + halfSize);
            glVertex3f(xSize + halfSize, ySize - halfSize, zSize + halfSize);
            glVertex3f(xSize + halfSize, ySize - halfSize, zSize - halfSize);
            glVertex3f(xSize + halfSize, ySize + halfSize, zSize - halfSize);
            quads++;      }
    }

    // top face
    if(y+1 < chunkSizeY)
    {
        if(chunk[x][y+1][z] == AIR.id)
        {
    //glColor3f(1.0,0.0,1.0);
    glNormal3f(0.0,1.0,0.0);
    glVertex3f(xSize + halfSize, ySize + halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize + halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize + halfSize, zSize - halfSize);
    glVertex3f(xSize + halfSize, ySize + halfSize, zSize - halfSize);
    quads++;
        }
    }else
    {
        //glColor3f(0,1,0);
        if(y+1 >= chunkSizeY)
        {
glNormal3f(0.0,1.0,0.0);
    glVertex3f(xSize + halfSize, ySize + halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize + halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize + halfSize, zSize - halfSize);
    glVertex3f(xSize + halfSize, ySize + halfSize, zSize - halfSize);
    quads++;
        }
    }
    // bottom face
    if(y-1 > -1)
    {
        if(chunk[x][y-1][z] == AIR.id)
        {
    //glColor3f(0.0,1.0,1.0);
    glNormal3f(0.0,-1.0,0.0);
    glVertex3f(xSize + halfSize, ySize - halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize - halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize - halfSize, zSize - halfSize);
    glVertex3f(xSize + halfSize, ySize - halfSize, zSize - halfSize);
    quads++;
        }
    }else
    {
        //glColor3f(1,1,1);
        if(y-1 < 0)
        {
    glNormal3f(0.0,-1.0,0.0);
    glVertex3f(xSize + halfSize, ySize - halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize - halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize - halfSize, zSize - halfSize);
    glVertex3f(xSize + halfSize, ySize - halfSize, zSize - halfSize);
    quads++;
        }
    }

    glEnd();
}
float angle = 0.0;
const int triangle = 1;

void init()
{
    //AIR
blockType[0].id = 0;
blockType[0].R = 0;
blockType[0].G = 0;
blockType[0].B = 0;
    //STONE
blockType[1].id = 1;
blockType[1].R = 0;
blockType[1].G = 0;
blockType[1].B = 1;
blockType[1].DepthMAX = 5;
blockType[1].DepthMIN = 0;
    //DIRT
blockType[2].id = 2;
blockType[2].R = 1;
blockType[2].G = 0;
blockType[2].B = 0;
blockType[2].DepthMAX = 10;
blockType[2].DepthMIN = 6;
    //GRASS
blockType[3].id = 3;
blockType[3].R = 0;
blockType[3].G = 1;
blockType[3].B = 0;
blockType[3].DepthMAX = 20;
blockType[3].DepthMIN = 11;

AIR.Solid = false;
AIR.id = 0;
STONE.id = 1;
DIRT.id = 2;
GRASS.id = 3;

    seconds = time (NULL);
    seed = seconds;
    srand(seed);
    /* Seed the random number generator with the specified seed */

    glClearColor(0.0,0.0,0.0,1.0);  //background color and alpha
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45,640.0/480.0,1.0,500.0);
    glMatrixMode(GL_MODELVIEW);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_COLOR_MATERIAL);
        glEnable(GL_LIGHTING);
        glEnable(GL_LIGHT0);
        float dif[] = {1.0,1.0,1.0,1.0};
        glLightfv(GL_LIGHT0, GL_DIFFUSE, dif);
        float amb[] = {0.2,0.2,0.2,1.0};
        glLightfv(GL_LIGHT0, GL_AMBIENT, amb);

    buildChunk();
}

void render()
{

    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
        float pos[] = {-2.0,2.0,-3.0,1.0};
        glLightfv(GL_LIGHT0, GL_POSITION, pos);
    glTranslatef(0.0,0.0,-40.0);
    glRotatef(angle,1.0,0.0,0.0);   // angle, x-axis, y-axis, z-axis
    renderChunk();

}

int main(int argc, char** argv)
{
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Surface *screen;
    screen = SDL_SetVideoMode(640, 480, 8, SDL_SWSURFACE|SDL_OPENGL);
//     screen = SDL_SetVideoMode(640, 480, 8, SDL_SWSURFACE|SDL_FULLSCREEN);
    bool running = true;
    const int FPS = 30;
    Uint32 start;
    SDL_Event event;
    init();
    while(running)
    {
        start = SDL_GetTicks();
        while(SDL_PollEvent(&event))
        {
            switch(event.type)
            {
            case SDL_QUIT:
                running = false;
                break;
            }
        }

        logic();
        quads = 0;
        render();

        SDL_GL_SwapBuffers();
        angle += 0.5;
        if(angle > 360)
            angle -= 360;
        if(1000/FPS > SDL_GetTicks()-start)
            SDL_Delay(1000/FPS-(SDL_GetTicks()-start));
    }

    countFaces();
    cout << "QUADS: " << quads << endl;
    cout<<"vertics: " << quads * 4 << endl;

delete [] blockType;
    SDL_Quit();
    return 0;
}

void buildChunk()
{

    int x;
    int y;
    int z;

    for(x=0; x < chunkSize; x++)
    {
        for(y=0; y < chunkSizeY; y++)
        {
            for(z=0; z < chunkSize; z++)
            {

                /* 50% chance for a cell to be alive */
                if(rand() % 100 < 50)
                {
                    chunk[x][y][z] = AIR.id;
                }
                else
                {
                    for(int i=1; i < blocksTotal; i++){
                    if(y <= blockType[i].DepthMAX && y >= blockType[i].DepthMIN){
                            chunk[x][y][z] = blockType[i].id;
                        }

                    }
                }
                cout<< "chunk[" << x << "][" << y << "][" << z << "]  state: " << chunk[x][y][z]<<endl;
            }
        }
    }
}

void renderChunk()
{
    int x;
    int y;
    int z;

    for(x=0; x < chunkSize; x++)
    {
        for(y=0; y < chunkSizeY; y++)
        {
            for(z=0; z < chunkSize; z++)
            {

                if(chunk[x][y][z] != blockType[0].id)
                {
                    for(int i=1; i < blocksTotal; i++){
                    if(chunk[x][y][z] == blockType[i].id)
                    {
                        drawCube(SCALE,x,y,z,blockType[i].R,blockType[i].G,blockType[i].B);

                        }
                    }
                }

            }
        }
    }
}

void logic()
{

}

void countFaces()
{

}

I think it might have something to do with the struct array I added and deleted?

A: You allocate space for three elements:
block * blockType = new block[3];

but then access four:
    //AIR
blockType[0].id = 0;
...
    //STONE
blockType[1].id = 1;
...
    //DIRT
blockType[2].id = 2;
...
    //GRASS
blockType[3].id = 3;
...

This results in memory corruption (technically, undefined behaviour).
The new should read
block * blockType = new block[4];


text:
Q: Why am I getting "argument of type char is incompatible with parameter of type FILE"? What could be a possible replacement for that?
I do not know what to change it to.
bool File_Exits(char fileName[]) {

    FILE* fp = fopen_s(fileName, "r");
    if (fp) {
        fclose(fp);
        return true;
    }
    return errno != ENOENT;
}

bool isFileCanBeRead(char fileName[]) {
    FILE* fp = fopen_s(fileName, "r");
    if (fp) {
        fclose(fp);
        return true;
    }
    return errno != ENOENT && errno != EPERM;
}

A: See the definition of fopen_s in this reference:
fopen_s, _wfopen_s.

errno_t fopen_s(
   FILE** pFile,
   const char *filename,
   const char *mode
);

Try this instead:
FILE *fp = nullptr;
errno_t openResult = fopen_s(&fp, filename, "r");


text:
Q: mvc bundling, one per view I am working with mvc4 and exploring how bundling of css and javascript works. I have a question that I need assistance with.
For every page (view) I render I would like to just have one js and css file. This is a culmination of the multiple files that are required for that view. From what I have seen, I can create bundles of files but I did not see a way of creating a bundle for each view.
Could someone help me out with this, if it is possible to achieve what I outlined?

A: Be more specific with your question. Show us what you tried. You have to create each of the bundles manually. If you want a bundle to be used on a specific view, create such a bundle and specify in a view that you will use that bundle there just like you specify in a view that you will be using a css file there.

A: What you need to do is go to Static>App_Start>BundleConfig.cs :

and then create a bundle for each view you have:
public class BundleConfig
{
    // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/GlobalScripts")
                            .Include("~/Static/Scripts/jquery-1.10.2.js"
                                    , "~/Static/Scripts/json2.js"
                                    , "~/Static/Scripts/jquery-ui-1.10.4.js"
                                    //, "~/Static/Scripts/jquery.layout-1.3.0.js"
                                    //, "~/Static/Scripts/jquery.layout.state.js"
                                    , "~/Static/Scripts/helper.mainlayout.js"));
    }
}

just keep adding your script path in .Include() for every javascript in the view and keep doing bundles.add(new ScriptBundle(<bundle path>)) for every view you have.
you will do the similar steps with CSS bundles, but instead of using ScripBundle you will use StyleBundle
To lessen the repetition of codes try creating a list of strings for every javascripts that are dependent to one another and do a union on them:
List<string> jqGridScripts = new List<string>
                             {"~/Static/Scripts/jquery.jqGrid.src.js"
                             , "~/Static/Scripts/i18n/grid.locale-en.js"
                             , "~/Static/Scripts/helper.jqgrid.js"};
List<string> jqStopwatch = new List<string>
                             { "~/Static/Scripts/jquery.stopwatch.js" };

bundles.Add(new ScriptBundle("~/bundles/viewName")
                             .Include(jqGridScripts
                                     .Union(jqStopwatch).ToArray()));

Just remember that the order in which they appear on the array is the same order in which they will appear on the HTML or be bundled and minified.
Code in View:
@section scripts{
    @Scripts.Render("~/bundles/viewName");
}

Resultant Code in HTML
<script src="/WDCSS/bundles/viewName?v=T3IlBuvfGTiz62pwDuiPogFX1jQoxVC2tmp3K6wffBQ1"></script>

My Opinion
I don't really know if we should do this or not. For me I separate scripts that are used in all pages in a separate bundle so that it would be cached. and then create another bundle for the scripts used in a view. What I am trying to say is that we should achieve a balance between bundling, minification, and caching.


text:
Q: In CKAN how do I list all the dataset resources with a table / entry in the DataStore? In CKAN how do I list all the dataset resources with a table / entry in the DataStore?
That is, put a different way, can I find out what dataset resources have data loaded into the DataStore?
Also can I just list all the entries / tables in the DataStore?

A: There is a special view _table_metadata that contains all tables and views in the datastore. Although, it is mainly used for internally, it can also be used to get a full list of all datastore resources.
Example call: http://demo.ckan.org/api/action/datastore_search?resource_id=_table_metadata
See the docs for details about the _table_metadata view.


text:
Q: How to overwrite a text in TextView using a button? I'm working on an app that generates passwords randomly using the array. The password is in TextView. Everything is good unless I want to generate a new password second time. How can I "delete" the old text (password) from the TextView and replace it with the new one using the same button?
Here are the variables that I'm using:
EditText dlugosc;
String haslo = "";
String pustak = "";
TextView haslo0;

And this is a code that I use to generate a password:
(znaki is the name of array)
dlugosc = findViewById(R.id.password_len);
haslo0 = findViewById(R.id.password);
String yui = dlugosc.getText().toString();
int x = Integer.parseInt(yui);
for(int i = 0; i < x; i++){
    int Index = generator.nextInt(znaki.length);
    haslo = znaki[Index] + haslo;
}

I have already tried doing an if structure:
if (haslo0 != null){
   haslo0.setText(pustak);
   haslo0.setText(haslo);
}
else
   haslo0.setText(haslo);

But it doesn't help :(
When I want to have 7 chars in the password and click the button first time, the result is correct e.g. PKAjzQL. But when I click the button second time, the result is nBzcRjQPKAjzQL instead of nBzcRjQ.

A:
How can I "delete" the old text (password) from the TextView and replace it with the new one using the same button?

The problem is not to "delete" the old text, the problem is that you have to clear the list for example, every time user clicks on the Button you clear the list doing : znaki.clear(), then it will only show the new password generated.
If you see your output :
First output :

PKAjzQL --> This is correct

Second output :

nBzcRjQPKAjzQL --> this is the new output + the old one

A: Why are you appending the old string haslo behind the newly generated one in haslo = znaki[Index] + haslo;
Probably that's why you are getting output like that. Can you please try just setting newly generated password into the textview like
haslo = znaki[Index];
And then try to set text in the text view using haslo0.setText(haslo);

A: Can you give the code of the OnClickButton? And why are you setting the same TextView with diferents Strings when you click?
 haslo0.setText(pustak);
 haslo0.setText(haslo);

?


text:
Q: google auth library node js: unpacking contents of token Some google service is sending the program an Authorisation JWT token in the header of a request. Using the Google Auth Library (https://github.com/googleapis/google-auth-library-nodejs), how can I unpack the package to retrieve a field of the token? Thanks

A: I found making a request to: https://oauth2.googleapis.com/tokeninfo?id_token= and passing the token returns the json.


text:
Q: Facebook Javascript Share UI include get variables in link I am using the facebook SDK to share a page link:
FB.ui({
        method: 'feed',
        link:  'http://freebirdevents.co.uk/test_results/?individual_result=1162',
        caption:$(this).data('message'),
}, function(response){});

However it is ignoring get parameter, I've tried URL encoding to no avail.

A:
However it is ignoring get parameter

That's because you are telling it to:
<link rel="canonical" href="http://freebirdevents.co.uk/test_results/" />

You specified here that the real URL for this piece of content is http://freebirdevents.co.uk/test_results/. Facebook follows that, and goes on to request that URL to get the relevant meta data from.
If you don't want that – then don't specify this as the canonical URL of the document.


text:
Q: How do I stop a parent DIV from stretching when I put an iFrame into it? I won't post the code directly but you can see it here: http://markbrewerton.co.uk/work.html
I have links which load an iFrame into a DIV when they are clicked, however, as you will notice, the parent DIV is stretched and goes down really far. I'm pretty new to all this, so could you explain how I can fix it?
Cheers

A: The first part is the setup the bounds of the div by using the height and width styles.
After that set the overflow style.
Overflow has different values. Auto will likely get your the desired result. http://programming.top54u.com/post/HTML-Div-Tag-Overflow-CSS-Style-Scrollbars.aspx

A: Try this (if you want scrollbars):
#yourdiv {
  height: 300px; /* fixed height */
  overflow: scroll;
}

...or this (if you want to just clip the content):
#yourdiv {
  height: 300px;
  overflow: hidden;
}

Edit: You can also fix the height of the <iframe> itself:
#youriframe {
  height: 300px;
}


text:
Q: Stretch window across two screens in windowed mode This question is specific to making one guest "screen", in windowed mode, wide enough to span two physical monitors on the host. I know how to get two guest screens in Virtualbox (easy!) or in VMware (less convenient, but doable with full screen mode).
Anyone know how to make this happen? I want to basically stretch one window to cover two monitors. The guest screen would then have a resolution like 3800x1080, and the single window which contains said guest then spans two monitors which each have 1900x1200 resolution.
Adjusting the resolution in the guest didn't do it; changing resolution manually in VMware graphics settings didn't do it; manually stretching the window just makes it automatically snap the window to cover just one host monitor.
Primary difference from VirtualBox single guest screen splits across two host monitors is that I want the guest to run in windowed mode.

A: With virtual box, you can stretch across 2 monitors with version 4.3.12. I haven't updated virtual box since then because they broke this feature.


text:
Q: Want to know how I can change the header through the tabview style property? I'm doing a project using: jsf, primefaces, css layout editing ...
I need to change the background of just one tabview without affecting all other tabviews in the project.
I know there is a property: .ui-widget-header.
If I change this property in the css file, all headers are changed.
Want to know how I can change the heater through the tabview style property?
I tried this in css, but it changes all headers:
 .ui-widget-header {
      border: 1px solid #56585C;
      background: #424548;
      color: #F9F7F7;
      font-weight: bold;
    }

My goal is to take a background from a tabView contained in another tabView without affecting the main tabView

A: Give your tabView a class:
<p:tabView styleClass="certain-tabview-class"

Use CSS descendant selector to style only tabViews with this class:
.certain-tabview-class .ui-widget-header {


text:
Q: Implicit conversion between std::filesystem::path and std::string, should it happen? The cppreference page for std::filesystem::path states:

Paths are implicitly convertible to and from std::basic_strings, which makes it possible to use them with over files APIs, e.g. as an argument to std::ifstream::open

Now the conversion to a std::filesystem::path is easy to see as it has a non-explicit constructor that takes std::string types. What I can't seem to find, though, is a way to go to a std::string implicitly.
There is a string function, but it is std::string string() const;, not operator std::string(). Using
#include <filesystem>

void foo(std::string) {}

int main()
{
    namespace fs = std::filesystem;
    fs::path p1;
    foo(p1);
}

this code compiles fine with icc, gcc, and clang, but not with MSVS, where it gives the error:
example.cpp

<source>(10): error C2664: 'void foo(std::string)': cannot convert argument 1 from 'std::filesystem::path' to 'std::string'

<source>(10): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

Compiler returned: 2

So, which compiler is right? Is there an implicit conversion sequence, or are the compilers just being helpful?

A: All compilers are right. It is specified by the standard that it should have a conversion to string_type:

operator string_type() const;

Returns: native().

string_type here is:
using string_type = basic_string<value_type>;

And native() :

const string_type& native() const noexcept;

Returns: The pathname in the native format.

Native format being basic_string<value_type>.
value_type however doesn't have to be char and thus the conversion to std::string doesn't always exist. It's only mandated that one to basic_string<>exists.

A: There is an implicit conversion to std::basic_string<value_type>, where value_type is an OS-dependent character type.
And, (§30.10.8 in my draft copy, n4659)

For POSIX-based operating systems, value_type is char  [...]
  For Windows-based operating systems, value_type is wchar_t [...]

so there doesn't need to be an implicit conversion to std::string on Windows, only to std::wstring.


text:
Q: Retrieving one property from jquery .data object I have created object:
element.data('itemAtrr', { idItem: iditem[i], itemName: names[i], divType: types[i] } );

When i do:
console.log(element.data("itemAtrr"));

Everything works  absolutely fine.
But when i try to retrieve one property like:
console.log(element.data("itemAtrr.itemName"));

or
console.log(element.data("itemAtrr[itemName]"));

it returns "UNDEFINED". What am i doing wrong? Could anyone help me?

A: You're passing the key to search for elementa on data store, there is no element with key itemAtrr.itemName or itemAtrr[itemName]. Use this instead to access object property
console.log(element.data("itemAtrr").itemName);

Notice that you first get the object using the key provided at save time. Then you access properties as you would do with any JS object. You can't do it in a single step.

A: First retrieve the object, then dial down into it:
console.log(element.data("itemAtrr").itemName);


text:
Q: How do I redirect a browser to a local file in ASP.NET? I want firefox to open C:\somefile.txt on the local drive. I've tried response.redirect with the "file:///" prefix, but it just inserts "Object moved to here." into the page. I also want to htmlencode the path because it could contain special chars...

Edit: To be clear: C:\somefile.txt is a file on the client box running the browser

A: You can't. Web pages are explicitly not allowed to link or redirect to local content. It's a security measure.

A: To be honest I don't quite know why Response.Redirect("file:///aaa") isn't working for you. Without reading the RFC, or testing it myself, I don't know.
-- Edit:
Tested myself; definitely doesn't work.
Failing someone showing you how, you can just write write a link to it, or use some (admittedly lame) javascript (to be written to the client, instead of Redirecting) like so:
<script language="javascript">document.location = "file:///aaaa";</script>


text:
Q: Meteor 'Cannot find module 'crypto' I keep getting an error saying "Cannot find module 'crypto'" I am using meteor and from my understanding, npm recently made crypto deprecated and made it built in however, my site now crashes. As a final issue, I cannot revert because I have not installed the module on my computer and it is no longer available on npmjs.org (I believe).
I have tried: updating meteor and npm, reinstalling the package, meteor reset, running an npm install.
Any ideas?


text:
Q: How to declare which methods can be applied to which objects I'm writing a server application which functionality is called via RPC. Application has objects which can interact with each other.
Assume the following simplified example:

*

*A person can inspect and fix, and can be inspected;

*A car can brake, and can be inspected and be fixed.

Straightforward implementation ¹ (RPC is out of scope):
class Car(object):
    def __init__(self, broken=False):
        self.name = 'car'
        self.broken = broken

    def breaks(self):
        self.broken = True
        print 'Car broke'

    def inspected(self, by):
        if by.pro:
            if self.broken:
                print '{}: It\'s a broken car'.format(by.name)
            else:
                print '{}: It\'s a working car'.format(by.name)
        else:
            print '{}: It\'s a car'.format(by.name)

    def fixed(self, by):
        if not self.broken:
            print 'Car is not broken'
        else:
            self.broken = False
            print by.name, 'fixed the car'

class Person(object):
    def __init__(self, name, pro=False):
        self.name = name
        self.pro = pro

    def inspect(self, target):
        target.inspected(by=self)

    def fix(self, target):
        target.fixed(by=self)

    def inspected(self, by):
        if self.pro:
            print '{}: {} is a pro'.format(by.name, self.name)
        else:
            print '{}: {} is not a pro'.format(by.name, self.name)

Create some objects:
>>> car = Car()
>>> john = Person('John', pro=True)
>>> bob = Person('Bob', pro=False)

Now user can interact with them ²:
>>> car.breaks()
'Car broke'
>>> john.inspect(car)
"John: It's a broken car"
>>> john.fix(car)
'John fixed the car'
>>> bob.inspect(john)
'Bob: John is a pro'

The problem here, if we call john.fix(bob) then we will get AttributeError: 'Person' object has no attribute 'fixed'.
So, what is a good and/or 'pythonic' way to declare/restrict which methods can be applied to which objects?
So far I came up with the following ideas:

*

*Make an bloated base (abstract) class which will have stubs for all possible methods and properties. The downside here is, as the project grows and new methods are added, it should be updated separately; and all child classes will have a lot of unrelated and unused stuff. Also, doesn't really solve the problem.

*Wrap all calls with try...except. Doesn't look stable and 'pythonic', and doesn't solve the problem.

*Manually specify which classes are supported by methods. Not maintainable as the project grows, and does not strictly tell which attributes target class must have.

*Multiple inheritance. Fixes the problem with #3 when, while creating new FixAllRobot class with fix method, we might forget to add pro attribute needed for target's checks. Cons: class Person(Inspecter, Fixer, ..., TwentyMoreOneFunctionHolder) doesn't look trustworthy and readable. And we still need to check if action can be used on target.

*Pretty much like #4, but inherit also target-side classes. Cons: Inheritance hell: class Person(Inspecter, CanBeInspected, Fixer, ...,  FortyMoreOneFunctionHolder). Pros: Looks like a solution.

Notes:

*

*About inspect and inspected (and other action pairs): There are some class dependent actions for both object and subject which must be made when action is called.

*For now all objects of the same class are stored in their class dictionary with their id as key. Meta class keeps track of what classes were created. User is usually in control of only one object. When user sends RPC request (actually json-rpc) which may look like {"jsonrpc": "2.0", "id": 77, "method": "inspect", "params": {"target": "car", "id": 1}}, target is resolved as target class and id as instance identifier. Some optional parameters might also be passed through params dict.
Sidenote: I am aware of QT signal-slot system and love it, but I think it's not the case.
Sidenote2: I'm stuck to python 2.7

A: I'd suggest going with the try...except method. EAFP ("Easier to ask for forgiveness than permission") is according to https://docs.python.org/2/glossary.html#term-eafp considered pythonic. It also scales well, as the project grows.


text:
Q: Changing text size of go Treemap for text inside sectors I have been looking to increase to the size of the text contained in a graph object Treemap, but with no success. I tried inserting HTML line breaks in the actual text but that didn't work. Maybe I am missing a simple solution. The docs have textinfo, textposition but not text size. Here is what it currently looks like: I just want the text to be readable.
enter image description here
Thank for you help!
EDIT: Here is my current code:
fig = go.Figure(go.Treemap(
ids=df_treemap['id'].tolist(),
labels=df_treemap['labels'].tolist(),
parents=df_treemap['parent'].tolist(),
values=df_treemap['value'].tolist(),
branchvalues='total',
hovertemplate='<b>%{label}',
insidetextfont=dict(size=11),
textfont=dict(size=30),
marker=dict(
    colors=df_treemap['color'],
    colorscale='RdBu',
    cmid=1,
    showscale=True),
name='',
text=summaries,

I have tried cutting the text up with the following, but that does help:
short_summaries = [textwrap.fill(df['Summary'].tolist()[0],10) if
isinstance(df, pd.DataFrame) else 'N.A' for df in x]

A: Extracted from the official docs:

textfont – Sets the font used for textinfo.

And it has a size property.


text:
Q: Domain is not working I have purchased a domain name from Godaddy. I would like to point this domain to a server EC2 instance on AWS. On my registrar's web site I specified AWS name servers which i created using Amazon Route 53. Using Route 53 I created specified DNS record (NS, A, SOA) please have a look at screenshot. I waited > 24 hours for changes to propagate but I can't access my website via my domain name.

I  have created one A record mydomain.in but still my site didn't work then i created two more A records named as www.mydomain.in and *.mydomain.in but didn't work this time as well.
Please let me know what's incorrect.
Any help would be appreciated.
Thanks in Advance.

A: Your Domain Name is still pointing to other nameservers [ns1.bodis.com, ns2.bodis.com] than the ones on your route53. you need to change that !
To do so you can refer to this tutorial
and then you can fill in the NS fields with the ones given in Route53 [ns-1825.awsdns-32.co.uk, ...]


text:
Q: PHP - function does not equal this echo? I have a question about php (wordpress) I have a plugin(buddypress) with function bp_the_profile_field_name();
when i use
echo bp_the_profile_field_name();

It's return "Tags"
But..
if (bp_the_profile_field_name() == "Tags"){
    echo "Yes, it's working";
} else {
    echo "Oh no..";
        }
?>

its return "Oh no.."
When i try equal to string "Tags" dosent't match.
Why? Please help

A: When googling to the source of the bp_the_profile_field_name function I found this source:
function bp_the_profile_field_name() {
    echo bp_get_the_profile_field_name();
}

Here we can see that the the function uses echo to show the value.

If you want to get the value to compare it with something else you'll need to use a other function which will return the value.
Below the mentioned page in the 'related' part this function is mentioned:

bp_get_the_profile_field_name

Returns the XProfile field name.

Note the _get_ insteaf off _the_
Which returns a string. Source can be found here.
So your code should become:
if (bp_get_the_profile_field_name() == "Tags"){
    echo "Yes, it's working";
} else {
    echo "Oh no..";
}

A: According to documentation (https://www.buddyboss.com/resources/reference/functions/bp_the_profile_field_name/) bp_the_profile_field_name() echoes output.
If you want to compare the output of this function you need a return, not echo.
You have 2 options:

*

*Use bp_get_the_profile_field_name() instead of bp_the_profile_field_name() in your if statement

*Edit bp_the_profile_field_name() to output the result instead of echoing it.


text:
Q: Нужно реверснуть массив из строк и при этом сохранить их длину У меня есть на входе массив строк, мне нужно их все реверснуть но самое для меня сложное, это сохранить длину каждого объекта массива
Например:
Input:  {"Don't", "worry", ",", "be", "happy", "!"}
Output: {"!yppa", "heb,y", "r", "ro", "wt'no", "D"}

Код:
public class ArrayReverser {
  public static String[] reverse(String[] a) {
    StringBuilder strBuilder = new StringBuilder();
    for (int i = 0; i < a.length; i++) {
      strBuilder.append(a[i]);
    }
    strBuilder.reverse();
    String newString = strBuilder.toString();
    int pos = 0;
    String[] b = {};
    for (int i = 0; i < a.length; i++) {
      int len = a[i].length();
      for (int j = 0; j < a.length; j++) {
        b[j] = newString.substring(pos, len);
      }
      pos = pos + len;
    }
    return b;
  }
}

A: Объединяете все слова в одну строку.
Обращаете её.
Записываете в выходной массив куски длинной строки с длинами, соответствующими длинам исходных коротких строк.
int pos = 0;
for(int i=0; i<a.length();i++) {
   int len = a[i].length();
   b[i] = Копировать из ReversedLongString с позиции pos количество символов len;
   pos += len;
}

На основе вашего последнего кода (проверить мне не на чем)
public class ArrayReverser {
  public static String[] reverse(String[] a) {
    StringBuilder strBuilder = new StringBuilder();
    for (int i = 0; i < a.length; i++) {
      strBuilder.append(a[i]);
    }
    strBuilder.reverse();
    String newString = strBuilder.toString();
    int pos = 0;
    String[] b = new String[a.length];
    for (int i = 0; i < a.length; i++) {
      int len = a[i].length();
      b[i] = newString.substring(pos, pos + len);
      pos = pos + len;
    }
    return b;
  }
}


text:
Q: Android: manage more touches in a general View In my app I want manage many touches inside the same view in this way:
I want obtain the exact number of finger that are over this view, that is, if lay a finger my total should be 1, if I lay a second finger the total should be 2, and etc. for 3,4,5... (until my device support its max number of touches).
It's ok but I want in real time also the total if I remove a finger from the screen, that is, if I layed 2 fingers over the screen ok the total is 2, but if I remove a finger the total should became 1.
I create this code but it doesn't work fine.
touch_view = (View)findViewById(R.id.touch_view);

        touch_view.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                int action = event.getAction();

                if (action == MotionEvent.ACTION_DOWN ){

                    touches++;
                    Log.i("", "touches "+ touches);
                    Log.i("", "action down");

                }
                else if (action == MotionEvent.ACTION_POINTER_DOWN){
                    touches++;
                    Log.i("", "touches "+ touches);
                    Log.i("", "pointer down");
                }
                else if (action == MotionEvent.ACTION_POINTER_UP){
                    touches--;
                    Log.i("", "touches " + touches);
                    Log.i("", "pointer up");
                }
                else if (action == MotionEvent.ACTION_UP){

                    touches--;
                    Log.i("", "touches " + touches);
                    Log.i("", "action up");
                }
                else if (action == MotionEvent.ACTION_CANCEL){

                    Log.i("", "cancel");
                }
                else if (action == MotionEvent.ACTION_HOVER_ENTER){

                    Log.i("", "action over enter");
                }
                else if (action == MotionEvent.ACTION_HOVER_EXIT){

                    Log.i("", "action over exit");
                }
                else if (action == MotionEvent.ACTION_OUTSIDE){

                    Log.i("", "action outside");
                }
                else if (action == MotionEvent.ACTION_POINTER_INDEX_MASK){

                    Log.i("", "index mask");
                }

                if (action != MotionEvent.ACTION_MOVE){
                    Log.i("","pointer count"+event.getPointerCount());
                    Log.i("","action type" +event.getAction());
                }

I notice that my count "touches" doesn't work well... and sometimes my log "event.getAction()" give me a strange number (261, 262...517,518...) what type of action are these numbers?
Can you help me?

A: My solution
touch_view.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                int action = event.getAction();

                if (action != MotionEvent.ACTION_MOVE){

                    if (action == MotionEvent.ACTION_DOWN ){

                        current_touches = 1;
                        Log.i("", "current touches " + current_touches);
                    }
                    else if (action == MotionEvent.ACTION_UP){

                        current_touches = 0;
                        Log.i("", "current touches " + current_touches);
                    }

                    else{

                        int action_code = event.getAction();

                        if (action_code%2 == 0){

                            if (current_touches != 0)
                                current_touches--;
                        }
                        else
                            current_touches++;

                        Log.i("", "current touches " + current_touches);

                    }
                }

                return true;
            }
        });


text:
Q: Python - Code snippet not working on Python 2.5.6, using IDLE I am using a piece of self-modifying code for a college project.
Here it is:
import datetime
import inspect
import re
import sys

def main():
    # print the time it is last run
    lastrun = 'Mon Jun  8 16:31:27 2009'

    print "This program was last run at ",
    print lastrun

    # read in the source code of itself
    srcfile = inspect.getsourcefile(sys.modules[__name__])
    f = open(srcfile, 'r')
    src = f.read()
    f.close()

    # modify the embedded timestamp
    timestamp = datetime.datetime.ctime(datetime.datetime.now())
    match = re.search("lastrun = '(.*)'", src)
    if match:
        src = src[:match.start(1)] + timestamp + src[match.end(1):]

    # write the source code back
    f = open(srcfile, 'w')
    f.write(src)
    f.close()

if __name__=='__main__':
    main()

Unfortunately, it doesn't work. Error returned:
# This is the script's output
This program is last run at  Mon Jun  8 16:31:27 2009
# This is the error message
Traceback (most recent call last):
  File "C:\Users\Rui Gomes\Desktop\teste.py", line 30, in <module>
    main()
  File "C:\Users\Rui Gomes\Desktop\teste.py", line 13, in main
    srcfile = inspect.getsourcefile(sys.modules[__name__])
  File "C:\Python31\lib\inspect.py", line 439, in getsourcefile
    filename = getfile(object)
  File "C:\Python31\lib\inspect.py", line 401, in getfile
    raise TypeError('{!r} is a built-in module'.format(object))
TypeError: <module '__main__' (built-in)> is a built-in module

I'd be thankful for any solutions.

A: It runs perfectly when run outside of IDLE -- so therefore the problem is not in your code alone, but in the environment where you are executing it.  When you run the erroring portion of your code in IDLE you get this output:
>>> import inspect
>>> sys.modules[__name__]
<module '__main__' from 'C:\Python26\Lib\idlelib\idle.pyw'>
>>> inspect.getsourcefile(sys.modules[__name__])
'C:\\Python26\\Lib\\idlelib\\idle.pyw'

When you run this in IDLE
# read in the source code of itself
srcfile = inspect.getsourcefile(sys.modules[__name__])
f = open(srcfile, 'r')
src = f.read()
f.close()

you are actually trying to modify 'C:\\Python26\\Lib\\idlelib\\idle.pyw' ... which IDLE will not let you do.
The long and the short of it seems to be that what you have written does work: but it cannot be run in IDLE.

A: You could use the __file__ global attribute to get the current module's source path.
From the 2.6 docs:

__file__ is the pathname of the file from which the module was loaded, if
  it was loaded from a file. The
  __file__ attribute is not present for C modules that are statically linked
  into the interpreter; for extension
  modules loaded dynamically from a
  shared library, it is the pathname of
  the shared library file.

EDIT:
I made the assumption that inspect.getsourcefile() would always throw TypeError when inspecting the __main__ module.  That's only the case when run from an interactive interpreter.  I stand corrected. Derp.


text:
Q: Sed does not exist for windows 10 64bits but? I have the following unix script :
ZECOM = /path/to/command/dothis
for FILEg in *g.F
do
echo $FILEg
FILE=`echo $FILEg | sed 's/g\./\./' | sed 's/\.F/\.f/'`
$ZECOM -someoption -f ./optionsfile.sh $FILE $FILEg somelib.so
FILEZECOM=`echo $FILE | sed 's/\.f/\.zecomextension64/'`
chmod ugo+x $FILEZECOM
done

that I want to translate into a batch script.
I came up with :
SET ZECOM = "C:\path\to\command\dothis.exe"

for %%FILEg in (*g.F) do (
    echo %%~nf
    SET FILE = `echo %%~nFILEg | sed 's/g\./\./' | sed 's/\.F/\.f/'`
    ZECOM -someoption -f %FILE% %%~nFILEg somelib.lib
    SET FILEZECOM=`echo %FILE% | sed 's/\.f/\.zecomextension64/'`
    cacls %FILEZECOM% /g everyone:f
)

but of course it doesn't work as sed is not a recognized command ... Of course, there's a 32bits gnu version of sed for windows that complains about some dll missing. So what would be my options/alternatives in this situation ?
Some background information :
The script looks, in its directory, for all files ending in "g.F", and for any such a file totog.F there is also (by construction, at the moment I want to run my script) an homologue file toto.f ; then the script executes the command acommand to which ZECOM points to : ZECOM -someoption -f %FILE% %%~nFILEg somelib.lib that is : acommand -someoption -f toto.f totog.F somelib.lib where someoption is some particular option of the command acommand and where the somelib.lib indicate that the command is to be run while linking to the library file somelib.lib.
This produces a file toto.zecomextension64. ("zecomextension64" is the extension of the produced files.) Then the cacls gives all rights to everyone, for the produced file. (These produced files will be executed and read by many different users through a same program they will all run in their own session.)
Basilly, I used sed on unix to make the string mappings "totog.F" --> "toto.f" and "toto.f" --> "toto.zecomextension64".

A: My try, the last two commands are only echoed to test output.
@Echo off & Setlocal EnableDelayedExpansion
SET "ZECOM=C:\path\to\command\dothis.exe"

for %%F in (*g.F) do (
    echo %%~nF
    SET "FILE=%%~nF"
    echo "%ZECOM%" -someoption -f "!%FILE:~0,-1!"  "!FILE!" somelib.lib
    echo cacls "!FILE:.F=.ZECOM!" /g everyone:f
)

If the output looks OK remove the echos


text:
Q: Navigating to a specific view from appdelegate using xamarin.ios and mvvmcross I am working on a cross platform app using xamarin and MVVMcross.
I want to navigate to Login page when the app is in background for a specific amount of time.
I was successfull in implementing the same in android but wasn't able to find a proper solution in ios for this where MVVMCross is used.
Below is my Android code which is working
Intent intent = new Intent(this, typeof(LoginView));
var viewModelRequest = new MvxViewModelRequest(typeof(Core.ViewModels.LoginViewModel));
                var serializer = new MvvmCross.Core.Parse.StringDictionary.MvxViewModelRequestCustomTextSerializer();
                intent.PutExtra("MvxLaunchData", serializer.SerializeObject(viewModelRequest));
                StartActivity(intent);

I need to implement the same in ios. I know I need to write a similar code like in android in WillEnterForeground method of Appdelegate but wasn't able to find  a proper solution for it anywhere.
Is WillEnterForeground the right place to do this ?
Can someone please help

A: I was able to go one step ahead
        var view = (IMvxIosView)UIStoryboard.FromName("Tasks", null).InstantiateViewController("LoginView");
        var viewController = view.CreateViewControllerFor(viewModelRequest) as UIViewController;
        Window.RootViewController = new UINavigationController(viewController);
        Window.MakeKeyAndVisible();

Now I am able to get to the login screen when the app comes in foreground again.
But when I click the Login button nothing happens.
Just for more information i am using Storyboards and have overridden CreateIosViewsContainer method of MvxIosSetup in my Setup class.
Any help please as I am relatively very new to ios development?


text:
Q: Filtering list using function values I have a list (Basis) of size $2^{21}$, and a binary function $A$ defined on it (only outputs 0 or 1). I want to filter out the items from Basis that $A$ sends to 1. I was able to find the size of the filtered list via:
Apply[A, Basis, {1}];

Total[%];

8125;

But I need the actual 8,125 vectors. I've tried a few things, including:
Select[Basis, Apply[A, [#]] == 1 &]

But this, for example, gives me

Syntax::sntxf: "Apply[A," cannot be followed by "[#]]".

What is the syntax issue, and is there a modification? If not, what would be an alternative approach?


text:
Q: Failed to resolve assembly 'Microsoft.AspNetCore.Mvc.Core, Version=3.1.0.0" when building Azure Function v3 I have an Azure Function v3.1.
On my machine (macOS + Visual Studio Mac / Jetbrains Rider), it fails to build with the following error:
Error : Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Microsoft.AspNetCore.Mvc.Core, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'

Here is the complete callstack:
##[error]C:\Users\VssAdministrator\.nuget\packages\microsoft.net.sdk.functions\3.0.9\build\Microsoft.NET.Sdk.Functions.Build.targets(32,5): Error : Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Microsoft.AspNetCore.Mvc.Core, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
   at Mono.Cecil.BaseAssemblyResolver.Resolve(AssemblyNameReference name, ReaderParameters parameters)
   at Mono.Cecil.BaseAssemblyResolver.Resolve(AssemblyNameReference name)
   at Mono.Cecil.DefaultAssemblyResolver.Resolve(AssemblyNameReference name)
   at Mono.Cecil.MetadataResolver.Resolve(TypeReference type)
   at Mono.Cecil.ModuleDefinition.Resolve(TypeReference type)
   at Mono.Cecil.TypeReference.Resolve()
   at MakeFunctionJson.AttributeExtensions.IsWebJobsAttribute(CustomAttribute attribute)
   at MakeFunctionJson.ParameterInfoExtensions.<>c.<ToFunctionJsonBindings>b__1_0(CustomAttribute a)
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.ToList()
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at MakeFunctionJson.ParameterInfoExtensions.ToFunctionJsonBindings(ParameterDefinition parameterInfo)
   at MakeFunctionJson.MethodInfoExtensions.<>c.<ToFunctionJson>b__6_1(ParameterDefinition p)
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.ToArray()
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at MakeFunctionJson.MethodInfoExtensions.ToFunctionJson(MethodDefinition method, String assemblyPath)
   at MakeFunctionJson.FunctionJsonConverter.GenerateFunctions(IEnumerable`1 types)+MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at MakeFunctionJson.FunctionJsonConverter.TryGenerateFunctionJsons()
   at MakeFunctionJson.FunctionJsonConverter.TryRun()
Error generating functions metadata

Here is the content of my csproj (I followed the recommendations regarding AspNetCore 3.1):
<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>netcoreapp3.1</TargetFramework>
        <AzureFunctionsVersion>v3</AzureFunctionsVersion>
        <LangVersion>latest</LangVersion>
        <Nullable>enable</Nullable>
        <RootNamespace>AccountManager</RootNamespace>
        <AssemblyName>AccountManager</AssemblyName>
    </PropertyGroup>
    <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
      <OutputPath>../bin\Debug\</OutputPath>
    </PropertyGroup>
    <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
      <OutputPath>../bin\Release\</OutputPath>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.0.1" />
        <PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" />
        <PackageReference Include="Microsoft.Azure.Management.Storage" Version="17.2.0" />
        <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.7" />
        <PackageReference Include="Microsoft.Extensions.Http" Version="3.1.7" />
        <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.9" />
        <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
        <PackageReference Include="NoSuchCompany.Diagnostics.Guards" Version="1.0.71" />
    </ItemGroup>
    <ItemGroup>
        <None Update="host.json">
            <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </None>
        <None Update="local.settings.json">
            <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
            <CopyToPublishDirectory>Never</CopyToPublishDirectory>
        </None>
    </ItemGroup>
    <ItemGroup>
      <ProjectReference Include="..\Core\Core.csproj" />
    </ItemGroup>
    <ItemGroup>
        <FrameworkReference Include="Microsoft.AspNetCore.App" />
    </ItemGroup>
</Project>

Question
Why is the pipeline unable to build the project?
Update 1
After cleaning the solution output and cleaning the packages folder on my machine, the build fails on my machine as well.

Update 2
It fails when it is trying to generate the Azure Functions output:
2>Target "_GenerateFunctionsPostBuild" in file "/Users/christophe/.nuget/packages/microsoft.net.sdk.functions/3.0.9/build/Microsoft.NET.Sdk.Functions.Build.targets" from project "AccountManager/src/AccountManager/AccountManager.csproj" (entry point):
       Using "GenerateFunctions" task from assembly "/Users/christophe/.nuget/packages/microsoft.net.sdk.functions/3.0.9/build/../tools/netcoreapp3.1/Microsoft.NET.Sdk.Functions.MSBuild.dll".
       Task "GenerateFunctions"
         Function generator path: '/usr/local/share/dotnet/dotnet'
         Microsoft.NET.Sdk.Functions.Generator.dll "AccountManager/src/bin/Debug/netcoreapp3.1/bin/AccountManager.dll " "AccountManager/src/bin/Debug/netcoreapp3.1/ " "False "

2>/Users/christophe/.nuget/packages/microsoft.net.sdk.functions/3.0.9/build/Microsoft.NET.Sdk.Functions.Build.targets(32,5): error : Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Microsoft.AspNetCore.Mvc.Core, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' [AccountManager/src/AccountManager/AccountManager.csproj]

If I copy the following file into the bin folder, it works:
/usr/local/share/dotnet/packs/Microsoft.AspNetCore.App.Ref/3.1.8/ref/netcoreapp3.1/Microsoft.AspNetCore.Mvc.Core.dll

A: If you added  [FromQuery]  or any other attribute to your azure function "controller signture" it could happened , at least that what happened to me...
after I removed the [FromQuery]  attribute it came back to life..
I have found this answer that nailed it : https://github.com/Azure/azure-functions-vs-build-sdk/issues/435#issuecomment-656854953


text:
Q: .NET MVC + Sensitive Data I am iterating through a List of custom data objects and outputing the data to the screen in a pageable format. Each item needs to offer the ability to edit the details (a redirect to another view) and to remove the data. In order to do this I will need to pass an id of some sort to identify the record that is going to be updated or deleted. I do not want to include this id as plain text in the route values but am at a loss for how to implement this functionality. I have two ideas but am not sure if either would be viable.

*

*Create a random key for each id each time the list is generated and store the key/id combo in sesion. I could then pass the key in the route values and grab the key when the user clicks an action. this seems like a lot of work

*Wrap the "edit" and "remove" options in a form where I can use a hidden input to pass the data via POST. This seems less that desirable however.
Is there any standarzied way to utilize sensitive data within a View / Controller relationship when I am working with more than one item on a page?

A: Just encrypt the sensitive data before it gets to the view. And send up the encrypted value and decrypt at the controller. Example:
public ActionResult RenderPage()
{
   CustomerInformation customerInformation = CustomerInformation.GetCurrentCustomer();
   customerInformation.SocialSecurityNumber = MyNamespace.Utilities.Encrypt(customerInformation.SocialSecurityNumber);
   return View(customerInformation);
}

and in the response you could do this.
public ActionResult SubmitData(CustomerInformation customerInformation)
{
   customerInformation.SocialSecurityNumber = MyNamespace.Utilities.Decrypt(customerInformation.SocialSecurityNumber);
   return View();
}

As you can see the data is encrypted before it goes out, and on the way back it gets decrypted again. Of course you can also use HTTPS and that should be really secure as well.


text:
Q: Dynamic window creation at runtime using ncurses Not sure if this is even possible with ncurses. All documentation and examples show that the creation of multiple windows is known at compile time.
I would like to do something like this.
 #include <ncurses.h>

WINDOW *create_newwin(int height, int width, int starty, int startx);
void star(int x,int y,int r);
 void newbox(int x,int y,int r);

int main(int argc, char *argv[])
{
    int startx, starty, width, height;
    int ch,sze;

    initscr();                      /* Start curses mode            */
    cbreak();                       /* Line buffering disabled, Pass on
                                     * everty thing to me           */
    //printf("%s\n",argv[1]);
    sze = atoi(argv[1]);
    starty = (LINES - sze) / 2;  /* Calculating for a center placement */
    startx = (COLS - sze) / 2;    /* of the window                */

    refresh();
    star(startx,starty,sze);

    endwin();                       /* End curses mode                */
    return 0;
}

WINDOW *create_newwin(int height, int width, int starty, int startx)
{       WINDOW *local_win;

    local_win = newwin(height, width, starty, startx);
    box(local_win, 0 , 0);          /* 0, 0 gives default characters
                                     * for the vertical and horizontal
                                     * lines                        */
    wrefresh(local_win);            /* Show that box                */

    return local_win;
}

void star(int x,int y,int r)
{
if(r>0)
{
star(x-r,y+r,r/2);
star(x+r,y+r,r/2);
star(x-r,y-r,r/2);
star(x+r,y-r,r/2);
 newbox(x,y,r);
 }
}

void newbox(int x,int y,int r)
 {
  WINDOW *mywin;
   mywin = create_newwin(2*r, 2*r, y, x);
 }

I would think that you would use the new keyword and malloc. My desired goal is to produce a type of fractal display with overlapping windows.The function star is a recursive one that will create the parameters to pass to the newbox function. Anyone out there used ncurses to create windows at runtime?

A: The (n)curses function newwin allocates space for a WINDOW structure and returns that.  The stdscr and curscr windows likewise are allocated in initscr or newterm (using newwin).  The main difference between stdscr and curscr versus other windows is that these are used throughout the library in a predefined manner, and cannot be freed.  The other windows can be freed using delwin.  None of that is "static".
The corresponding manual pages have this basic information.
The ncurses example programs show how windows can be created which are not explicit in the code, e.g., prompting for the user to move the cursor to begin creating a window, then moving to select the end (top-left versus bottom-right, in menu item g below).  Likewise, several use recursion, e.g., to draw a series of nested, boxed windows (menu item a or A below, used to test resizeterm).  Those are both done in the main test-program, whose menu is shown here:
Welcome to ncurses 5.9.20150502.  Press ? for help.
This is the ncurses main menu
a = keyboard and mouse input test
A = wide-character keyboard and mouse input test
b = character attribute test
B = wide-character attribute test
c = color test pattern
C = color test pattern using wide-character calls
d = edit RGB color values
e = exercise soft keys
E = exercise soft keys using wide-characters
f = display ACS characters
F = display Wide-ACS characters
g = display windows and scrolling
i = test of flushinp()
k = display character attributes
m = menu code test
o = exercise panels library
O = exercise panels with wide-characters
p = exercise pad features
q = quit
r = exercise forms code
s = overlapping-refresh test
t = set trace level
? = repeat this command summary
>


text:
Q: How can I increase the final integer variable? Eclipse is offering final but I can't increase the i variable.
@Override
public void onClick(View v) {
    final TextView tv = (TextView) findViewById(R.id.tvSayac);

    int i = 1;
    do {
        try {
            new Thread(new Runnable() {
                public void run() {
                    tv.post(new Runnable() {
                        public void run() {
                            tv.setText(Integer.toString(i));
                        }
                    });
                }
            });
            i++;
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } while (i < 16);
}

A: A final is an entity that can not be changed after it is initialized.
Final (Java)
What you could do is create a variable within the scope of the do/while loop that is final with the value of i and send that into the function.

A: The easiest solution here is to create a class:
public class FinalCounter {

    private int val;

    public FinalCounter(int intialVal) {
        val=intialVal;
    }
    public void increment(){
        val++;
    }
    public void decrement(){
        val--;
    }
    public int getVal(){
        return val;
    }

    public static void main(String[] arg){
        final FinalCounter test = new FinalCounter(0);
        test.increment(); // 1
        test.increment(); // 2
        test.increment(); // 3
        test.increment(); // 4
        test.increment(); // 5
        test.decrement(); // 4
        System.out.println(test.getVal());  // prints 4
    }
}

A: I think it is possible to create a local copy of the variable i. Try this:
@Override
public void onClick(View v) {
    final TextView tv = (TextView) findViewById(R.id.tvSayac);

    int i = 1;
    do {
        final int localCopy = i; // Create here a final copy of i
        try {
            new Thread(new Runnable() {

                public void run() {
                    tv.post(new Runnable() {
                        public void run() {
                            // use here the copy
                            tv.setText(Integer.toString(localCopy));
                        }
                    });
                }
            }).start(); // Don't forget to start the Thread!
            i++;
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } while (i < 16);
}

By creating a final local copy:

*

*the compiler won't complain anymore

*because of Java copies by value, you will only increase i and not localCopy.

I suppose you want to start the Thread as well...
EDIT: Indeed, you were right. You have to create the local final copy inside the loop. Check the new code.

A: A final variable can only be initialized once not necessarily when you are  defining it. It can be set any time within the constructor , but only once. In your case when you are incrementing i using i++, you are trying to assign the incremented value to i again which is not allowed.

A: You could create a counter class like that and increment it. This way, the reference of the Counter object could be final but you could still set its value ?

A: What I did was add a:
private int i;

Before this:
@Override
public void onClick(View v) {
    final TextView tv = (TextView) findViewById(R.id.tvSayac);

    i = 1;
    do {
        try {
            new Thread(new Runnable() {
                public void run() {
                    tv.post(new Runnable() {
                        public void run() {
                            tv.setText(Integer.toString(i));
                        }
                    });
                }
            });
            i++;
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } while (i < 16);
}

And you'll be able to use your variable as usual after that, without having to mark it as final.


text:
Q: Inner Shadow Effect for line drawn to screen? I've made an iOS program that allows the user to draw a line on the screen with their finger. I used the touchesBegan, touchesMoved, and touchesEnded methods, along with creating a CGContext and drawing my line that way. I want the line to look as though it is beveled into the screen, almost as if it was carved. How would this be possible?

A: You can achieve a simple bevel by stroking your lines three times:

*

*first, with a color brighter than the background at points p(x-1, y-1) relative to the actual line

*then, your line color at the actual line position, points p(x, y)

*then, brighter than the line color, but darker than the background at p(x+1, y+1)

You can think of this as a light shining onto your lines from above and to the left, making the lower coordinates brighter, passing over the bevel and having a little shadow cast on the higher coordinates.
Once you get the hang of thinking through the pseudo-3D geometry this way, you can create prettier bevels, including details inside the line.  Those will take more strokes.


text:
Q: If Statement on Date submit would need help on the statement below:
its a form submission for date and its not a mandatory field.
how can i submit without any value ?
because currently i can't submit the form without value in date field.
Thank you
function ABC_StringIsDateFormatddMMyyyy(str) {
    if (str.length != 8) {
        return false;
    }
    var strYear = str.substring(4, 8);
    var strMonth = str.substring(2, 4);
    var strDay = str.substring(0, 2);
    if (isNaN(strYear)) {
        return false;
    }
    if (isNaN(strMonth)) {
        return false;
    }
    if (isNaN(strDay)) {
        return false;
    }

    var d = new Date();
    d.setFullYear(strYear, parseInt(strMonth) - 1, strDay);
    strYear = d.getFullYear();
    strMonth = d.getMonth() + 1;
    strMonth = "00" + strMonth;
    strMonth = strMonth.substring(strMonth.length - 2, strMonth.length);
    strDay = d.getDate();
    strDay = "00" + strDay;
    strDay = strDay.substring(strDay.length - 2, strDay.length);
    var tmp = strDay + strMonth + strYear;
    if (str != tmp) {
        return false;
    }
    return true;
}

A: Return true if the field is empty.
function ABC_StringIsDateFormatddMMyyyy(str) {
    if (str.length == 0) {
        return true;
    }
    if (str.length != 8) {
        return false;
    }
    var strYear = str.substring(4, 8);
    var strMonth = str.substring(2, 4);
    var strDay = str.substring(0, 2);
    if (isNaN(strYear)) {
        return false;
    }
    if (isNaN(strMonth)) {
        return false;
    }
    if (isNaN(strDay)) {
        return false;
    }

    var d = new Date();
    d.setFullYear(strYear, parseInt(strMonth) - 1, strDay);
    strYear = d.getFullYear();
    strMonth = d.getMonth() + 1;
    strMonth = "00" + strMonth;
    strMonth = strMonth.substring(strMonth.length - 2, strMonth.length);
    strDay = d.getDate();
    strDay = "00" + strDay;
    strDay = strDay.substring(strDay.length - 2, strDay.length);
    var tmp = strDay + strMonth + strYear;
    if (str != tmp) {
        return false;
    }
    return true;
}


text:
Q: Setting locations latitude & longitude in facing direction How do you clone your own Location, and then add some extra metres towards a desired direction?
Right now my android app can get the azimut, and my GPS location, and I hardcoded the desired distanct for an example, 10 metres.
Then my app should create a new Location, exactly 10 metres ahead where im facing.
So if my position is: longitude 17.537200603552526, latitude 25.70358496181195
and i want to it to move 8 metres directly towards north, and 2 metres directly towards east.
Would the new longitude and latitude look like:
current longitude + 0.00008 , current latitude + 0.00002
Heres some of my code to calculate the gradient and the new location:
public double[] calculateXYLength(double[] vals, double distance)
{
    double x = vals[0];
    double y = vals[1];

    if (vals[0] < 0)
        {
            x = x * -1;
        }
    if (vals[1] < 0)
        {
            y = y * -1;
        }
    // Log.d("lengths", "K = " + distance + " / (" + x + " + " + y + " )" );
    double k = distance / (x + y);

    // Log.d("lengths", "vals[0]: " + vals[0] + "  vals[1]: " + vals[1]);
    // Log.d("lengths", "x: " + (vals[0] * k) + "  y: " + (vals[1] * k) +
    // "  k: " + k);
    return new double[] { (vals[0] * k), (vals[1] * k) };
}

Notice the vals is the gradient i already calculated, and the result i'm returning i'm going to use to add to my new location point.
    Location newPosition = currentPosition
    newPosition.setLongitude(myPosition.getLongitude() + val[0]);
    newPosition.setLatitude(myPosition.getLatitude() + val[1]);

But the thing is, I don't get the desired distance between these two locations.. And I can't figure out why. How do I add the desired distance on the latitude/longitude?
Thanks,
Johan

A: The measures of longitude and latitude are degrees not meters, I think that is the problem.
1 degree = 111.12 km


text:
Q: Hazard function of $\min(X_1, X_2)$ Suppose I have two random variables, $X_1$ and $X_2$, that are independent (but not identically distributed) and assume both have hazard functions $\lambda_1(s)$ and $\lambda_2(s)$, for $s > 0$. Then how can I derive the hazard function of $\min(X_1, X_2)$?
EDIT: The following is how I define the hazard function (instantaneous rate of mortality):
Let $S$ denote the lifetime of an object, then define $\theta_s(t) = P(S>s+t | S>s)$. Then the hazard function, $\lambda(s)$ is defined as:
$\displaystyle \lambda(s) = \lim_{t \rightarrow 0} -\frac{\theta_s(t) - \theta_s(0)}{t} = -\theta_s'(0)$
EDIT 2: My solution:
Let $Y = \min\left(X_1, X_2\right)$. We need to find the hazard function for $Y$, which we denote as $\lambda_Y(s)$. We have,
\begin{align*}
\lambda_Y(s) = \frac{f_Y(s)}{1-F_Y(s)}
\end{align*}
where $f_Y(s)$ and $F_Y(s)$ denote the probability density function and cumulative distribution function of $Y$, respectively. Note that,
\begin{align*}
F_Y(s) & = P\left(Y \le s\right) \\
& = 1-P(Y>s) \\
& = 1-P\left(\min\left(X_1, X_2\right) > s\right) \\
& = 1 - P\left(X_1 > s, X_2 > s\right) \\
& = 1-P(X_1>s)P(X_2>s) \ \ \ \ \text{Due to the independence between} \ X_1 \ \text{and} \ X_2 \\
& = 1-\left[1-P(X_1 \le s) \right]\left[1-P(X_2 \le s) \right] \\
& = 1-\left[1-F_{X_1}(s) \right]\left[1-F_{X_2}(s) \right]
\end{align*}
where $F_{X_1}(s)$ and $F_{X_2}(s)$ denote the cumulative distribution functions of $X_1$ and $X_2$, respectively. Hence,
\begin{align*}
1-F_Y(s) & = 1-\left(1-\left[1-F_{X_1}(s) \right]\left[1-F_{X_2}(s) \right] \right) \\
& = \left[1-F_{X_1}(s) \right]\left[1-F_{X_2}(s) \right]
\end{align*}
We also have,
\begin{align*}
f_Y(s) & = \frac{d}{dy} F_Y(s) \\
& = F_{X_1}'(s)\left[1-F_{X_2}(s) \right]+F_{X_2}'(s)\left[1-F_{X_1}(s)\right] \\
& = f_{X_1}(s) \left[1-F_{X_2}(s) \right]  + f_{X_2}(s)\left[1-F_{X_1}(s)\right]
\end{align*}
where $f_{X_1}(s)$ and $f_{X_2}(s)$ denote the probability density function $X_1$ and $X_2$, respectively. Putting everything together yields,
\begin{align*}
\lambda_Y(s) & = \frac{f_{X_1}(s) \left[1-F_{X_2}(s) \right]  + f_{X_2}(s)\left[1-F_{X_1}(s)\right]}{ \left[1-F_{X_1}(s) \right]\left[1-F_{X_2}(s) \right]} \\
& = \frac{f_{X_1}(s)}{1-F_{X_1}(s)} + \frac{f_{X_2}(s)}{1-F_{X_2}(s)} \\
& = \lambda_1(s) + \lambda_2(s)
\end{align*}

A: Hint: The hazard function of an absolutely continuous random variable $Z$ can be obtained by
$$
\lambda_Z(t)=-\frac{\mathrm d}{\mathrm d t}\log S_Z(t),
$$
where $S_Z(t)=P(Z>t)$ denotes the survivor function.

A: Answer:
I have given the answer for n random variables which can be simplified to two.
$$F_{min}(x) = P(X_{min} \leq x)$$ $$= 1- P(X_{min} > x)$$$$= 1-P(X_1 > x; X_2 > x;\cdots X_n > x)$$
$$= 1 - [1 - F_1(x)][1 - F_2(x)]\cdots[1 - F_n(x)]$$
For x > 0,$$ F_{i}(x) = 1 - e^{-\lambda x}$$
$$ 1- F_{i}(x) = e^{-\lambda x}$$
$$F_{max}(x) = F_{1}x.F_{2}x.F_{3}x.\cdots F_{n}x$$
Hazard function $= \frac{P(x)}{1-F(x)}$.(probability function/survival fuction)  For this to be minimum, we need to have $F_{min}(x)$.  Do the calculation appropriately.
Thanks
Satish


text:
Q: What are the generators for $\mathbb{Z}_p^*$ with p a safe prime? lets consider $\mathbb{Z}_p^*$ with $p = 2 \cdot q + 1$ a safe prime ($p$ and $q$ have to be prime).
Then $\varphi\left(p\right) = 2 \cdot q$ is the order of  $\mathbb{Z}_p^*$, and $\varphi\left(\varphi\left(p\right)\right) = q-1$ the number of generators in  $\mathbb{Z}_p^*$.
Also there are exactly $\frac{p-1}{2} = q$ quadratic residue and $q$ non quadratic residue in $\mathbb{Z}_p^*$.
Now my question:
Is every non quadratic residue (except $-1$ if it is a nqr) a generator of $\mathbb{Z}_p^*$? (due to the fact, that we have $q-1$ generators and quadratic residues cannot be generators)
An affirmation or compelling arguments, why I am wrong, are very appreciated, thanks!

A: Indeed that is true, your counting argument does it.  Since $p\equiv 3\pmod{4}$, we have that $-1$ is a non-residue.  It is the only non-residue which is not a primitive root of $p$.