Error when writing to report file after successful test execution

Question: I've tried to set up HTML reporting in nightwatch by adding handlebars etc but after I do all that when I try to run a test the test runs but I get the following error message and the report is never created:

Error: An error occurred while trying to save the report file:
Error: The reporter module must have a public ".write()" method defined.
    at C:\Users\Beller\automation\node_modules\nightwatch\lib\reporter\global-reporter.js:130:15
    at async GlobalReporter.writeReportToFile
(C:\Users\Beller\automation\node_modules\nightwatch\lib\reporter\global-reporter.js:141:24)
    at async Promise.all (index 1) at async DefaultRunner.reportResults
(C:\Users\Beller\automation\node_modules\nightwatch\lib\runner\test-runners\default.js:119:7)
    at async DefaultRunner.run
(C:\Users\Beller\automation\node_modules\nightwatch\lib\runner\test-runners\default.js:140:7).
Error: The reporter module must have a public ".write()" method
defined.
    at async Promise.all (index 1)
    at async Promise.all (index 1)

not sure what I need to do here…. any help would be greatly appreciated
Not sure how to fix this.  Has anyone else seen an issue similar?
Answer: HI I think I may have solved this now? Try the below which needs to be in your global.js file.
<code>    var HtmlReporter = require('nightwatch-html-reporter');
var reporter = new HtmlReporter

module.exports = {
    before: function (done) {
        chromedriver.start();
        done();
    },

    after: function (done) {
        chromedriver.stop();
        done();
    }
};

({
    openBrowser: true,
    reportsDirectory: __dirname + '/reports'
});
module.exports = {
    reporter: reporter.fn
};
</code>


Where does the football teams play home matches during the Rugby World Cup?

Question: Where does football teams play their home matches when the stadiums are involved in Rugby World Cup 2015 matches?
Apart from Twichenam it seems that other stadiums are used for Premier League's football matches, so how is it possible to play together those sports?
Answer: Don Biglia's comment is pretty much spot on - the soccer team just plays somewhere else, or not at all, when the stadium is in use for the Rugby World Cup. To take a couple of examples:

Villa Park was used for rugby matches on the 26th and 27th September. Aston Villa played away at Liverpool on the 26th September.
City of Manchester Stadium will be used for a rugby match on 10th October. Manchester City don't play at all that weekend.

Almost every major soccer ground is a multi-use venue one way or another, so this isn't a new problem for the teams - for example, Old Trafford is hosting the Super League (rugby league) Grand Final on 10th October, which is not really any different from hosting a union match.
Comment: The premier league grounds are available as it's an international weekend and there are no premier league fixtures 10/10
Answer: Hi Having just spent 10 days volunteering at Milton Keynes stadium rugby world Cup has an exclusive use agreement with the stadia for a period.   MK dons played Derby at home on the 26th September the next home game should have been this weekend giving us plenty of time to setup for the matches and return to football.   This has been done at all stadia used.


Printing pattern sequence of 3 characters

Question: I would like to print pattern of 3 characters using PHP. Like aaa, aab, aac .... zzz.
Now, I am using these PHP code but it is printing randomly instead sequence.
<code>$i = 1;
$chars = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");

while($i > 0){ $current = $chars[rand(0,25)].$chars[rand(0,25)].$chars[rand(0,25)]; }
</code>
Answer: Quick but sloppy
<code>$i=0;
$j=0;
$k=0;
while($i<26){
  while($j<26){
    while($k<26){
      echo $chars[$i] . $chars[$j] . $chars[$k];
      $k++;
    }
    $j++;
    $k=0;
  }
  $i++;
  $j=0;
  $k=0;
}
</code>
Comment: Parse error: syntax error, unexpected '[', expecting ',' or ';' in C:\xampp\htdocs\start\test2.php on line 12
Comment: But when i replace "echo chars[$i] . chars[$j] . chars[$k];" with "echo "hi ";" Then printing hi.
Comment: @RinkuYadav ok try that then, see if that fixes anything:
echo "chars[$i] chars[$j] chars[$k] ";
Comment: @RinkuYadav oops just realized it, forgot the '$' in front of the chars
Comment: Yes it's printing right sequence of array but when i use echo chars[$i] . chars[$j] . chars[$k]; then it display error Parse error: syntax error, unexpected '[', expecting ',' or ';' in. can i print characters instead array ?
Comment: @RinkuYadav I updated my answer you need the '$' in front of the variable: echo $chars[$i] . $chars[$j] . $chars[$k];
Comment: @RinkuYadav copy and paste my new answer see if it gives you error, you keep showing me my old answer
Comment: Yeah, i was also forget $ before variable. Thank you so much.
Answer: Count from 0 to 26^3 -1. Then convert your numbers to base 26 , replace numbers by letters as needed, and prefix with "a" or "aa" if the converted result is single or double digit.
Use this function: string base_convert ( string $number , int $frombase , int $tobase )
I am not going to code it all out for you. You need to learn from it.
Answer: I got it in c#.
<code>        string sample = "AAA";
        char[] chars = sample.ToCharArray();

        char first = chars[0];
        char second = chars[1];
        char third = chars[2];

        if (first == second && first == third)
        {
            third++;
            bool isAlphaBet = Regex.IsMatch(third.ToString(), "[a-z]", RegexOptions.IgnoreCase);
            if (isAlphaBet)
            {
                return $"{first}{second}{third}";
            }
            return $"empty";
        }
        if (first == second && first != third)
        {
            third++;
            bool isAlphaBet = Regex.IsMatch(third.ToString(), "[a-z]", RegexOptions.IgnoreCase);
            if (isAlphaBet)
            {
                return $"{first}{second}{third}";
            }
            else
            {
                second++;
                third = 'A';

                return $"{first}{second}{third}";
            }
        }//"ABA";
        if (first != second && first == third)
        {
            third++;

            bool isAlphaBet = Regex.IsMatch(third.ToString(), "[a-z]", RegexOptions.IgnoreCase);
            if (isAlphaBet)
            {
                return $"{first}{second}{third}";
            }
            else
            {
                second++;
                third = 'A';

                return $"{first}{second}{third}";
            }

        }
        if (first != second && first != third && second != third)
        {
            third++;

            bool isAlphaBet = Regex.IsMatch(third.ToString(), "[a-z]", RegexOptions.IgnoreCase);
            if (isAlphaBet)
            {
                return $"{first}{second}{third}";
            }
            else
            {
                second++;
                third = 'A';
                bool isAlphaBetSecond = Regex.IsMatch(second.ToString(), "[a-z]", RegexOptions.IgnoreCase);
                if (isAlphaBetSecond)
                {
                    return $"{first}{second}{third}";
                }
                else
                {
                    second = 'A';
                    first++;
                    bool isAlphaBetFirst = Regex.IsMatch(first.ToString(), "[a-z]", RegexOptions.IgnoreCase);
                    if (isAlphaBetFirst)
                    {
                        return $"{first}{second}{third}";
                    }
                    else
                    {
                        return $"empty";
                    }
                }

            }

        }
        if (first != second && second == third)
        {
            third++;
            bool isAlphaBetThird = Regex.IsMatch(third.ToString(), "[a-z]", RegexOptions.IgnoreCase);
            if (isAlphaBetThird)
            {
                return $"{first}{second}{third}";
            }
            else
            {
                third = 'A';
                second++;
                bool isAlphaBetSecond = Regex.IsMatch(second.ToString(), "[a-z]", RegexOptions.IgnoreCase);
                if (isAlphaBetSecond)
                {
                    return $"{first}{second}{third}";
                }
                else
                {
                    second = 'A';
                    first++;
                    bool isAlphaBetFirst = Regex.IsMatch(first.ToString(), "[a-z]", RegexOptions.IgnoreCase);
                    if (isAlphaBetFirst)
                    {
                        return $"{first}{second}{third}";
                    }
                    else
                    {
                        return $"empty";
                    }
                }
            }
        }

        return $"{first}{second}{third}";
</code>
Answer: If you need to print random - like 'aaa' or 'vvv' or 'ddd' - try to use
<code>$char = $chars[rand(0,25)];
echo $current = $char.$char.$char;
</code>
If you want to print 'aaa','bbb','ccc',...- use
<code>for ($i = 0; $i < 26; $i++) {
    $char = $chars[$i];
    echo $current = $char.$char.$char;
}
</code>
Comment: I need sequence instead random. please read question once again.


Using filter instead of foreach

Question: I am currently trying to execute some operations after retrieving some data, the format I am trying to achieve is an array of strings:
let cleanedData = ['foo', 'bar']
The data I receive could either be an array of objects or an array of arrays that could have empty arrays that needs to be filtered out. So for example I can receive either: let notCleanedData = [['foo'],[],[],['bar']] or this let notCleanedData = [{var: 'foo'}, {var: 'bar'}]
This is my code, it is working but I would like to improve it in a cleaner way or with ES6+ methods I have tried to use a filter function without success, any advice?

function filterInputData(notCleanedData) {
  let cleanedInputData = [];
  notCleanedData.forEach(input => {
    if (input.length > 0) {
      cleanedInputData.push(input)
    }
    if (input.var) {
      cleanedInputData.push(input.var)
    }
  });
  return cleanedInputData;
}

console.log(
  filterInputData([['foo'],[],[],['bar']])
)
console.log(
  filterInputData([{var: 'foo'}, {var: 'bar'}])
)
Comment: [codereview.se] is a more appropriate place to ask for improvements to working code.
Comment: I am not sure this is exactly working as intended.  When I ran this with the array version of the data, I got "[ [ 'foo' ], [ 'bar' ] ]", not "[ 'foo', 'bar' ]".  Would that then make this the right place to ask?
Answer: This is a simple one-line solution that comes to my mind without using any libraries:
const clean = (data) => data.map(item => item.var ||  item[0]).filter(item => item)

I tried it on the test inputs you provided:

const clean = (data) => data.map(item => item.var ||  item[0]).filter(item => item)

console.log(
  clean([['foo'],[],[],['bar']])
)
console.log(
  clean([{var: 'foo'}, {var: 'bar'}])
)
Comment: So smooth, thanks, I came up with the same solution but more verbose. Does ```item=>item``` filter empty items, right?
Comment: @FilippoRivolta yes it filters out the undefined items from empty arrays.
Answer: const input = [['foo'],[],[],['bar']]
const input2 = [{var: 'foo'}, {var: 'bar'}]

const clean = (data) => data && data[0].length // check type
    ? data.flat(1) // use new flat method if array
    : (data || []).map((e) => e.var) // map objects otherwise

Answer: In this situation you can use map to achieve what you want without foreach. Filter wont work since it can only remove elements from the list and not actually make any modifications to them.
function filterInputData(notCleanedData) {
    let cleanedInputData = notCleanedData.map((input) => {
        if (input.length > 0) {
            return input;
        }
        if (input.var) {
            return input.var;
        }
    }).filter(item => item !== undefined);
    return cleanedInputData;
}

Comment: What does your notCleanedData look like?  When I ran your answer with his input (notCleanedData = [['foo'],[],[],['bar']]), I got: [ [ 'foo' ], undefined, undefined, [ 'bar' ] ]
Comment: Ah my bad, didn't notice that not adding the item was an option. I've updated my answer.
Answer: Here is a much cleaner approach using reduce:-
// This function assumes that the array inside the array has single value and the object inside array has only one key called var
function filterInputData(notCleanedData) {
    return notCleanedData.reduce((acc, item) => {
        if (item.length) acc.push(item[0]);
        if (item.var) acc.push(item.var);
        return acc;
    }, [])
}

Hope you find this useful.
Answer: I'd bring in lodash to help here.
You can use flattenDeep to clean and flatten and map to test if the data includes objects.
Example:

function clean(data) {
   return
     _.chain(data)
       .flattenDeep()
       .map(x => {
       if (x.var) {
            return x.var;
          }

          return x;
       })
      .value();
}

console.log(
  clean([['foo'],[],[],['bar']])
)
console.log(
  clean([{var: 'foo'}, {var: 'bar'}])
)

Using filter instead of foreach


IIS7 Compression CSS files only compressed when dynamic compression is enabled

Question: If anyone can help it would be appreciated. I would like to enable compression for static files within IIS7 (for the sake of simplicity I'll just refer to static css files for the time being).
The problem I'm getting is that  css files are only compressed when both dynamic and static compression is enabled in IIS for the website. What I really want to achieve is css compression (static file) whilst leaving the dynamic (aspx) pages as uncompressed for the time being (to avoid unnecessary CPU load).
I am puzzled as to why just leaving 'static compression' enabled causes css files to be returned uncompressed.
My applicationHost.config file has not be altered and looks like this:
<code>        <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
        <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
        <staticTypes>
            <add mimeType="text/*" enabled="true" />
            <add mimeType="message/*" enabled="true" />
            <add mimeType="application/javascript" enabled="true" />
            <add mimeType="*/*" enabled="false" />
        </staticTypes>
        <dynamicTypes>
            <add mimeType="text/*" enabled="true" />
            <add mimeType="message/*" enabled="true" />
            <add mimeType="application/x-javascript" enabled="true" />
            <add mimeType="*/*" enabled="false" />
        </dynamicTypes>
    </httpCompression>
</code>
The server-wide compression setting within IIS is set to 'Dynamic Disabled' and 'Static Enabled' from the Server > Features > Compression page.
The web-site compression setting (Server > Sites > MyWebsite > Features > Compression) is where I am enabling and disabling dynamic compression as detailed above.
Any help would be really help me get unstuck on this.
Thanks
Comment: Same issue here.
Answer: Chances are, your CSS file is being served by a dynamic content handler, which means it's considered dynamic content by IIS. If .CSS files are mapped directly to the StaticFileHandler, they'll probably be compressed along with other static content, as long as the mime-type is correct.
To work out whether that's the case:
Turn on Failed Request Tracing for the site, and enable a rule that traces on 200 responses.
Open the failed request log file corresponding with a .CSS request, and check to see which handlers are being invoked to produce the file, and whether compression was regarded as being required. Wildcard script mappings are often the cause of this type of behaviour.
If you don't score more than frequentHitThreshold requests in frequentHitTimePeriod (typically 2 in 10 seconds, if memory serves), the content may not be compressed until breaking that threshold - the same threshold is used for compression as caching.


VB.NET Manipulando um "Birthday Drop Down"

Question: Olá, pessoal!
Estou com dificuldades em definir uma data em um DropDown do site do Yahoo...
O link do site é: https://na.edit.yahoo.com/registration?.pd=&intl=br
Aqui o que estou tentando, mas não funciona... não sei porquê...
WebBrowser1.Document.GetElementById("month").SetAttribute("value", "01")
WebBrowser1.Document.GetElementById("day").SetAttribute("value", "04")
WebBrowser1.Document.GetElementById("year").SetAttribute("value", "1990")

Se alguém puder me dar uma força... Já tentei muitas coisas, mas esse foi o mais próximo do certo que cheguei kkkk
Enfim... Agradeço desde já!
Answer: Seria por que o elemento day não tem nenhuma propriedade chamada "value"?

Isso deve ser sincronizado com uma database interna lá nos servidores deles, não achei a propriedade value em nenhum dos três elementos.
Comment: Quais você acha que são minhas opções? Preciso definir esse campo das datas pelo programa...
Comment: Não sei se seria possível, poderia estudar usar Handlers para quando o usuário selecionar a caixa enviar um sinal e selecionar um valor. Eu que o `SendKeys.Send()` não funciona, tem que ser com o mouse, mas não sei fazer.


Drupal 8 - taxonomy term field without "title" attribute

Question: I have a simple view block with exposed the taxonomy term linked to the taxonomy page, but I have noticed that the attribute is missing, I tried to rewrite the term but every attempt went wrong.
What I need is simple, this is the view generated field:
Events

I want to add title="Events", like this:
Events

But I can't find any solutions in Drupal 8 view!
Comment: I'm not sure why you're adding the title attribute, but I don't think the example you've given is the intended way to use for it.
Comment: Hi sonfd, I want to add the title for accessibility, a requirement that WCAG requires.
https://www.w3.org/TR/WCAG20-TECHS/H33.html
Comment: Is your TITLE coming from VIEW or Its the default taxonomy page with TITLE?
Comment: From the page you linked to "Because of the extensive user agent limitations in supporting access to the title attribute, authors should use caution in applying this technique. For this reason, it is preferred that the author use technique C7: Using CSS to hide a portion of the link text (CSS) or H30: Providing link text that describes the purpose of a link for anchor elements."
Comment: Hi Ajay Reddy, the title i coming from VIEW, view generated field!
Comment: sonfd ok, but i want the title="XXX", then I'll put a description, the one above is just an example!
Answer: You should be able to use template_preprocess_views_view_field to accomplish this. Create that hook in your custom theme like:
/**
 * Alter field_MY_TAX_FIELD link to add title attribute.
 *
 * Implements template_preprocess_views_view_field().
 */
function MY_THEME_preprocess_views_view_field(&$vars) {
  if ($vars['field']->field == 'field_MY_TAX_FIELD') {
    // Add title attribute to link.
  }
}

Alternatively you could create a new field formatter that extends Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceLabelFormatter. Override the viewElements method. First call $elements = parent::viewElements($items, $langcode);, then traverse $elements and add your title attribute when appropriate. After you create the formatter, clear cache and then go back to your view and select your new formatter as formatter for the taxonomy field.


Como escolher (dependendo do login) qual master page executar?

Question: Queria algo parecido com isto (esta não funciona).
Erro "A propriedade 'MasterPageFile' só pode ser definida no ou antes do evento 'Page_PreInit'."
foreach (DataRow item in dt.Rows)
            {
                if (item["tipoLogin"].ToString().Contains("admin"))
                {

                    MasterPageFile = "~/MasterPage.master";
                    Response.Redirect("HomeAdmin.aspx");
                }
                else
                {
                    if (item["tipoLogin"].ToString().Contains("gestor"))
                    {
                        MasterPageFile = "~/MasterGestor.master";
                        Response.Redirect("HomeGestor.aspx");
                    }
                    else
                    {
                        if (item["tipoLogin"].ToString().Contains("responsavel"))
                        {
                            MasterPageFile = "~/MasterPageResponsavel.master";
                            Response.Redirect("HomeResponsavel.aspx");
                        }
                    }
                }

            }

Obrigado
Answer: Como o erro diz, para informar qual MasterPage usar, use o evento Page_PreInit
protected void Page_PreInit(object sender, EventArgs e)
{
    //Sua Logica Aqui
    this.MasterPageFile = "~/SuaMasterPage.master";
}

Você pode ler mais sobre isso na Documentação
Comment: funcionou, já estava à muito tempo de volta disto , o meu cérebro deu tilt nem prestei atenção no erro muito Obrigado !
Comment: @PedroCardoso Fico feliz em ter ajudado, não se esqueça de marcar como aceita ;) assim se outros tiverem a mesma dúvida irão ver como você resolveu o problema.


Print Only Non Reoccuring Numbers (Python)

Question: Let me clean this up a bit so people can understand better.
I'm reading into a text file and I'm wanting to print out numbers just once, even if they appear again later on in the list.
Example Text File:
 100
 200
 300
 200

Based on my logic, since 200 is in the text file twice, I only want to print it once. So my desired output would look like this using the example text file above.
 100
 200
 300

Here is another example just to clarify (Text file is below)...
 250A
 300D
 300D
 300D
 250A

The designated output with the example above would be:
 250A
 300D

Comment: Why isn't the output "1, 2, 3, 4" or "1, 2, 2, 4"? If your rule is "print every number that appears, but only once", then 3 should be in the output. If your rule is "print only numbers that don't have a neighbor identical to them", then there should be two 2s in the output.
Comment: Sure, what would work. What's wrong with that solution?
Comment: So print `1, 2, 3, 3, 3, 2, 4` without `3`?
Comment: show all the code required for us to reproduce the problem, and only that code
Comment: I think you have an error in the question, I guess you actually want to print out 1,2,3,4 if that's the real request I would add all numbers to a Set and then print the set.
Comment: Please clarify the question, it is ambiguous as noted by kevin.
Answer: If the rule is "print only numbers that don't have a neighbor identical to them":
import itertools

def remove_consecutives(seq):
    return [k for k,v in itertools.groupby(seq) if len(list(v)) == 1]

seq = [1, 2, 3, 3, 3, 2, 4]
print remove_consecutives(seq)
#result: [1, 2, 2, 4]

If the rule is "print every number that appears, but only once":
def remove_repeats(seq):
    seen = set()
    result = []
    for item in seq:
        if item not in seen:
            result.append(item)
            seen.add(item)
    return result

seq = [1, 2, 3, 3, 3, 2, 4]
print remove_repeats(seq)
#result: [1, 2, 3, 4]

If the rule is "print every number that appears, but only once, and only if they don't have a neighbor identical to them":
import itertools

def remove_consecutives(seq):
    return [k for k,v in itertools.groupby(seq) if len(list(v)) == 1]

def remove_repeats(seq):
    seen = set()
    result = []
    for item in seq:
        if item not in seen:
            result.append(item)
            seen.add(item)
    return result

seq = [1, 2, 3, 3, 3, 2, 4]
print remove_repeats(remove_consecutives(seq))
#result: [1, 2, 4]

Answer: Why not read each number from the text file into a set then print the set out?
Comment: that would print every number, eliminating doubles. I think the OP wants to print only those numbers which have no duplicates (in sequence) I may be wrong (see @Kevin's comment above)
Answer: You can read those numbers into python list. If they are inside file, it will simply be:
with file('your_file.txt', 'r') as f:
    numbers = [line for line in f]

Then you can transform that list into set:
unique_numbers = set(numbers)

And inside unique_numbers you will get each number only once.
Comment: Welcome to Stack Overflow! Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem.
Answer: Two people suggested using set() to remove duplicates, which I think is a good idea. Python sets are kind of like lists, but each value can only appear once.
Here's some example code:
# Import the file as a list
with open('OldFile.txt','r') as f:
    values = f.readlines()

# Make a set object
unique_values = set(values)

# Write the set to a new file
with open('NewFile.txt','w') as f:
    f.writelines(unique_values)

Caution: set() does not respect the order of your elements. If that's a problem, consider sorting them like this:
unique_values = sorted(set(values))


Sql Query to get count from another row

Question: MenuID  PreMenuID  Type
P2000   BS02        p
P8001   P2000       x

Hi Experts i have table structure given above which indicates menu id as main id and PremenuId Indicates the previous menu from which call is  transferred.
Now type=x means there is a exception in the call
from the above table menuid=p8001 is transfer from P2000 as shown in premenuid
i want to get the count of exception generated in table but in mainId
the output should be smthng like ths
MenuID  Exception  OnId
p2000     1        p8001

Thanks.
Comment: Please format your table schema, and show us a minimum sample data and expected result.
Comment: Can `P2000` be in multiple `MenuID`? Meaning, can another row exist like this ? `P8002 P2000 x`
Comment: @ashish jayara can you try my ans
Answer: If I get your requirements right, a simple group by-Statement will do the job:
select PreMenuID as `MenuID`, count(Type) as `Exception`, MenuID as `OnID`
  where Type = x
  group by `MenuID`, `OnID`

Answer: You need to join table with itself.
select a.MenuID, count(b.MenuID) as Exception, group_concat(b.MenuID) as OnID
from tableName as a
join tableName as b on a.MenuID=b.MenuID
where a.type='x'

Comment: Don't you need to consider field `Type`? Something like `where Type='x'`...
Comment: Also I would use `join tableName as b on a.MenuID = b.MenuID` syntax rather than giving the join-condition in the where-clause. The `join ... on ...`-syntax has the advantage that you'll notice if the condition is missing, and won't execute a cross-join then.
Comment: @krishn patel group_concat Not a suportng tag in my sql  m useing sql 2008
Comment: @RenéHoffmann thanks for your remark, I was in hurry so I have made a mistake it

Sql Query to get count from another row


Probability density function of Gaussian noise

Question: I am wondering if a probability density function on a stochastic process can be defined. I've been searching around but what I've seen so far are only finite-dimensional distributions of a stochastic process. What's I'm interested in is something else -- can a probability density function be defined on an infinite-dimensional space such as the samples of a stochastic process?
Until recently, I came across a paper which says that if $\eta(t)$ is a Gaussian noise process (i.e. white noise) such that $E[\eta(t)] = 0$ and $E[\eta(t) \eta(t')] = D \delta(t-t')$ then the "formal" probability density for this process is given by
$P(\eta(t)) \propto \exp(-\frac{1}{2D} \int_{t_i}^{t_f} \eta^2 \,dt)$ for time points $t_i,t_f$.
I cannot find a reference for this and am unsure if the authors quoted "Quantum Mechanics and Path Integrals" by Feynman and Hibbs because the reference citation appeared to allude to a previous statement.
In any case, it appears that this density function was formulated by physicists. Can anyone direct me to mathematical papers which discuss this concept and how to make sense of it, somewhat more rigorously?
Comment: Your question is a little unclear.  What is a "formal" density function?  The spectrum (transform of the covariance) of this process is constant.  In your note, what is the definition of $P(\eta (t))$?
Comment: That's how the paper defines the probability density function of white noise. In other words, given an observation of the white noise $\eta(\cdot,\omega)$ for $\omega \in \Omega$, the "likelihood" of this observation is computed by the formula above. That's how  I interpret it
Comment: https://www.encyclopediaofmath.org/index.php/White_noise_analysis  https://www.encyclopediaofmath.org/index.php/White_noise
These might help clarify.  My working with white noise has always been mathematical.
Comment: The formula $P(\eta (t))=$ is weird to me.  $\eta (t)$ is an element of a stochastic process.  $P(\eta (t))$ is a number, but the right hand side contains the integral of a stochastic process, so it is not a number.
Comment: I know it's weird -- I presume these come from physics which is why I'm looking for more rigorous theory on this. The right hand side, for a fixed sample of a stochastic process, is a number so I don't see what's inconsistent
Comment: Your notation still doesn't look right.  On the right hand side you have a fixed sample for $\eta(t)$ - which sample?  On the left hand side you have $P(\eta (t))$, which is in itself not well defined, since $\eta (t)$ is not discrete, so intrinsically $P(\eta (t))=0$.  You need to clarify what you mean.
Comment: OK. Left hand side is the PDF, not probability that $\eta(t,\omega) = \eta^*(t)$ for some function $\eta^*(t)$. Right hand side would have $\eta(t)$ replaced by $\eta^*(t)$ which is now a deterministic function. Is this still not clear??
Comment: Notation is now clear.  You need to explain relationship between $t$ in $P(\eta (t))$and $t_f$ and $t_i$.  Also $\eta ^*(t)$ needs to be defined.
Comment: Defining $P(\eta (t))$ as you have is still very confusing.  If $\eta (t)$ is a Gaussian noise process, then its PDF is the usual Gaussian ($\frac{1}{\sigma \sqrt{2\pi}}e^{-\frac{x^2}{2\sigma^2}}$) and the major questions involve correlation or spectrum.
Comment: I agree that the notation is a bit strange. As a minimum, the upper limit in the integral should perhaps be $t$ (variable) instead of $t_f$ (value), so that both sides are functions of $t$. Also, upper case P is usually reserved for probability (as opposed to probability density $p$), so I would replace it with $p$. Then $p(\eta(t))$ is the probability density of the variate $\eta$ at time $t$.
Answer: Notation in the given expression aside, here is an attempt at interpreting it in relation to infinite-dimensional distributions, as mentioned in your first paragraph.
(Real) Gaussians with the given time-independent mean and delta-correlated covariance define a stationary process, i.e., independent of $t_i$. For any pair $(t_i,t_j)$, the two associated Gaussian variates $\eta_i=\eta(t_i)$ and $\eta_j\equiv\eta(t_j)$ are uncorrelated r.v. Hence, being Gaussians, they are mutually independent, so that their joint 2-dimensional probability density is their product
\begin{equation}
p(\eta_i,\eta_j;t_i,t_j) \propto \exp \left ( -\frac{\eta^2_1}{2\sigma^2_1} \right ) \cdot \exp \left  ( - \frac{\eta^2_2}{2\sigma^2_2} \right ) = \exp \left ( -\frac{\eta^2_1+\eta^2_2}{2D} \right )
\end{equation}
with $\sigma^2_1=\sigma^2_2 = E(\eta^2_1)=E(\eta^2_2) = D$ (taking $t=t^\prime$ above)  because $E(\eta_1)=E(\eta_2)=0$.
Repeating and extending this for $3, 4, \ldots, n < \infty$ time points, one gets a (finite) $n$-dimensional hierarchy of $n$-dimensional joint Gaussian density functions. For continuous $t$, one can let $n$ approach infinite, thus producing an infinite-dimensional joint pdf (i.e., for all uncountable infinite $t$ within $[t_i,t_f]$ or $[-\infty,+\infty]$) and hence a stochastic process as a probability functional on $t$. In general, this requires all 2-, 3-, ..., $n$-point correlations to be specified and known (a serious difficulty in practice). For real Gaussians, only the two-point correlations are necessary and sufficient to define the process completely.
Returning to the formula in your post, since all $\eta_i$ are uncorrelated no matter how small the mutual distances $|t_i-t_j|$, one can take them arbitrarily close. Thus, $\eta^2_1+\eta^2_2+\ldots + \eta^2_n$ in the numerator of the exponential (in the extension of the expression above to $n$ dimensions) approaches a Riemannian sum and becomes an integral over $t$ when considering all points $t$ in a given interval $[t_i,t_f]$.


EntityObject 5.x and Self Tracking Entities 5.x

Question: Does anyone know the if/when/where behind the self-tracking entities template for the latest version of EF? Our team would like to move forward to be able to take advantage of the performance improvements that the EF team has documented, but we haven't been able to find any reference to the new T4 templates for self-tracking entities, which we are dependent upon.
We've tried firing up the old template, but the framework has changed too much.
There's a thread on MSDN about it, but it has not been updated in a while. (http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/4993d0bf-94e8-4d14-aff1-3458b4ad467f/#889cc5f1-e267-448a-ae82-e3d705b7dfa5)
Thanks.
Comment: I would not be surprised if neither of those templates would be produced. `EntityObject` is mostly deprecated and self-tracking entities were replaced by WCF Data Services.
Comment: Now I see you are asking for 5.x templates - those even cannot exist because EF 5.x is only `DbContext`. It doesn't support `EntityObject` entities and STEs for DbContext never existed (at least officially).
Comment: STE exists. Got word from MS today that they are finishing up the licensing aspects of it and will release the template later this week.
Answer: You can download it from here, they are available now.


Convert expression from C# into Java

Question: I am to convert a C# program into Java. At one point I really don't get what is done, there. I changed the code to clarify the types and give an example.
string myString = "Test";
long l = (long)myString[0];

1) What is the [0] doing with a normal string? Is that even possible? Is it just the substring, in this case "T"?
2) How could you cast a String or character to long, if the String represents a text?
Comment: Btw the cast is redundant as this is not a narrowing conversion.
Comment: +1 for leveling. Maybe Manuel is not fluent in English. And anyway there are two related questions numbered as (1) and (2). For me it's pretty clear he wants to understand what's happening here (for eventually translate it to Java).
Comment: As I said, all answers were helpful. I decided to accept helios' answer because, at first, he was the only one who provided the example in Java. And, his explanation, as short as it might be, did help me understand what was going on in C# (because in the end it wasn't hard to understand, I kinda feel stupid that I asked).
But I have to admit that Abel's answer would've been a good choice, too.
Answer:
long l = (long)myString[0];

the index of a string gives the char. A char is castable as a long. This will give you the long-value (unicode value) of the character in the first position of the string, i.e., A will be 65.
The cast (long) is not needed in C#, because char has what's called a "implicit cast operator" for long and  int. The following statement is just as well correct:

long l = myString[0];

The equivalent of char in C# is char in Java, albeit that implementations are slightly different. In Java, a char can be cast to an int or a long. To get the character, use CharAt().
Answer: I think it's converting a char code to long. In Java you would have to:
long l = (long) myString.charAt(0)

Comment: Thanks @ all for clarifying this. All answers were helpful and I mark this one as accepted for giving the example in Java.
Answer: A string is an array of characters, so that makes it possible to access given position.
Having said that, myString[0] is accessing the first char, 'T'.
You can then cast a char to a long, converting it to its ASCII position value.
Answer: You can use this converter http://www.tangiblesoftwaresolutions.com/index.htm - the trial version is able to convert some amount of lines for free :)
Comment: You could also use IKVM and not having to convert anything. It just works under .NET.

Convert expression from C# into Java


Interpretation of regression coefficients as percent change when the outcome is log-scaled?

Question: $X$ is democracy level
$Y$ is infant mortality rate (IMR)
In my model, 1 unit increase in $X$ predicts a $20\%$ decrease in $Y$
Does this mean 5 unit increase in $X$ will eradicate IMR? In other words, can I conclude that 5 unit increase in democracy predicts $100\%$ decrease in IMR?
Answer: The regression models of positive outcomes usually consider multiplicative decrease in outcome and additive change in predictor. Assuming model $\log Y=\beta X+\epsilon$. Then an additive change in $X$ by one unit changes $Y$ by a multiplicative factor $e^\beta$, which can be translated into percent change with $(e^\beta-1)\cdot 100$.
Increasing $X$ by five units i.e. $X=x_0+5$ gives us $Y=y_0 \cdot \exp(\beta)^5$ with $y_0=\epsilon \exp(\beta x_0)$. Assuming that

1 unit increase in X predicts a 20% decrease in Y

then $\exp(\beta)= 1-20/100=.8$ and for 5 units increase in $X$, $Y$ decreases by a factor $\exp(\beta)^5=0.8^5=0.33$. That is approx. $67\%$ decrease.
It is sometimes recommended to approximate the logarithm with $\log(z)=z-1$ which is what You implicitly do when You claim that the percantage change is equal to $\beta$. The approximation is only valid for small changes in $Y$. Thus, with a change in $X$ by one unit, the approximation gives $-19.5$ for a true value of $(e^\beta-1)\cdot 100=-17.71\%$ which is reasonably accurate. However, when $X$ changes by five units, the approximation fails. Approximation suggests a change by $-97.5\%$ while the true value is $(e^{5\beta}-1)\cdot 100=-62.28\%$. When in doubt avoid the approximation and perform the exact calculation.
Comment: Hi Matus, thanks for answering. could you explain a bit more please.  i am trying to find the relationship between democracy level and infant mortality rate (IMR). I log-transformed the dependent variable (IMR). my equation is now: log Y= 4.107-0.195*democracylevel.                                                                      The interpretation is:  one unit increase in democracy level will predict 19.5% reduction in IMR. but how do i find the effect if democracy level is increased by 5 units?
Comment: @Hans I added more details. Let me know if additional clarification is needed.


What is the difference between mixing tracks with and without vocals?

Question: So whats the differences about regular edm track with no vocals vs pop/rock/rap tracks. Because i know it's something different. I want to know how i should mix instrumental behind the vocals in pop/rock/rap tracks you know what i'm saying

I'm stuck with these sh*t. I can't make tracks with vocals because i
don't know how it should sounds. I tired of mixing that. I have some
knowledge about how it should be. I have one way of mixing, maybe even
two. But I'm not sure why or when it works.
I create instrumental tracks(house,electro,etc.) with ease. Where only music is playing.
But tracks with vocals are another planet, it seems. Very strange!
Comment: How about doing it backwards, start with a good vocal track and add instrumental tracks to it one by one? When the vocal track stops sounding good, figure out why that happened. If you can't make a vocal track to sound good even by itself to begin with, then you have a problem that has nothing to do with the instrumental things.
Comment: Hm... as someone who's never tried, I'm not sure *why* it should require a whole different approach. Is the block-quote from yourself? Could you (or whoever said it) explain more about why you feel the instrumental approach isn't working? E.g., is it about how you process the vocals themselves, or about how you treat everything else to make them prominent? Also, mixing in different genres is very different. An EDM track with vocal samples, vs metal or a pop-rock or a hip hop track, all would take significant stylistic differences.
Comment: Yes, it's my block-quote.
Comment: Also maybe because it requires using a mic and i have a bad recordings and them don't mixed well. But i create tracks with my synth and it mixed good(EDM).
Comment: Ah; I do know that the best way to get a good mix is to start with good recordings! Maybe, instead of making your own with your own equipment, look for good vocal recordings under licenses that let you use them, like Creative Commons, and practice on those.
Answer: You're not going to learn this in a week, a month, or even a year, so be prepared for the long haul.
You need to create a vocal-shaped hole in your mix, into which the vocal will sit neatly - not spilling out, not being buried.
You can do it in the arrangement or you can do it in the mix. Here's an idea as to how to limit yourself to doing it in the mix. It gives you fewer choices, but makes you think… & learn.
On occasion I get a track that needs to be fixed, where I cannot for one reason or another touch the actual arrangement. Sometimes I've been given a bad stereo mix, which these days I break into stems using AI - but fixing it in the arrangement is no longer an option.
Here's a trick I've learned over the years.
Take two multiband compressors, one over the mix, the other just on the vox. I'm not allowing you any other effect for this, unless your vocal is totally dry, in which case I'll allow you one reverb & one delay. Don't cheat. Less is more.
Get the mix fairly happy first - treat the multiband as though you were mastering. You can't touch the mix, so you have to treat it as a master - then push a hole in it for the vox to sit. Make the vox sit in the hole using the other multiband. Stop the loud bits getting too loud & the soft bits getting too soft. Use it to EQ the vocal, so you can hear the consonants without them spitting at you. Tame the lows so they don't overpower. Make sure the mids are always clean; this aids overall intelligibility.
This is the bit that takes practise, but as I've only given you two things to adjust, you get to learn relatively quickly what works & what doesn't.
Make a version. Listen to it for a day or so on your phone, in the car, on friends' HiFis. Then come back & having learned what may be wrong with it… have another go.
Don't be scared to go back to the start. If you keep pushing the same idea further & further & it still isn't working, there was something wrong with the original idea - so throw it out & start over.
Here's a bit of a rough of a track I did recently. The song itself has been completely re-worked [brand new arrangement over original vox] for release, but this was the original version, done a long time ago, which the record company want to include as a 'historical version'. We had just the stereo mix to work from, which has some nasty buzzy synth badly clashing with the vocals, which themselves are over-worked. Basically the vox & keyboard are both trying to take up the same space. This does not work:\ My job was to get the keyboard out of the way, make the vox less smooshy [& they wanted 'wider'], and add a little clarity in the kick & bass frequencies [cleaning up the low-mids] while we were there.
The new arrangement is a lot better than this old one, but the record company were happy enough with this re-working for the 'historical version [they're going to pretend this is actually what the original sounded like ;)
It's a 'radio edit' so not particularly pumping, let the radio compression do that [loudness wars 101] & the vox are 'radio loud' not 'dancefloor loud'.
This is just recorded live off the board with me hitting mutes. You can hear the big clunk as it switches original to new each time, but not as it switches back again, you just hear it get fuzzy & small again. It starts with the fuzzy version. [File not level-optimised].
https://soundcloud.com/graham-lee-15/tc-demo/s-1Tvw6Sl758m?si=cbf663e6d0584ad3b1438c930cc1c68d&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing
sekrit link… ooohhhh… ;)
Comment: Even though your approach is very different from mine, the fundamental goal of making room for the vocal is the same.  I like your phrase "create a vocal-shaped hole in your mix".
Comment: I think the OP's problem is probably with song writing and arranging. Trying to add a vocal lead melody to a song that already has an instrumental melody or other central attention-seeking musical elements. Multiple leaders with incompatible agendas. Conflicting musical ideas which don't make a sensible combination, like two people trying to tell a different joke at the same time. And then trying to fix it in the mix. This is what I suspect. The right solution would of course be to have exactly ONE leading coherent musical idea, and have all elements support that same common idea.
Comment: @Theodore - I wrote this as 'an exercise in one thing & one thing only', because, as you appear fully aware… there's no fast fix to learn how to do this.
Answer: Even before you get to the vocals, there are some big differences between EDM, pop, rock, and rap.  Too many to put in one concise answer.
If you have a good mix of the instrumental portion (in whatever style) and try to add a lead vocal line to it, the most important work you need to do is to make space for it:

The composition and arrangement need to leave space. This is especially important to consider if the instrumental part was created on its own without any expectation that vocals would be added.
The dynamics of the instrumental portion may need to be adjusted so that the vocal isn't buried.  (I mostly mean altering macrodynamics by riding faders, not dynamic processing.)
The frequency balance/equalization of the instrumental parts will probably need to be adjusted so that they don't mask the vocal.

Considering the vocal track on its own, you'll probably need to learn something about dynamic processing (compression, limiting, etc.) and EQ for vocals.  In some situations, with the right vocal recording, you might not need much of that, but with pop or rock songs, I'd expect to use at least some.
Even with a good vocal performance, recorded with good equipment, in a good acoustical environment, expect to spend some time on all these.
Comment: I'm already knew about compression and eq. I told you that i'm good at making House music. The question here was how to make tracks with a voice like pop or rock. Thanks for the reply.
Comment: @LyubaIvanova Knowing how to use a compressor or EQ to do House music is not the same thing as knowing how to use a compressor or EQ on vocals.  It's probably not even the same compressor (or plugin).
Comment: @LyubaIvanova Then you'll know what frequencies you find the various parts of the voice at, for men and women?  Which frequencies are the fundamentals, which frequencies you can boost to increase clarity, and which frequencies you can cut to reduce breath noises?  How to use de-essing?  How you set up compressors (intentionally plural!) to reduce transients and get levels more steady?  How much of what reverb works for different styles?  Hint: If you've never worked with vocals, you ***don't*** already know any of this.  It'll be easier for you to learn, sure, but you still need to learn.


setup database to use with MS SQL Server 2008 and IIS7 on own server

Question: I have my own virtual server and I am looking to deploy a website to it.
The problem I am having is setting up the database. Normally on a hosted site I just upload the mdf file and I get a connection string from them.
I tried attaching the mdf file that I created with VS2010 using Management Studio to the 'local' server on my virtual server.
It creates it with a name that is the path to the file 'c:\inetpub\wwwroot...'
How do I get the connection string I need for to use this in my web config file?
I guess I will need to also create a user login for this also?
I did try and just have it use the express connection string but I get this error
Unable to open the physical file "C:\inetpub\wwwroot\gtro\App_Data\ASPNETDB.MDF". Operating system error 5: "5(failed to retrieve text for this error. Reason: 15105)".
An attempt to attach an auto-named database for file C:\inetpub\wwwroot\gtro\App_Data\ASPNETDB.MDF failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I have changed the app pools in IIS7 to use Network service in Identity.
There is definitely no database already attached with the same name either.
Answer: Please create Database on Server. Backup local database and upload .bak file on server. Restore backup using SQL management studio.
if you don't have SQL Express Installed on your VPS. You can download and install it from Microsoft Website.
Please check following URL :
http://forums.iis.net/t/1082433.aspx
Comment: That never worked. Complains that the backup is from a different database.
Comment: OK, Have you checked like While restoring database you can give name of database. You can give different name and it will restore it. Please check following URL http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=40841
Answer: Since the new database has a different schema, when you restore the database you will need to visit the Options tab and choose Overwrite the existing database.
Answer: System Error 5 is Access Denied.  Are you using SQL 2005 or above?  When you create a database and then detach it to attach it to another server its permissions are changed so only the same account can use it.  I believe the simple fix is to change the permissions on the local copy of the file to allow admins full control.  More info at this blog
edit: blog is now dead.
Hope that helps.


JSF 2.0 validation and field highlighting

Question: I am looking for some guidance/opinion on the best way forward to add field error highlighting in JSF 2.0. So far I have successfully implemented using Cagatay's example with a few minor adjustments to logic.
String styleClass = ( String ) uiInput.getAttributes().get("styleClass");
        //Check the valid flag
        if ( !uiInput.isValid() )
        {
            //Component already has a styleclass
            if ( styleClass != null )
            {
                //check if it's already highlighted
                if ( !styleClass.contains("ui-input-invalid") )
                {
                    //if not add the error class to it
                    styleClass = styleClass + " ui-input-invalid";
                    //and put the new styleclass back on the component
                    uiInput.getAttributes().put("styleClass", styleClass);
                }
            } else
            {
                //no current style class so just add the error class
                uiInput.getAttributes().put("styleClass", "ui-input-invalid");
            }
        } else  //component is valid so we might need to remove a highlight
        {
            //component has a styleclass
            if ( styleClass != null )
            {
                //check if it is already highlighted
                if ( styleClass.contains("ui-input-invalid") )
                {
                    //remove error class from the string
                    styleClass = styleClass.replace("ui-input-invalid", "");
                    //and put the new styleclass back on the component
                    uiInput.getAttributes().put("styleClass", styleClass);
                }
            }
        }

I have also used the suggestion of adding el to each component's styleclass - styleClass="#{component.valid ? '' : 'ui-input-invalid'}".
Both methods work like a charm when used in conjunction with Bean Validation JSR303. However I also have 2 additional validation stages. 1 to validate the form as a whole i.e. correct combination of fields and 1 to validate our general business rules once the field and form validation is successful. In order for these stages to also add the highlighting I need to do some manual work.  For both highlighting approaches I have to manually set the component(s) valid flag to false. To have access to the component I have bound it to its own object in the form vo.  Now for Cagatay's example I need to add all of the components to a List and then pass this list to the highlighting method.  If I use the styleclass approach I don't have to worry about a component list and passing to a highlighting method.  This seems the better approach to me however I'm a little concerned that it is adding logic to the JSF page which is something I want to stay away from.
What do you feel is the best approach or is there another way I am not aware of?  Also I assume there is no other way of setting the valid flags without binding to the component? At the moment I having to bind every component so I can set its valid flag.
Answer: It's been a while since I asked this and in the mean time we have actually partially implemented JSF into our enterprise app.  The solution for the field highlighted was quite complicated and in order for it to work, be reusable and be customisable it really has to fit snuggly into a framework that encompasses JSF/Input Value Objects, associated Input Field objects and Bean Validation.  Therefore someone stumbling here may not get the answer they are looking for.  However I going to include an portion of our internal design docs which describes the mechanism.  Hopefully this will help anyone else:

Field Highlighting and Error Messages  Field highlighting in JSF
  proved to be quite a complicated task.  This is because the html
  id/name is generated by jsf at runtime and can include many prefixes.
  JSF will add a prefix to an id when it is inside a
  form/tab/datatable/composite component.  An id of ucn may end up
  becoming tab1:contentForm:jsfDataTable:1:ucn.  It is therefore
  virtually impossible to try and predeterime what an id will be and
  then to try and highlight.  To resolve this issue a
  preRenderComponentEventListener class is used.  This is registered in
  the facesConfig.xml along with an input type.  This tells the JSF
  lifecycle to run this class whenever that type of input is about to be
  rendered.  We then have access to the short and long ids of the input
  which we can then save and look up later.  The full procedure is as
  follows:

Entry in facesConfig.xml registers a
  preRenderComponentEventListener and the associated type of input.
  Each time before the input is rendered the processEvent method is
  called.
Entry in facesConfig.xml registers a HashMap called
  componentMap which is used to store the input ids.
When the
  processEvent method is called the Input element is retrieved.  The
  componentMap is retrieved and input's id/clientID is added to the map.
  The id of the input is the Key (this is the short id i.e. ucn) and the
  ClientID is the value (this is the long JSF generated id i.e.
  csn01Form:jsf454:ucn:1).  To handle multiple inputs of the same name
  like in DataTables the key is added with an Incrementing Index.  E.g.
  if ucn3 is already in the map ucn4 will then we added.
Once this
  process is complete the componentMap will contain entries for every
  input field.  Therefore by using the short id the full clientID can be
  retrieved.
In the BackingBean FormatValidationExceptions and
  RuleExceptions are caught and handled.
FormatValidationExceptions.  These derive from BeanValidation.  A
  subclass of an InputVO is created which contains subclasses of
  Destin8Input (See CSN01InputVO).  If format validation is needed on an
  Input they should be annotated with a custom bean validation. E.g.
  @StringCheck (See Bean Validation).
The FormatValidation class
  has a method called validateFormats which takes in a type of InputVO
  and runs it through the Bean Validator (when using a Transaction
  Controller this method will automatically be run).  The Bean Validator
  will automatically take each annotated field and run the isValid()
  method associated with the annotation.  The @StringCheck for example
  checks the value entered matches a regular expression and that the
  number of characters entered is correct.  Any failures will result in
  a ConstraintViolation.  At this point the error message is generated
  using the Error Display Name from the Destin8Input.  All validation
  checks are performed and will result in a Set of ConstraintViolations.
In the validateFormats method the Set of ConstraintViolations is
  looped round and each message is added to an Error Message List in the
  ValidationFormatException.  Each htmlID in error is also added to a
  Field Error List.
The ValidationFormatException is caught in the
  BackingBean.  All Error messages are added as a FacesMessage to be
  displayed at the top of the page.
RuleExceptions are similar
  except messages and fields to highlight are manually added when
  throwing an exception.  The message code will be looked up from the
  DB.
The List of ids in error is now looped round and is used to
  retrieve the associated full ClientID from the componentMap.  Each
  ClientID is added to a List.
This List is passed to the
  JSFUtils.highlightFields method where each ClientID is added to a ~
  Delimited String.
This delimited String is then added to the
  RequestMap with a key of 'errors' (this is a map automatically
  available as per of each request).
This String is then retrieved
  as part of the Destin8Template.xhtml -
A
  javascript method called highlightFields in then immediately called.
  This effectively loops through the delimited String, gets the full id
  and then adds the Error css class using jQuery.
It is important to
  note that the link between a Java Input and a JSF Input is the id.  In
  order to connect the 2 it is vital they have the same ID.  This is
  achieved by using the IDConstants class.  This is an ENUM which
  contains entries for different fields.  An entry is also added to the
  IDConstants managed bean which allows access via a facelet.  This is
  then added as the id attribute for the applicable input element.
Comment: Prime Faces does this by default


If $a|c$ and $b|d$, is it true that $ab|cd$?

Question: Determine if this is true or not:

For any natural numbers $a$, $b$, $c$, and $d$, if $a | c$ and $b | d$ then $ab|cd$.

My answer was True, I went:

$a = 2$, $b = 4$, $c = 6$, and $d = 8$.
If $2|6$ and $4|8$, then $(2 * 4) | (6 * 8)$.

Is there another way to do it using, for example, a contradiction proof?
Comment: You haven't proved the assertion. You've just found one example where it's true. You need algebra for the general case. Start with: if $a | c$ then there is an integer $x$ such that $c = ax$. Then ...
Comment: You haven't done anything yet. You claimed something, but you didn't prove it. Your example is not a proof.
Comment: You can't prove by giving an example.  But an example can give you ideas of how to do it.  What is $a|c$ *mean*?  It means $c = ka$ for some integer $k$.  So $b|d$ means $d = jb$ for some integer $j$.  So what is $c*d$ equal to?
Answer: The claim is that this is True for any numbers $a$, $b$, $c$, and $d$.  So, unlike the counterexample you asked about earlier, where you only had to find one example where the claim fails, if you want to prove that this is True, you want to prove that this is true in general, i.e. for all numbers $a$, $b$, $c$, and $d$, and not just for some specific numbers.
So: Take any numbers $a$, $b$, $c$, and $d$, and suppose $a|c$ and $b|d$. Now, if $a|c$ then that means that $c = ae$ for some whole number $e$. Likewise, $d = bf$ for some whole number $f$.  Hence, $cd = aebf = abef$. Hence, there is some whole number $g =ef$ such that $cd =abg$. Hence, $ab|cd$.


pushing a folder to a bitbucket

Question: I have a folder(b) inside another folder(a) which was already pushed into a repository, and i want to push folder(b) to the bitbucket using macHg but I want it to push it so in bitbucket it looks like a new folder, right now when i pushed it it just made a new head it didn't put the whole folder in there. How can I push the whole folder so on bitbucket would look like
Folder A

Folder B

file
Answer: If you run hg status, what do you get? You should get output like this:
zck@zck-desktop:~/my-test$ hg status
? a/b/file

The question mark means that mercurial doesn't know about a/b/file yet. So let's tell it to track the file. This is just a local command, nothing will hit the remote server yet.
zck@zck-desktop:~/my-test$ hg add a/b/file
zck@zck-desktop:~/my-test$ hg status
A a/b/file

The A means that the file was just added. Now we just need to commit (which is another local command).
zck@zck-desktop:~/my-test$ hg commit -m "added a/b/file, with contents in it?"

Finally, we need to push the changeset up to the remote server. This is the only command we've done that touches the remote server.
zck@zck-desktop:~/my-test$ hg push

pushing a folder to a bitbucket


Let $\ X_1,X_2,X_3$ be an independent continuous random variables

Question: Let $\ X_1,X_2,X_3$ be an independent continuous random variables that are uniformly distributed on $\ [0, n]$.
Let $\ M = M=max{(X_1,X_2,X_3)}$
$\ P(M≤X)=?$ for general $\ X∈[0,n]$
$\ E[M]=?$
I Know that $\ P(X≤t)=F(t)=(t-a)/b=t/n$
$\ P(M≤X)=P(X>M)=1-F(t)=1-M/n$ , Is that true?
How I calculate $\ E[M]=?$
Answer: To find $P(M\le t)$ :
Calculate it by definition : $P(M\le t) = P(Max\{X_1,X_2,X_3 \} \le t) = P(\cap_{i=1}^3 (X_i\le t) )$ now use independence and finish.
For $E[M]$ , again calculate it by definition.
Differentiate $F_M(t) = P(M\le t)$ to get $f_M(t)$ and then find $E[M] = \int_\Bbb R t f_M(t) dt$.
Comment: $\  a≤X≤b $
$\  P(X_1≤X)=P(a≤X_1≤b)=F(b)-F(a)=
(b-a)/(b-a)-(a-a)/(b-a)=1 $
Therefore , $\  P(M≤X)=1*1*1=1 $
$\ E[M]=∫(X*1)=X^2/2$
**I'm not sure about the answer** @infinity
Answer: Hints:

$P(M \le x) = P(X_1 \le x, X_2 \le x, X_3 \le x) = P(X_1 \le x) P(X_2 \le x) P(X_3 \le x)$
Because $M$ is nonnegative you can use the tail sum formula for expectation: $E[M] = \int_0^n P(M \ge t) \, dt$. You can use the result of the previous question to find the integrand.
Comment: $\  a≤X≤b $
$\  P(X_1≤X)=P(a≤X_1≤b)=F(b)-F(a)=(b-a)/(b-a)-(a-a)/(b-a)=1 $
Therefore , $\  P(M≤X)=1*1*1=1 $


Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' Line 53

Question: I've looked high and low and cannot find it. Here are Lines 48-55
//add the cover page sales link here
        echo "

        Get Your Divorce Magazine By Mail - Click Here

Comment: a syntax error is a syntax error. Your lost in `"`
Comment: Google `PHP escape quotation marks`
Comment: Use an editor with syntax highlighting (and auto-indenting and other goodies) - notepad.exe is *not* a suitable environment. The error is trivial to spot once posted here. Look at the discoloration at `id="future"`.
Answer: Better use a here-doc for such a string:
//add the cover page sales link here
echo <<<saleslink

    Get Your Divorce Magazine By Mail - Click Here

saleslink;

beware that saleslink;needs to be in col 1 of the line!
Comment: @Brad thanks, too early here ...
Comment: Stack Overflow is my insomnia cure here.  :-D  But, I don't think it's working.  Ha!  Also, to help Irene with Googling... PHP land seems to prefer to call it heredoc.
Comment: What does `here-script` mean? They way its tagged that makes it look like an official term which it isn't. Its either `heredoc` or `nowdoc` and the difference can be see here http://php.net/manual/en/language.types.string.php   :)
Comment: I was asked for the whole code: too long. grrr..
Comment: I tried changing to that, but still getting an error. Any further help?
Comment: @IreneGaudet what error exactly?
Comment: @AxelAmthor This document is riddled with problems. Trying to fix someone else's mess and know just enough to have gotten in big trouble! Now error further down in document. In Lin3 117 Here are 115 onward
$gab_query = new WP_Query();$gab_query->query('cat='.$cat2.'&posts_per_page=1&orderby=rand');
     while ($gab_query->have_posts()) : $gab_query->the_post();
     $do_not_duplicate[] = $post->ID;
     ?>
Comment: @IreneGaudet then we need the entire code. Probably the heredoc end is not put on a single line and not in column one and not terminated by `;` reda about [heredoc](http://php.net/manual/de/language.types.string.php#language.types.string.syntax.heredoc)
Comment: I've been looking at that - entire code too long to post here.
Comment: managed to post it in new
Cleaning up someone's code and getting nothing but errors.
Answer: The error is caused by an unescaped quote in a quoted string. This is just a messy situation all around - such strings rarely belong in code.
I would move the HTML out of PHP (strings) and any required value interpolation into the HTML - note the use of the <?= ?> tags as examples. This let's PHP function more as a template engine and does a tiny little bit to separate the concerns.. and there are template engines to clean this up even more.
<?php /* some php stuff way up here */ ?>

    <a href='<?= $theUrl ?>'>Get Your Divorce Magazine By Mail - Click Here

<a href='<?= $theUrl ?>'>

                <?= htmlentities($thePostBody) ?>

<?php /* some php stuff way down here */ ?>

Answer: Take a look at how StackOverflow has formatted your code example.  See how the text is red up until the quote before future?  That's because it's a string up until that point... where the string is ended because your quote mark is actually ending the quote.
Escape your quotes with \.
<div id=\"future\" ...

You can also just use a single quote out front.  This is preferred anyway as it is marginally faster since string interpolation isn't done.  If you do this, remember to escape any literal single quotes with \ as well.
Answer:

change it to

When you are echoing, using ", you should use ' to internal codes and if it is necessary to use ", use it as \"


Debugging broken Sublime Text 3 keyboard shortcuts

Question: After installing a couple of Sublime Text packages, some of the previous keyboard shortcuts were broken.
What's the best way to find the package which defines a keyboard shortcut?
Answer: I personally prefer the Plugin Keymaps.
Quote from the readme:

Plugin for Sublime Text 2/3 editor that enables searching for keymaps by function as well as showing all enabled keymaps in a searchable color-coded list - Cheat Sheet.

So can simply install it with package control and search for entries.
Answer: To save the next person some time trying to debug this situation:
To enable logging in your Sublime Text window, first open the Python console by typing:
    CTRL-`

Then run this command to enable logging of commands:
    sublime.log_commands(True)

With the output you see in the console, it should be easier to identify the offending package which overrides a keyboard shortcut.


Functions for regression diagnostics on mer objects in R

Question: I'm particularly interested in plotting residuals against fitted values, and residuals against predictors.  Often times I need to make boxplots of the residuals conditional on predictors.
I'd be interested in functions that include other/multiple diagnostics as well, e.g. ceres plots, qqplots.
The car package has some nice diagnostic functions but they are only for objects of class lm and I often use lmer.
Comment: Did you check Gelman's [ARM package](http://www.stat.columbia.edu/~gelman/arm/)? I seem to remember there were pretty nice functions in there. (Would have to check again, though.)
Comment: I certainly could be wrong, but I wouldn't be surprised if you need to roll your own because exactly how to treat the different levels of residuals you get from a mixed model may depend on how your model is set up.  I remember Gelman having functions to simulate data from the model to see if it looks like the original.  Very good for diagnostics, though not quite what the OP has in mind.
Answer: Not really about partial residuals plots, but I came across the influence.ME package which seems to address the last point, if we consider diagnostic measures to extend to influential observations.
I also found some illustrations that were apparently done in R in the following paper:

Nobre, JS and da Motta Singer, J (2007). Residual Analysis for Linear
  Mixed Models. Biometrical Journal, 49(6), 863–875.

(But check out the following slides, Residual Analysis for Linear Mixed Models, by one of the authors.)


.NET bug in BigInteger?

Question: I've been working on a .NET project where I need BigIntegers and I've noticed that the framework's implementation delivers what appears to be incorrect results. After hours of trying to find what I'm doing wrong I decided to test my algorithm in Java and C++ (using OpenSSL) and shockingly in both languages I get the expected results.
Now I'm naturally wondering what I'm doing wrong (since there is no way on earth this is a bug that hasn't been noticed before) and I hope someone can help me!
This is the reduced C# code:
using System;
using System.Numerics;
using System.Globalization;

public class Program
{
    public static void Main()
    {
        var B = BigInteger.Parse("023B61801145A9CB06ADF77493042D166E793B946D1B07B46070E3986A6F036BE", NumberStyles.AllowHexSpecifier);
        var k = BigInteger.Parse("3", NumberStyles.AllowHexSpecifier);
        var x = BigInteger.Parse("09F015DB40A59403E42FBD568AF5774A0A0488A62", NumberStyles.AllowHexSpecifier);
        var g = BigInteger.Parse("7", NumberStyles.AllowHexSpecifier);
        var N = BigInteger.Parse("0894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7", NumberStyles.AllowHexSpecifier);
        var u = BigInteger.Parse("0AC06F615645BEA9B3D6D887C30D28D71B079B598", NumberStyles.AllowHexSpecifier);
        var a = BigInteger.Parse("0D4515CA7747787F1DDA9962ACE81E8412D9D20D06251696ACD74735F1F3B9875", NumberStyles.AllowHexSpecifier);

        var S = calc(B, k, x, g, N, u, a);
        Console.WriteLine(S.ToString("X"));
    }

    static BigInteger calc(BigInteger B, BigInteger k, BigInteger x, BigInteger g, BigInteger N, BigInteger u, BigInteger a)
    {
        var val = B - k * BigInteger.ModPow(g, x, N);
        var exponent = a + u * x;
        return BigInteger.ModPow(val, exponent, N);
    }
}

You can execute it here: https://dotnetfiddle.net/qXXiBk
Same code in Java:
import java.math.BigInteger;

public class Main
{
  public static void main(String[] args)
  {
    BigInteger B = new BigInteger("023B61801145A9CB06ADF77493042D166E793B946D1B07B46070E3986A6F036BE", 16);
    BigInteger k = new BigInteger("3", 16);
    BigInteger x = new BigInteger("09F015DB40A59403E42FBD568AF5774A0A0488A62", 16);
    BigInteger g = new BigInteger("7", 16);
    BigInteger N = new BigInteger("0894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7", 16);
    BigInteger u = new BigInteger("0AC06F615645BEA9B3D6D887C30D28D71B079B598", 16);
    BigInteger a = new BigInteger("0D4515CA7747787F1DDA9962ACE81E8412D9D20D06251696ACD74735F1F3B9875", 16);

    BigInteger S = calc(B, k, x, g, N, u, a);
    System.out.println(S.toString(16));
  }

  private static BigInteger calc(BigInteger B, BigInteger k, BigInteger x, BigInteger g, BigInteger N, BigInteger u, BigInteger a)
  {
    BigInteger value = B.subtract(k.multiply(g.modPow(x, N)));
    BigInteger exponent = a.add(u.multiply(x));

    return value.modPow(exponent, N);
  }
}

You can execute it here: https://www.onlinegdb.com/BJXxMiO28
And finally a quick and dirty C++ implementation using OpenSSL:
#include <iostream>

 #include <openssl/bn.h>

 class BigInteger
 {
     public:
        BigInteger(char const* hexString, BN_CTX *ctx)
            : bn_{BN_new()}
            , ctx_{ctx}
        {
            BN_hex2bn(&bn_, hexString);
        }

        ~BigInteger()
        {
            BN_free(bn_);
        }

        BigInteger ModPow(BigInteger const& exponent, BigInteger const& modulo) const
        {
            BigInteger ret{"0", ctx_};
             BN_mod_exp(ret.bn_, bn_, exponent.bn_, modulo.bn_, ctx_);
             return ret;
        }

        BigInteger Subtract(BigInteger const& rhs) const
        {
            BigInteger ret{"0", ctx_};
            BN_sub(ret.bn_, bn_, rhs.bn_);
             return ret;
        }

        BigInteger Multiply(BigInteger const& rhs) const
        {
            BigInteger ret{"0", ctx_};
            BN_mul(ret.bn_, bn_, rhs.bn_, ctx_);
             return ret;
        }

        BigInteger Add(BigInteger const& rhs) const
        {
            BigInteger ret{"0", ctx_};
            BN_add(ret.bn_, bn_, rhs.bn_);
             return ret;
        }

        std::string ToString() const
        {
            return BN_bn2hex(bn_);
        }

     private:
     BIGNUM* bn_;
     BN_CTX *ctx_;
 };

BigInteger calc(BigInteger const& B, BigInteger const& k, BigInteger const& x, BigInteger const& g, BigInteger const& N, BigInteger const& u, BigInteger const& a)
{
    BigInteger value = B.Subtract(k.Multiply(g.ModPow(x, N)));
    BigInteger exponent = a.Add(u.Multiply(x));

    return value.ModPow(exponent, N);
}

int main()
{
     BN_CTX *ctx = BN_CTX_new();

    BigInteger B{"023B61801145A9CB06ADF77493042D166E793B946D1B07B46070E3986A6F036BE", ctx};
    BigInteger k{"3", ctx};
    BigInteger x{"09F015DB40A59403E42FBD568AF5774A0A0488A62", ctx};
    BigInteger g{"7", ctx};
    BigInteger N{"0894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7", ctx};
    BigInteger u{"0AC06F615645BEA9B3D6D887C30D28D71B079B598", ctx};
    BigInteger a{"0D4515CA7747787F1DDA9962ACE81E8412D9D20D06251696ACD74735F1F3B9875", ctx};

    auto S = calc(B, k, x, g, N, u, a);

    std::cout << S.ToString();
    BN_CTX_free(ctx);
}

You can execute it here: https://godbolt.org/z/PtNGdQ
Again, both C++ and Java agree on the answer beeing 218BC3CE2641EFF5F4BB95A2DB931CA62A933C6BA40D3F6E2AD5D5F7D41F0E0A and only C# says it's 98405F6F9C609C9A370E3A17B28CCC5322918ADCE44DE0DE7F995370A9E07253. This is an actual show-stopper since I need to work on systems that require the first (correct) answer. I'm really at a loss here and I sincerely hope that somebody knows what I'm doing wrong.
Cheers
Comment: @AliKianoor These numbers don't fit in `Int64` - that's the whole point of `BigInteger`.
Comment: @AliKianoor Why do you think that will help when it's already established that the hexadecimal strings are being parsed correctly in all 3 platforms?
Comment: Have you ever tried Int64 instead of BigInteger?
Comment: try this one: BigInteger.Parse(hexString, NumberStyles.Any); maybe 'Any' can solve the problem.
Comment: Even using the decimal values and no flags still generates the incorrect answer (or all other platforms and also python are wrong and only c# is correct... I didn't check the computation myself by hand or with my own big integer code).
Comment: @SirRufo I don't believe so, I get the same results from C# and Java **after** the `ModPow` call. Things only get different at `d = B - m` in my wiki answer below.
Comment: @Dai Your wiki answer is wrong
Comment: @SirRufo It's a wiki after-all, please update it if you think it can be improved :)
Comment: @Dai use ToString() in C# and toString(10) in Java and you will get comparable results
Comment: @Dai I tried to improve the answer - but honestly the best improvement would be its deletion
Answer: Python also agrees the answer should be 218bc3ce2641eff5f4bb95a2db931ca62a933c6ba40d3f6e2ad5d5f7d41f0e0a
and the problem doesn't seem the hex parsing (even parsing the decimal version of the values the result is the same).
I think you've the correct attitude about thinking that's not possible that it's a bug in the big integer in that C# implementation, but this actually seems to me a screaming evidence this is the case (even if I must say I'm not a C# programmer, only played with it a bit).
You should in my opinion file a bug report.
EDIT
As Sir Rufo pointed out correctly in the comments the problem is in how modulo operation is handled in C# for negative dividends, changing the code to
var val = (B - k * BigInteger.ModPow(g, x, N) + N*k) % N;

produces the expected result.
I would say still a bug, but a design bug and not going to be fixed.
Comment: Very interesting! I'd also say it's very much unlikely that this will get fixed since I'd assume a lot of code depends on this weird behaviour. Thank you so much for looking into this!
Answer: Information
Lets have a look inside the calc method:
When we compare the hex output values in C# val.ToString("X") and Java val.toString(16) we will get different outputs:

C#:   F4EB82A8CAFDA89F0E2B69C3C4FEF2920913B60DD701C2193C41AE7EC6BC1A38B
Java: -b147d5735025760f1d4963c3b010d6df6ec49f228fe3de6c3be51813943e5c75

but when we use the decimal output values in C# val.ToString() and Java val.toString(10) we will get the same outputs:

C#:   -80186293521643543106092742417459818853945355375849134884320433064971933211765
Java: -80186293521643543106092742417459818853945355375849134884320433064971933211765

This answer is based on a comparison (hex outputs) which you cannot compare.

(Posting this as an answer because this won't fit into a comment, but making it a community wiki):
The difference between the C# and Java versions happens inside calc. When I separate-out the intermediate values like so:
CSharp
BigInteger B = BigInteger.Parse("023B61801145A9CB06ADF77493042D166E793B946D1B07B46070E3986A6F036BE", NumberStyles.AllowHexSpecifier);
BigInteger k = BigInteger.Parse("3", NumberStyles.AllowHexSpecifier);
BigInteger g = BigInteger.Parse("7", NumberStyles.AllowHexSpecifier);
BigInteger x = BigInteger.Parse("09F015DB40A59403E42FBD568AF5774A0A0488A62", NumberStyles.AllowHexSpecifier);
BigInteger N = BigInteger.Parse("0894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7", NumberStyles.AllowHexSpecifier);

Console.WriteLine( "B == " + B.ToString("X") );
Console.WriteLine( "k == " + k.ToString("X") );
Console.WriteLine( "g == " + g.ToString("X") );
Console.WriteLine( "x == " + x.ToString("X") );
Console.WriteLine( "N == " + N.ToString("X") );

Console.WriteLine( "-------" );

BigInteger p = BigInteger.ModPow(g, x, N);
Console.WriteLine( "p == " + p.ToString("X") );

BigInteger m = k * p;
Console.WriteLine( "m == " + m.ToString("X") );

BigInteger d = B - m;
Console.WriteLine("d == " + d.ToString("X"));

Java
BigInteger B = new BigInteger("023B61801145A9CB06ADF77493042D166E793B946D1B07B46070E3986A6F036BE", 16);
BigInteger k = new BigInteger("3", 16);
BigInteger g = new BigInteger("7", 16);
BigInteger x = new BigInteger("09F015DB40A59403E42FBD568AF5774A0A0488A62", 16);
BigInteger N = new BigInteger("0894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7", 16);

System.out.println("B == " + B.toString(16));
System.out.println("k == " + k.toString(16));
System.out.println("g == " + g.toString(16));
System.out.println("x == " + x.toString(16));
System.out.println("N == " + N.toString(16));

System.out.println("-------");

BigInteger p = g.modPow(x, N);
System.out.println("p == " + p.toString(16));

BigInteger m = k.multiply(p);
System.out.println("m == " + m.toString(16));

BigInteger d = B.subtract(m);
System.out.println("d == " + d.toString(16));

These gives me this output:
CSharp:
B == 23B61801145A9CB06ADF77493042D166E793B946D1B07B46070E3986A6F036BE
k == 3
g == 7
x == 09F015DB40A59403E42FBD568AF5774A0A0488A62
N == 0894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7
-------
p == 46FF4F26CC2AB0EA82B849044AC68D6CC772C8232086C890C0FBC5DE13BA3111
m == 0D4FDED74648012BF8828DB0CE053A84656585869619459B242F3519A3B2E9333
value == F4EB82A8CAFDA89F0E2B69C3C4FEF2920913B60DD701C2193C41AE7EC6BC1A38B

Java:
B == 23b61801145a9cb06adf77493042d166e793b946d1b07b46070e3986a6f036be
k == 3
g == 7
x == 9f015db40a59403e42fbd568af5774a0a0488a62
N == 894b645e89e1535bbdad5b8b290650530801b18ebfbf5e8fab3c82872a3e9bb7
-------
p == 46ff4f26cc2ab0ea82b849044ac68d6cc772c8232086c890c0fbc5de13ba3111
m == d4fded74648012bf8828db0ce053a84656585869619459b242f3519a3b2e9333
d == -b147d5735025760f1d4963c3b010d6df6ec49f228fe3de6c3be51813943e5c75

So it's something weird going on in B - m and not the ModPow call.
Part 2
Let's reduce this case down to d = B - m by serializing the BigInteger values (I verified they're being serialized correctly):
CSharp
BigInteger B = BigInteger.Parse("023B61801145A9CB06ADF77493042D166E793B946D1B07B46070E3986A6F036BE", NumberStyles.AllowHexSpecifier);
Console.WriteLine( "B == " + B.ToString("X") )

BigInteger m = new BigInteger( new Byte[] { 51, 147, 46, 59, 154, 81, 243, 66, 178, 89, 148, 97, 105, 88, 88, 86, 70, 168, 83, 224, 12, 219, 40, 136, 191, 18, 128, 100, 116, 237, 253, 212, 0 } );
Console.WriteLine( "m == " + m.ToString("X") )

BigInteger d = B - m;
Console.WriteLine( "d == " + d.ToString("X") )

Java:
BigInteger B = new BigInteger("023B61801145A9CB06ADF77493042D166E793B946D1B07B46070E3986A6F036BE", 16);
BigInteger m = new BigInteger( new byte[] { 0, -44, -3, -19, 116, 100, -128, 18, -65, -120, 40, -37, 12, -32, 83, -88, 70, 86, 88, 88, 105, 97, -108, 89, -78, 66, -13, 81, -102, 59, 46, -109, 51 } );

System.out.println("B == " + B.toString(16));
System.out.println("m == " + m.toString(16));

BigInteger d = B.subtract(m);
System.out.println("d == " + d.toString(16));

This shows that both C# and Java have the same values for B and m and different values for d:
// C#:
B == 23B61801145A9CB06ADF77493042D166E793B946D1B07B46070E3986A6F036BE
m == 0D4FDED74648012BF8828DB0CE053A84656585869619459B242F3519A3B2E9333
d == F4EB82A8CAFDA89F0E2B69C3C4FEF2920913B60DD701C2193C41AE7EC6BC1A38B

// Java:
B == 23b61801145a9cb06adf77493042d166e793b946d1b07b46070e3986a6f036be
m == d4fded74648012bf8828db0ce053a84656585869619459b242f3519a3b2e9333
d == -b147d5735025760f1d4963c3b010d6df6ec49f228fe3de6c3be51813943e5c75

The question is - does F4EB82A8CAFDA89F0E2B69C3C4FEF2920913B60DD701C2193C41AE7EC6BC1A38B represent the same value as -b147d5735025760f1d4963c3b010d6df6ec49f228fe3de6c3be51813943e5c75?
Comment: Seems the difference in how hex conversion displays negative values; what you found is a display difference.
Comment: Your are not comparing the real results, just presentations of the values and the hex presenters are different for C# and Java.

.NET bug in BigInteger?


Embedding dataframe plot on figure canvas?

Question: Despite the ample matplotlib documentation at https://matplotlib.org/3.1.0/gallery/user_interfaces/embedding_in_tk_sgskip.html
I'm struggling with the simple task of embedding a dataframe plot on a figure canvas in a tkinter GUI.
I've loaded all the relevant packages and created my dataframe, named "df", inside a tkinter master window named "root".
The problem, which likely stems from an inadequate understanding of how figures work, comes down to the following lines of code
fig=df.plot()
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=TOP)

The error message I receive states, "AttributeError: 'AxesSubplot' object has no attribute 'set_canvas'"
Comment: Does `df.plot()` return a `matplotlib.figure.Figure`? It looks like it returns a `matplotlib.axes.AxesSubplot` object instead. I think that `FigureCanvasTkAgg`'s first argument should a figure
Comment: Yes, df.plot() works. However, the command print(type(df.plot())) indicates
Comment: I don't know much about `matplotlib` but it seems that `df.plot()` returns a `matplotlib.axes._subplots.AxesSubplot` object but `FigureCanvasTkAgg` takes only a `matplotlib.figure.Figure` object. So you need to find a way to get the `Figure` object from the `AxesSubplot`.
Comment: I see. That's the gap in my understanding.
Answer: TheLizzard's comment is correct, df.plot() does not returns a matplotlib.figure.Figure but a  matplotlib.axes.AxesSubplot and fig should be a Figure.
However, df.plot() can take the matplotlib AxesSubplot in argument (the ax option). So you can create the subplot in the figure, then plot your DataFrame in the subplot:
fig = Figure(figsize=(5, 4), dpi=100) # create the figure
ax = fig.add_subplot(111)   # create the subplot
df.plot(ax=ax)  # plot df in ax

canvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

Comment: I was just guessing from the documentation :D. Nice answer btw


Limit $\lim_{x\to\infty} x(\arctan(a^2x)-\arctan(ax))$

Question: I have a limit $\lim_{x\to\infty} x(\arctan(a^2x)-\arctan(ax))$ and I know the solution $\frac{a-1}{a^2}$, but I dont have any Idea, how to calculate this limit or at least how to start. Any idea?
Comment: Do you know what is $\lim_{x \to \infty} \arctan(x)$?
Comment: Are you allowed to use Taylor expansions?
Comment: As long as I know $\pi/2$. Is there possibility, that it was an error in my solutions, which I get (only resoult without caluclation).  @user170231, how do u Solve with Taylor?
Answer: I assume that we are near $+\infty$.
If $ a=0 $, the limit is zero.
If $ a<0 $ the limit is$$+\infty(\frac{\pi}{2}-(-\frac{\pi}{2}))=+\infty$$
If $ a>0$, then we use the well-known identity, for $X>0 \;:$
$$\arctan(X)=\frac{\pi}{2}-\arctan(\frac 1X)$$
So, we want
$$\lim_{x\to+\infty}x\Bigl(\arctan(\frac{1}{ax})-\arctan(\frac{1}{a^2x})\Bigr)$$
we use the fact that, near $+\infty$
$$\arctan(\frac 1X)=\frac 1X(1+\epsilon(X))$$
thus
$$\arctan(\frac{1}{ax})-\arctan(\frac{1}{a^2x})=$$
$$\frac 1x(\frac 1a-\frac{1}{a^2})+\frac 1x\epsilon(x)$$
the limit is then
$$\frac 1a-\frac{1}{a^2}=\frac{a-1}{a^2}$$


how we get element width in decimal using jquery

Question: I am getting the width of element in integer rather than in fraction because my element width is 49.358 px. But i am getting 50px using
$('lichildren').width()

where liChildren is my variable
please suggest me any alternate for this issue.
Comment: When an element is shown on screen, the browser rounds the size to the nearest pixel - because the smallest unit of measurement on a monitor is a pixel. 50px is probably what the width of the element is when displayed, so the variable is correct
Answer: Reference Question Use the native Element.getBoundingClientRect rather than the style of the element. It was introduced in IE4 and is supported by all browsers:
$("#lichildren")[0].getBoundingClientRect().width

Demo
Answer: See the following answer to a similar question:
Getting the actual, floating-point width of an element
The accepted answer starts by saying:
If you already have a reference to the DOM element, element.getBoundingClientRect will get you the values you want.


R making dataset

Question: Manufacturer <- c("WARNER","TONYS","TOMBSTONE", "SNYDER", "SHULTZ", "QUAKER", "PRIVATE_LABEL", "POST_FOOD", "P&G", "MKSL", "KING", "KELLOGG", "GENERAL_MI", "FRITO_LAY", "COLGATE", "CHATTEM")
Max <- c(4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4)
Min <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
Price_elasticity <- c(1.343, 3.741, 3.612, 0.7562, 0.6249, 3.393, 0.7283, 1.117, 0.3996, 2.414, 3.024, 3.031, 1.470, 2.416, 0.2536, 1.129)
MANUF_PE <- data.frame(Manufacturer, Min, Max, Price_elasticity)

If I do this I get
  Manufacturer     Min     Max
1   WARNER          0       4      1.3430
2   TONYS           0       4      3.7410
3   TOMBSTONE       0       4      3.6120
4   SNYDER          0       4      0.7562
5   SHULTZ          0       4      0.6249
6   QUAKER          0       4      3.3930
7   PRIVATE_LABEL   0       4      0.7283
8   POST_FOOD       0       4      1.1170
9   P&G             0       4      0.3996
10  MKSL            0       4      2.4140
11  KING            0       4      3.0240
12  KELLOGG         0       4      3.0310
13  GENERAL_MI      0       4      1.4700
14  FRITO_LAY       0       4      2.4160
15  COLGATE         0       4      0.2536
16  CHATTEM         0       4      1.1290

But I was hoping I could get it to look like this :

So I can use it for this radar graph:
library(ggplot2)

radarchart( manu_pe  , axistype=1 ,

            #custom polygon
            pcol=rgb(0.8,0.2,0.5,0.9) , pfcol=rgb(0.8,0.2,0.5,0.4) , plwd=4 , plty=1, ,

            #custom the grid
            cglcol="grey", cglty=1, axislabcol="grey", caxislabels=seq(0,4,1), cglwd=0.2,

            #custom labels
            vlcex=0.8
)

I tried to do it by flipping the dataframe but it wasn't woring... Please help thank you!
Answer: We can reshape it to long format and then convert to 'wide' with names_from the 'Manufacturer' column
library(dplyr)
library(tidyr)
MANUF_PE %>%
    pivot_longer(cols = -Manufacturer) %>%
    pivot_wider(names_from = Manufacturer, values_from = value)
# A tibble: 3 x 17
#  name  WARNER TONYS TOMBSTONE SNYDER SHULTZ QUAKER PRIVATE_LABEL POST_FOOD `P&G`  MKSL  KING KELLOGG
#  <chr>  <dbl> <dbl>     <dbl>  <dbl>  <dbl>  <dbl>         <dbl>     <dbl> <dbl> <dbl> <dbl>   <dbl>
#1 Min     0     0         0     0      0       0            0          0    0      0     0       0
#2 Max     4     4         4     4      4       4            4          4    4      4     4       4
#3 Pric…   1.34  3.74      3.61  0.756  0.625   3.39         0.728      1.12 0.400  2.41  3.02    3.03
# … with 4 more variables: GENERAL_MI <dbl>, FRITO_LAY <dbl>, COLGATE <dbl>, CHATTEM <dbl>

If we need the radarchart
library(fmsb)
library(tibble)
MANUF_PE %>%
    pivot_longer(cols = -Manufacturer) %>%
    pivot_wider(names_from = Manufacturer, values_from = value) %>%
    column_to_rownames("name") %>%
    radarchart(axistype = 1,  pcol=rgb(0.8,0.2,0.5,0.9),
     pfcol=rgb(0.8,0.2,0.5,0.4), plwd=4 , plty=1,  cglcol="grey",
     cglty=1, axislabcol="grey", caxislabels=seq(0,4,1), cglwd=0.2,
     vlcex=0.8 )

If the columns needs to be in a specified order
MANUF_PE %>%
    pivot_longer(cols = -Manufacturer) %>%
    pivot_wider(names_from = Manufacturer, values_from = value) %>%
    arrange(factor(name, levels = c("Max", "Min", "Price_elasticity"))) %>%
    column_to_rownames("name") %>%
    radarchart(axistype = 1,  pcol=rgb(0.8,0.2,0.5,0.9) ,
      pfcol=rgb(0.8,0.2,0.5,0.4) , plwd=4 , plty=1,  cglcol="grey", cglty=1,
       axislabcol="grey", caxislabels=seq(0,4,1), cglwd=0.2, vlcex=0.8 )

Answer: You can use data.table::transpose(). The output will be a regular data.frame if the input is :
data.table::transpose(MANUF_PE,keep.names = "name",make.names = "Manufacturer")
#>               name WARNER TONYS TOMBSTONE SNYDER SHULTZ QUAKER PRIVATE_LABEL
#> 1              Min  0.000 0.000     0.000 0.0000 0.0000  0.000        0.0000
#> 2              Max  4.000 4.000     4.000 4.0000 4.0000  4.000        4.0000
#> 3 Price_elasticity  1.343 3.741     3.612 0.7562 0.6249  3.393        0.7283
#>   POST_FOOD    P&G  MKSL  KING KELLOGG GENERAL_MI FRITO_LAY COLGATE CHATTEM
#> 1     0.000 0.0000 0.000 0.000   0.000       0.00     0.000  0.0000   0.000
#> 2     4.000 4.0000 4.000 4.000   4.000       4.00     4.000  4.0000   4.000
#> 3     1.117 0.3996 2.414 3.024   3.031       1.47     2.416  0.2536   1.129

Answer: As far as the sought data transformation is concerned, a simple R base solution is by using t to transpose columns into rows and vice versa:
t(MANUF_PE)
                 [,1]     [,2]     [,3]        [,4]     [,5]     [,6]     [,7]            [,8]
Manufacturer     "WARNER" "TONYS"  "TOMBSTONE" "SNYDER" "SHULTZ" "QUAKER" "PRIVATE_LABEL" "POST_FOOD"
Min              "0"      "0"      "0"         "0"      "0"      "0"      "0"             "0"
Max              "4"      "4"      "4"         "4"      "4"      "4"      "4"             "4"
Price_elasticity "1.3430" "3.7410" "3.6120"    "0.7562" "0.6249" "3.3930" "0.7283"        "1.1170"
                 [,9]     [,10]    [,11]    [,12]     [,13]        [,14]       [,15]     [,16]
Manufacturer     "P&G"    "MKSL"   "KING"   "KELLOGG" "GENERAL_MI" "FRITO_LAY" "COLGATE" "CHATTEM"
Min              "0"      "0"      "0"      "0"       "0"          "0"         "0"       "0"
Max              "4"      "4"      "4"      "4"       "4"          "4"         "4"       "4"
Price_elasticity "0.3996" "2.4140" "3.0240" "3.0310"  "1.4700"     "2.4160"    "0.2536"  "1.1290"

R making dataset


Are the vector subspaces equal?

Question: Let $v_1, v_2, v_3, v_4$ be elements of a vector space.
Does it hold that $\langle 2v_1, 3v_2, \frac{1}{2}v_2+v_3, -3v_4\rangle=\langle v_1, v_2, v_3, v_3+v_4\rangle$ ?
Or is one of them a subspace of the other?
Comment: What do you mean by "equal"?
Comment: I mean that the sets of the corresponding linear combinations are equal. Can that be? @MichaelMcGovern
Comment: Does it hold that $\langle 2v_1, 3v_2, \frac{1}{2}v_2+v_3, -3v_4\rangle=\langle v_1, v_2, \frac{1}{2}v_2+v_3, v_4\rangle=\langle v_1, v_2, -\frac{1}{2}v_2+\frac{1}{2}v_2+v_3, v_4\rangle=\langle v_1, v_2, v_3, v_4\rangle$ ? @MichaelMcGovern
Comment: So you're asking if the two sets form bases for the same space?
Comment: Yes. @MichaelMcGovern
Comment: What have you tried? What do you know about sets of vectors that form bases for subspaces?
Comment: I tried to write a vector x as a linear combination of both bases. That is opssible, or not? @MichaelMcGovern
Comment: What else do we have to check? @MichaelMcGovern
Answer: Hint: Both are equal to $\langle v_1,v_2,v_3,v_4\rangle$.
In general, with a subspace $U$,  for $\langle a_1,a_2,\dots\rangle\subseteq U$ it's enough to show that each $a_i\in U$, and equality of sets $U=V$ is implied by $U\subseteq V$ and $V\subseteq U$.
Comment: Ah ok! Thank you!! :-)

Are the vector subspaces equal?


How do I get CKEditor to run on my site's textareas?

Question: Basically I was recently recommended CKEditor. My only problem is, I looked all over the site and have been looking on this one as well and cannot seem to find how to actually get the editor to convert my HTML textareas to the editor. I would like to accomplish this with the standard editor.
I have already looked at the support on http://ckeditor.com but couldn't find anything on how to use the editor for some reason.
If you could just show me a page that would explain how to do it or let me know in your comment that would be excellent!
(Answer to question!) Recently I encountered this issue with CKEditor, I was unable to get it to work. I could not locate a guide on how to use it correctly. To use CKEditor on your FTP Server just download the exact Editor you would like here. Now locate the directory where your files were downloaded to. The file you need within the downloads folder should look something like this: ckeditor_4.2_standard.zip. Next, double click the folder ckeditor_4.2_standard.zip, then drag the CKeditor folder to the location where it will be easily accessible. Now all you need to do is upload the CKEditor folder you just moved to the root directory of your website via FTP.
Now, to convert your text areas into the new editor, just paste this code into the head of your HTML page:

(HTML tag within the body of your page)
<textarea class="Reply"></textarea>

Comment: It is surprisingly confusing, but http://docs.ckeditor.com/#!/guide/dev_framed is probably what you're after.
Answer: I would first checkout the installation guide which will help you download everything you need.
http://docs.ckeditor.com/#!/guide/dev_installation
From here you can load it and edit it using these instructions:
http://docs.ckeditor.com/#!/guide/dev_ckeditor_js_load
The basic syntax when creating the editor is to make a field like normal with a name:
<textarea name="editor1"><p>Initial value.</p></textarea>

and then initialize it by calling a replace of a current text area with the CKEditor:


Django generate csv file on view and download

Question: I have this code:
    with open('stockitems_misuper.csv', 'wb') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerows(file_rows)

    response = HttpResponse(myfile, content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=stockitems_misuper.csv'
    return response

I get the error:

I/O operation on closed file

How can I send the created csv file to the front end?
Answer: you're passing the handle of the file being written (and not sure of your indentation, you could just be outside the with block.
Just reopen it in read mode.
with open('stockitems_misuper.csv', 'w', newline="") as myfile:  # python 2: open('stockitems_misuper.csv', 'wb')
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerows(file_rows)

with open('stockitems_misuper.csv') as myfile:
    response = HttpResponse(myfile, content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=stockitems_misuper.csv'
    return response

or better: write to a io.StringIO() instance, and pass that, avoiding to create the file.
import io,csv

buffer = io.StringIO()  # python 2 needs io.BytesIO() instead
wr = csv.writer(buffer, quoting=csv.QUOTE_ALL)
wr.writerows(file_rows)

buffer.seek(0)
response = HttpResponse(buffer, content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=stockitems_misuper.csv'

return response

Comment: that could probably be done, with a custom object having a "read" method, which consumes data from `file_rows` when needed. More complex. If the file is small, not worth it.
Comment: I had to change the import to `from io import BytesIO as StringIO` and `buffer = StringIO()` to make this work, but otherwise great solution!
Comment: that's because you're using Python 2 (in your example you're using "wb" to create the csv file so it has to be python 2, edited)
Comment: wouldn't the buffer hold the complete file_rows within memory and therefore eliminate the advantages of a streaming http response?
Comment: Will this be feasible for very large CSV files? If not then how can I implement it.