Alter date field granularity on exposed filter mid-request

Question: I have an exposed filter on a date value that has it's granularity set to month, so it shows possible year and month values in the form.  If I select just a year, no results are returned, even though I know there are posts that should be retrieved based on the year.  If I then specify a month, all posts from that month and year are returned.
I need to be able to return results from the entire year when just year is selected.  I'm thinking there might be a way to alter the granularity somehow during the request based on whether or not the month was specified?  Any thoughts?
Answer: Working solution thus far:
<code>/**
 * Impliments hook_form_views_exposed_form_alter
 *
 * Used to change exposed date filter to year only, as this is not available in the views UI
 */
function bain_views_form_views_exposed_form_alter(&$form, $form_state)
{
    if( $form['#id'] == 'views-exposed-form-news-items-page')
    {
        // dpm($form_state['input']['date']['value']);
        if (isset($form_state['input']['date']['value'])
            && empty($form_state['input']['date']['value']['month']))
        {
            // Switch date formatter to year only
            $form['date']['value']['#date_format'] = 'Y';
            // Add extra validator to handle filter submit
            $form['#validate'][] = 'bain_views_views_exposed_form_validate';
        }
    }
}

/**
 * Custom validator for exposed date filter
 */
function bain_views_views_exposed_form_validate(&$form, &$form_state)
{
    if ($form['#id'] == 'views-exposed-form-news-items-page')
    {
        $handlers = &$form_state['view']->filter;
        $date_handler = $handlers['field_news_date_value'];
        // dpm($date_handler);
        if (!empty($date_handler->options['exposed'])
            && isset($form['date']['value']['#type'])
            && $form['date']['value']['#type'] == 'date_select'
            && $form['date']['value']['#date_format'] == 'Y')
        {
            $date_handler->options['granularity'] = 'year';
            $date_handler->format = 'Y';
        }
    }
}
</code>


Help in CRLB for linear model

Question: The model is an FIR (MA) filter
$$x(t) = h_1 u(t-1) + h_2 u(t-2) + u(t) \tag{1}$$
$$ y(t) = h^T x(t) + v(t)  \tag{2}$$
$u(t)$  is a pseudo-random binary signal (PRBS) that excites/ drives the process ; and $v(t) = N(0,\sigma^2)$ is the measurement noise.
Q1 : VEctor representation: Is the representation $$y(t) = \mathbf{h^T x(t)} + w(t) \tag{3}$$ correct? Or will it be $$y(t) = \mathbf{h^T u(t)} + w(t) \tag{4}$$
Q2: In Book : Fundamentals of Statistical Signal Processing by Steven Kay, Chapter 4 : Eq(4.21) fives the variance of the estimated coefficients as $var(\hat{h(I)} = \sigma^2/Nr_u[0]$ . Will the CRLB for the MA model be the inverse of this variance when the input $u$ is a PRN sequence? In that case how do I find out $r_u$ in order to implement the formula?
Please help in clearing these problems. Thank you
Comment: Ok, few counterquestions first: 1. Why is there a $h^T$ on (2)?. Should not be $g_1$. 2. Could you paste an image of the paragraph of the book?.
Comment: With that, i would complete the answer below...
Answer: The CRLB Estimator proposed, is just the standard estimator on the MSE conventional sense. There is nothing too strange to worry about. Just follow the cautions here indicated regarding the estimation of MA processes.
Answer 1
The proper representation is:
$$x(t)=b_0 u(t) + b_1 u(t−1)+b_2 u(t−2)+v(t)$$
that is:
$$x(t)=\mathbf{u(t)b} + w(t)$$
or:
$$\mathbf{x=H \theta + w}$$
This is an ARMAX model with no autoregressive (AR) order, $n_a$=0, two moving average (MA) orders, $n_b=2+1$, and white noise $w=N(0,\sigma^2)$. $H$ is the matrix of observations from $u(0)...u(n)$.
Answer 2
The expression on the document on p.37 are somehow incorrect, on the sense the matrix $H(t)^TH(t)$ depends on time. For making the estimator MVU (Minimum Variance & Unbiased), in the sense of the slides presented,

Ensure the measurement over a large $t$ in order to reduce the impact of the initial conditions on the Parameter Estimation:
$$t -> \inf$$
so
$$H(t)^TH(t)$$ is not triangular (just as $H(0)^TH(0)$ is), but tends to diagonal.

Ensure an i.i.d. random white-noise (RN) input:
$$u(t)=N(0,\sigma_u)$$
Thus by definition of i.i.d., the autocorrelation of the input will be:
$$r_{uu}(0)=\sigma_u^2$$
$$r_{uu}(\tau)|_{\tau<>0}=0$$
Qualitatively and theoretically there is little difference between a perfect and a pseudo white noise, as the i.i.d. is a stronger abstraction than the perfection of the whiteness for these identically and independency.

Build the matrix $H(t)^TH(t)$ and construct the estimators:
$$\theta=(H(t)^TH(t))^{-1}H(t)^Tx(t)$$
$$C_{\theta}=\sigma^2(H(t)^TH(t))^{-1}$$

Cheers...
Comment: The standard estimate
$$θ=(H(t)^TH(t))^{−1}H(t)^Tx(t)$$
is built from H(t) rows as
^$$H(t,:)=[u(t−2)u(t−1)u(t)]$$
, with as many $t$s as data is available, provided that $t$ is not close to the initial condition.
Comment: Check the answer.
Comment: I am a bit confused by your current background and the question itself. The EM Kalman, the CRLB Estimate and the slides document are three difficult level kind of objects. WHich one do you desire to be explained?. According the slides, the CRLB estimate is just.. the standard one. The EM estimate is another story.
Comment: The matrix H(1000) is then built for example as: $H=[u(998) u(999) u(1000); u(997) u(998) u(999);...;u(98) u(99) u(100)]$...
Comment: The u(t) for identification purposes is a white noise (Pseudo Random Noise, PRN) $u=randn(1000,1)$

Help in CRLB for linear model


Why is $\sqrt[n]{a}$ equal to $a^{1/n}$ only when $n\ge 2$?

Question: My teacher gave us the following logarithmic equation to solve for $x$.

$\log 4$ + $(1+1/(2x))\log 3$ = $\log(\sqrt[x]{3} + 27)$

As you can see it involves the term $\sqrt[x]{3}$, which later in the solution was converted into $3^{1/x}$. The values of $x$ obtained were $1/4$ and $1/2$. However my teacher said these two values were to be rejected, citing this "rule"; $\sqrt[n]{a}$ is equal to $a^{1/n}$ only when $n\ge 2$. Why is this so? My teacher didn't provide any reasoning for this and told us just to remember this rule and apply it accordingly.
Comment: @JohnTony The usual definition of $\sqrt[n]{x}$ is the $n^{th}$ root of $x$ where $n \in \mathbb N$. By that definition $\sqrt[1]{x} = x$ is redundant, so $n=1$ is never actually used. Which leaves $n \ge 2$.
Comment: Is it $1/(2x)$ or $(1/2) \cdot x$?
Comment: @Gary oh brother, the infamous social media problem :D
Comment: @JohnTony That's not a technicality, it's intrinsic to the definition of $\sqrt[n]{x}$. If the question uses $\sqrt[n]{3}$ then it's about a positive integer $n \ge 2$. If it used $3^{1/n}$, instead, without a stated constraint on $n$ then it would be a different question.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: @Gary I fixed it but it isn't really relevant to the question.
Comment: @dxiv I see. However it seems strange to me that this technicality is sufficient to reject these values of x as solutions.
Comment: For me $\sqrt[n]x=x^{1/n}$. But in the context of complex numbers it can mean a specific analytic branch of $x^{1/n}$.
Answer: $\sqrt[n]{x}$ is typically treated as equivalent to $x^{\frac{1}{n}}$, as seen in symbolic solvers such as WolframAlpha.
However, there is a lot of convention needed to be taken into account. Typically, the radical is used when dealing with $n\in\mathbb{N}$. As dxiv pointed out, the case when $n=1$, i.e; $\sqrt[1]{x}$ is redundant, so we're left with the cases when $n\geq2$.
Personally, I use them interchangeably, so will your calculator. We can presume $\sqrt[\sqrt{2}]{x}$, for example, should be treated not so differently to $x^{\frac{1}{\sqrt{2}}}$. Obviously, the latter notation is preferred in this case.
I know some mathematicians differentiate the use in complex analysis, for instance. It's convention to use the radical only when referring to a principal root, and $\frac{1}{n}$ when dealing with other branches.
Should you be docked marks for using them interchangeably? Probably not.
Will it affect calculation? If in your calculation separate branches need to be taken into account, or the more likely scenario, the condition that $n\in\mathbb{N}$ is implied, as seems to be the case in the eyes of your teacher.


For positive, decreasing $a_n$, must $a_n=O(1/n)$ for the series $\sum_{n=1}^{\infty} a_n$ to converge?

Question: If $a_n$ is a sequence of decreasing positive numbers, must $a_n=O(1/n)$ for the series $\sum_{n=1}^{\infty} a_n$  to converge? I think it's true but a proof eludes me. My ideas so far:
Suppose it's not true, then for all $C>0$ and for all $N \in \mathbb{N}$ there exists $n \geq N$ such that $a_n>C/N$. Take $C=1$. Let $n_k$ be a sequence such that $a_{n_k}>1/n_k$.

If the $n_k$ are close together then the series clearly won't converge (since $\sum_{n=1}^{\infty} 1/n$ diverges)
If the $n_k$ are all say a constant $M$ apart, so $n_k=Mk$, then the series will diverge since $\sum_{n=1}^{\infty} 1/a_n \geq \sum_{k=1}^{\infty} M \cdot(1/Mk)=\infty$
If the $n_k$ are rapidly getting further and further apart then
$$\sum_{n=1}^{n_k} =\sum_{n=1}^{n_1} a_n + \sum_{n=n_1}^{n_2} a_n +...+\sum_{n=n_{k-1}}^{n_k} a_n \geq \frac{n_1}{n_1}+\frac{n_2-n_1}{n_2}+....+\frac{n_k-n_{k-1}}{n_k} \approx k. $$

So these three cases lead me to believe it is true but I don't know how to prove it. Any help would be appreciated. It seems like there should be a simple proof of this.
Comment: What about $a_n=\frac1{\sqrt n}\cdot[\text{$n$ is a power of $2$}]$ ? EDIT: I missed "non-decreasing".
Comment: @YvesDaoust Technically, $a_{n}=\frac{1}{n^{2}}$ is $O\left(1/n\right)$ since $\frac{1}{n^{2}}\leq \frac{1}{n}$ for all $n\geq1$, and the series $\sum\frac{1}{n^{2}}$ converges.
Comment: @Brian: you are right. I need some rest.
Comment: @YvesDaoust OP was asking must $|a_{n}|\leq \frac{k}{n}$ for some positive k in some tail of a convergent series with the $a_{n}$ decreasing. Restated once again for clarity: If the series converges and $a_{n}$ is decreasing, then $|a_{n}|\leq \frac{k}{n}$ for some positive k in some tail of the sequence $a_{n}$. At least that is how I am reading the question as currently stated.
Answer: Actually, one even has $a_n=o(1/n)$ (if $a_n$ is positive decreasing). Indeed, let $k$ be the integer part of $n/2$: then $\sum_{i=k}^{n}{a_i} \rightarrow 0$, and $0\leq \frac{na_n}{2} \leq (n-k+1){a_n} \leq \sum_{i=k}^n{a_i}$, so it follows $na_n \rightarrow 0$.
Comment: What about $a_n=\frac1{\sqrt n}\cdot[\text{$n$ is a power of $2$}]$ ? (Nevermind after the edit.)
Comment: The OP states that $a_n$ must be decreasing.
Comment: ahhhh sorry, missed that
Comment: Nice proof, thanks!
Answer: Assume the sum converges to $L>0$ and that $a_n\neq O(1/n)$. Then there are infinite natural numbers $\{N_k\}_{k=1}^\infty$ such that
$$a_{N_k}>\frac{2L}{N_k}$$
But then for any of the naturals in this sequence (denoted just by $N$ at this point)
$$L=\sum_{n=1}^\infty a_n>\sum_{n=1}^{N}a_n\geq \sum_{n=1}^{N}a_{N}>\sum_{n=1}^{N}\frac{2L}{N}=N\frac{2L}{N}=2L$$
Since this is a contradiction, we conclude $a_n=O(1/n)$$
Comment: No, there are no infinite natural numbers! Every natural number is finite. There are _infinitely many_ natural numbers such that etc.
Answer: Correct me if I am wrong, but wouldn't $a_1=2$, $a_n=\sqrt{a_{n-1}}$ for all n>1 violate your conjecture?
Comment: $\sum_{n=1}^\infty a_n$ doesn't seem to converge here, though?
Comment: The wording of the question maybe tripped you up you can restate the question as an if then statement like so: If the series converges and $a_{n}$ is decreasing, then $|a_{n}|\leq \frac{k}{n}$ for some positive k in some tail of the sequence $a_{n}$. At least that is how I am reading the question as currently stated.


Simplifying Nested Try Catch in Python

Question: I'm stuck on this problem. I'm not necessarily looking for code snippets here, but maybe a higher-level concept of how what I'm trying to do can be engineered.
I have a list of PDF files of different "types". The different type don't contain the same information and are not formatted in the same way. Based on the type of the PDF, I need to extract information from them differently. To do this, I use two Python libraries that allow me to extract data in different ways from the PDF files.
The issue is that I could for instance recognize PDF_1 by looking at index [10] in a Dataframe, while when reading PDF_2, there is no index [10], so I get an IndexError.
Right now, my brute force solution is doing something like below. But this is not doable, because in reality I have many more types of PDF files, and this is extremely unscalable/unreliable
for file in os.listdir("all file"):
    if file.endswith(".pdf"):
        content = tab.read_pdf('file/'+file, pages='all', guess=False, stream=True)
        # checks for PDF_1
        try:
            if content[1].columns[10] == 'String identifying PDF 1':
                extract_pdf_1()
                print(file + ' is pdf 1')

        # checks for PDF_2
        except:
            try:
                if content.loc[4].str.contains("String identifying PDF 2").all():
                    extract_pdf_2()
                    print(file + ': is pdf 2')
            except:
                print('pdf not recognised')

Comment: I don't know if this is only a mistake here but  the try and except expressions should be on the same level of indentation... In my opinion recognising different types of pdf shouldn't be done in the try catch blocks (especially if you have a lot of different types) You can use if statement and firstly check the length of the array... or find other way to distinguish pdfs
Comment: what are the differences between the types?
Comment: They are formatted completely differently. So during the data extraction process, the output will not be the same.
Answer: It can be done like this:
def check_pdf_1(content):
    try:
        if content[1].columns[10] == 'String identifying PDF 1':
            return True
    except SpecException as e:
        return False
...
pdf_handlers= {
    1: (check_pdf_1, extract_pdf_1),
    2: (check_pdf_2, extract_pdf_2),
}
...
for file in os.listdir("all file"):
    if file.endswith(".pdf"):
        content = tab.read_pdf('file/' + file, pages='all', guess=False, stream=True)
        for check_pdf, extract_pdf in pdf_handlers.values():
            if check_pdf(content):
                extract_pdf(content)
                break

Answer: You can create different functions that recognizes each type of pdf, and return "true" or "false" if you find it. In addition you need another function which calls each check-type until it finds a "true" return value. You don't need nested try-check, you can separate them on each function (having all in the same level).
def check1():
    try:
        if content[1].columns[10] == 'String identifying PDF 1':
            extract_pdf_1()
            print(file + ' is pdf 1')

    except:
        return False

def check2():
    try:
        if content.loc[4].str.contains("String identifying PDF 2").all():
            extract_pdf_2()
            print(file + ': is pdf 2')
    except:
        return False

def checks(content):
    if (check1(content)):
        return
    if (check2(content)):
        return

for file in os.listdir("all file"):
    if file.endswith(".pdf"):
        content = tab.read_pdf('file/'+file, pages='all', guess=False, stream=True)
        checks(content)

Simplifying Nested Try Catch in Python


access oracle enterprise manager from client

Question: Somebody can tell me how to enable oracle enterprise manager to access from a client?
I install Oracle Express 188.8.131.52.0 in a Centos 7 vm.
Now I access to oracle em by browser on url https://localhost:5500/em from my client throw a ssh putty tunnel If I try from my client a telnet to linux server on 5500 the connection is refused and if i try telnet localhost 5500 the connection is ok.
I've disabled selixux and firewall
What can I do to enable access from an IP pool?
Thanks in advance. Raffaele
Edit:
The output of ss -tlnp is
[root@osboxes ~]# ss -tlnp
State      Recv-Q Send-Q    Local Address:Port                          Peer Address:Port
LISTEN     0      128       127.0.0.1:631                      *:*    users:(("cupsd",pid=1257,fd=12))
LISTEN     0      100       127.0.0.1:25                        *:*    users:(("master",pid=1708,fd=13))
LISTEN     0      128       127.0.0.1:5500                    *:*    users:(("tnslsnr",pid=2458,fd=16))
LISTEN     0      128             *:111                             *:*    users:(("rpcbind",pid=742,fd=4),("systemd",pid=1,fd=46))
LISTEN     0      5           192.168.122.1:53                *:*    users:(("dnsmasq",pid=1786,fd=6))
LISTEN     0      128             *:22                                *:*    users:(("sshd",pid=1258,fd=3))
LISTEN     0      128        [::1]:631                          [::]:*    users:(("cupsd",pid=1257,fd=11))
LISTEN     0      100        [::1]:25                            [::]:*    users:(("master",pid=1708,fd=14))
LISTEN     0      128          [::]:19585                      [::]:*    users:(("ora_d000_xe",pid=2541,fd=9))
LISTEN     0      128          [::]:111                          [::]:*    users:(("rpcbind",pid=742,fd=6),("systemd",pid=1,fd=48))
LISTEN     0      128          [::]:1521                        [::]:*    users:(("tnslsnr",pid=2458,fd=8))
LISTEN     0      128          [::]:22                            [::]:*    users:(("sshd",pid=1258,fd=4))

in oracle xe 18c I found listener.ora file in /opt/oracle/product/18c/dbhomeXE/network/admin/listener.ora.
The file not contains this configuration.
    # listener.ora Network Configuration File: /opt/oracle/product/18c/dbhomeXE/network/admin/listener.ora
# Generated by Oracle configuration tools.

DEFAULT_SERVICE_LISTENER = XE

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = osboxes)(PORT = 1521))
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

I try a "grep -r 5500 *" in /opt/oracle but I found nothing to help me.
In file diag/tnslsnr/osboxes/listener/trace/listener.log there is this log message
diag/tnslsnr/osboxes/listener/trace/listener.log:Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=127.0.0.1)(PORT=5500))(Security=(my_wallet_directory=/opt/oracle/admin/XE/xdb_wallet))(Presentation=HTTP)(Session=RAW))

Thanks in advance
Comment: Could you please add the output of `sudo ss -tlnp`?
Comment: Thanks, I add a new answer because the output of the command is too long.
Comment: On this site, we are editing the question and add additional info there. This site is not designed like a discussion forum, but like a Question/Answers site.
Answer: In the following line you can see that tnslsnr is listening on 127.0.0.1:5500. The IP address 127.0.0.1 is assigned to lo (loop back) interface. This means that only local programs can directly access this service.
LISTEN     0      128       127.0.0.1:5500                    *:*    users:(("tnslsnr",pid=2458,fd=16))

You need to find a file called listener.ora that is located in $ORACLE_HOME/network/admin/ directory. Here you need to change the HOST = from localhost or 127.0.0.1 to an IP address that is assigned to an external interface like Ethernet.
Restart the listener after you change that file. You can see  the status with: lsnrctl status. Consult Oracle documentation for tnslsnr for more details.


filter based on user reference

Question: I have a content type "book" that has an entity reference field that references users and pulls in a name.  Users also has fields for a picture and an author website.
I would like to add a block at the bottom of each book node that shows the author picture and website.
What is the correct way to set up the relatioknship and filter when there is no user ID in the URL?
Answer:
Set up the relationship. Under the Relationships section click + to add a relationship.

Under "Add relationships" you will see all fields listed.
Drop down the Groups menu and select "Content".
Locate your node reference field, for example 'Content: Reference user (field_reference_user)'. Check the box to the left of it.
Click the Add button.
Check the box labeled 'Require this relationship', and click the Update button.

Add a Contextual filter for Node ID. Set the default value -> get ID from URL
Add a field. Click + next to Fields. Under Groups, select Node, and choose Node: Title. Under Relationship, select your node reference field, e.g., Reference user, click Update.

Create a view on a node reference field will explain you in detail
Comment: Thanks you.  But there is no ID in the URL...  Doesn't that matter?
Comment: if it's node page then the URL would be node/nid.. Even if you use path alias.. arg(1) will be nid.
Comment: Yes, but the node iD does not related to the user ID?  I will try.  Maybe that's my problem. I am expectuing there to be a relationship beyween the user ID and the selection I am making in the arguments
Comment: And actually, Node is isn't an option with a view or users.  :)

filter based on user reference


Separar a soma com um " " em c#

Question: Quero poder definir os valores do vetor sem  dae uma quebra de linha.
quero que fique dessa forma: 255 2255 25
<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BigSum
{
    internal class Program
    {
        static void Main(string[] args)

        {
            long n = long.Parse(Console.ReadLine());
            long[] BigSum = new long[n];

            for (int i = 0; i < n; i++)
            {
                BigSum[i] = long.Parse(Console.ReadLine());
            }

            long sum = 0;

            for (int i = 0; i < n; i++)
            {
                sum += BigSum[i];

            }

            Console.WriteLine(sum);

        }
    }
}
</code>
Comment: É só ler a entrada do usuário, fazer a quebra por espaço(s) e depois converter cada item quebrado em número...
Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: Se for oque voce quer pode ser assim:
Console.WriteLine(" "+ sum +" ");
Comment: O autor da pergunta quer saber como ler os vários valores para um vetor em uma única chamada de `Console.ReadLine()`.
Comment: Isto não responde à pergunta. Quando você tiver [reputação](https://pt.stackoverflow.com/help/whats-reputation) suficiente, você vai poder deixar [comentários em qualquer publicação](https://pt.stackoverflow.com/help/privileges/comment), mas, até lá, escreva apenas respostas que não [dependam de mais informações de quem perguntou](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [Da Revisão](/review/low-quality-posts/445911)

Separar a soma com um " " em c#


In table tennis, can you serve from the side of the table provided the ball is being hit from outside of the playing surface

Question: Now I know that in TT, you have to serve the ball from behind the table and above the playing surface. My question is, can I stand sideways to the Table and make the serve provided my ball is still outside the table as shown in the image below?
Answer: As the ITTF rules state :

From the start of service until it is struck, the ball shall be above the level of the playing surface and behind the server's end line, and it shall not be hidden from the receiver by the server or his or her doubles partner or by anything they wear or carry.

There's no mention of where your body has to be positioned during that part of the game, so parts of your body can be over the playing area, or as you are asking along the side of the area. The only thing that matters is the position of the ball itself.
If you need more info about this, I encourage you to check out this link : http://www.allabouttabletennis.com/official-table-tennis-rules.html


How do I read a property file present in another package with Resource Bundle?

Question: User file location
Property File locationI have a property file in one package named EnotebookCore, but I have to read it in another package named User in one of its java file. When the property file was in one other folder of the same package i.e. User, I gave the full path of the property file in java file(present in another folder)and it was working fine. But now I am supposed to shift property file to a new package and I am unable to read it from there.
Comment: Please, post the code you are using
Comment: When the file was in a folder in User package, i could read it from one folder languages to other folder bean in userBean , java file by the following code :
ResourceBundle bundle = ResourceBundle.getBundle("com.sial.enotebook.user.languages.user", Locale.US);
Comment: Is it a property file or a class?
Comment: it is a property file
Comment: Post the folder structure, please...the class package and the properties location
Comment: @BrunoDM I have added links in my question for properties and file location
Answer: When you say
ResourceBundle.getBundle("com.sial.enotebook.user.languages.user", Locale.US);

Java will look in the package com.sial.enotebook.user.languages for a bundle called user. More exactly it will look in the folder com/sial/enotebook/user/languages for a property file named user_US.properties or user.properties
In your case, make sure that the .properties file is named correctly (including case) and sits in the correct package. For example, if the bundle name is Messages (capital M) and sits in the com.sial.enotebook package, you need to have a Messages.properties file in the com/sial/enotebook folder and use the following:
ResourceBundle.getBundle("com.sial.enotebook.Messages", Locale.US);

Comment: Thank you ! But this is working for me. In my current project I need the files location to be from it's class path.
Comment: The file is always read from the classpath. You have to create the correct package structure (i.e. folder structure) on your classpath. If you place your .properties file in the same folder as your .java class, then it will sit in the same package as the class.
Comment: can you please check the links I have provided in my question for folder structure
Comment: Try to put it in the resources folder, i.e. resources/com/sial/enotebook/languages/user.properties. Otherwise, it's possible that it doesn't get copied to the output folder.


Where to place Dlls in version control visual studio

Question: My Current structure is as follows

/Project Name/
file1.cs
file2.cs
project.sln
Libraries/

I know the common answer is to put a Libraries folder within the /Project Name/ folder as shown above. Is this correct?
If so, do I need to do anything special when adding the references in my project? What do I need to set for the "Copy Local" option? Thanks.
Answer: For an answer to the first question, see Location of Third Party Dll's in Version Control for .NET Project.
For your second question: nothing special needs to be done; adding a Reference in Visual Studio (using the Browse tab) will automatically set up the assembly DLL to be copied to the output folder.


Half-life time computation, and percentage of isotope remaining after X years.

Question: The half-life of a certain radioactive substance is 1400 years. What is the percentage of radioactive isotopes still present after 700 years? The reference solution of my book is: 80.8%
Thank you very much for considering my request.
Answer: If you start out with an amount of radioactive material with half-life $T$denoted by $N_0$, then the amount remaining at time $t$, denoted by $N(t)$, is given by:
$$N(t) = N_0\cdot (\frac{1}{2})^{(\frac{t}{T})}$$
The percentage of radioactive material left at a given time is given by:
$$\frac{N(t)}{N_0} \times 100\%$$
Can you proceed from there?
By the way, I don't agree with your book's reference solution.
Answer: Of course this is dead wrong. If we have $80.8\%$ after $700$  years, then we have $(0.808)^2$ of the initial amount after $1400$ years, and that is definitely not $\frac{1}{2}$ of the initial amount.
In $1400$ years, the amount shrinks to $\frac{1}{2}$, so the amount at time $t\ge 0$ is $A\times 2^{-t/1400}$, where $A$ is the initial amount.
So the amount after $700$ years is $A\times 2^{-700/1400}$, which is about $70.7\%$ of the initial amount.
Comment: I think you mean  $A\times (\frac{1}{2})^{700/1400}$
Comment: Sure do! Thanks for spotting it.


Why doesn't Lisp-Stat load with quicklisp under MacOS?

Question: I'm relatively new to Common Lisp and Lisp-Stat. But I wanted to try it out and play around with it in my empirical social research.
Unfortunately installing LISP-Stat fails at building.
My Setup
SBCL 2.2.8 / Emacs 28.1 (Doom Emacs Config) / SLIME 2.27 / all on MacOS Monterey 12.6
What I tried:
<code>(ql:quickload :lisp-stat)</code>
Error Message
<code>; Loading "lisp-stat"
;   caught 1 fatal ERROR condition
Building #P"/Users/stefan/common-lisp/cephes.cl/scipy-cephes/libmd.so"
gcc -g -O2 -Wall -Wno-unused-function -fno-builtin -fPIC -include cephes.h -include math.h   -c -o cbrt.o cbrt.c
</code>
Full Backtrace
<code> 0: ((:METHOD NO-APPLICABLE-METHOD (T)) #<STANDARD-GENERIC-FUNCTION ASDF/SESSION:SESSION-CACHE (1)> NIL) [fast-method]
 1: (SB-PCL::CALL-NO-APPLICABLE-METHOD #<STANDARD-GENERIC-FUNCTION ASDF/SESSION:SESSION-CACHE (1)> (NIL))
 2: (ASDF/SESSION:CALL-WITH-ASDF-SESSION #<FUNCTION (LAMBDA NIL :IN ASDF/OPERATE:OPERATE) {1002DF771B}> :OVERRIDE NIL :KEY NIL :OVERRIDE-CACHE NIL :OVERRIDE-FORCING NIL)
 3: ((:METHOD ASDF/OPERATE:OPERATE :AROUND (T T)) ASDF/LISP-ACTION:LOAD-OP "lisp-stat" :VERBOSE NIL) [fast-method]
 4: (ASDF/OPERATE:LOAD-SYSTEM "lisp-stat" :VERBOSE NIL)
 5: (QUICKLISP-CLIENT::CALL-WITH-MACROEXPAND-PROGRESS #<FUNCTION (LAMBDA NIL :IN QUICKLISP-CLIENT::APPLY-LOAD-STRATEGY) {1002DF6AAB}>)
 6: (QUICKLISP-CLIENT::AUTOLOAD-SYSTEM-AND-DEPENDENCIES "lisp-stat" :PROMPT NIL)
 7: ((:METHOD QL-IMPL-UTIL::%CALL-WITH-QUIET-COMPILATION (T T)) #<unused argument> #<FUNCTION (FLET QUICKLISP-CLIENT::QL :IN QUICKLISP-CLIENT:QUICKLOAD) {1002CBDA4B}>) [fast-method]
 8: ((:METHOD QL-IMPL-UTIL::%CALL-WITH-QUIET-COMPILATION :AROUND (QL-IMPL:SBCL T)) #<QL-IMPL:SBCL {1004C6D5C3}> #<FUNCTION (FLET QUICKLISP-CLIENT::QL :IN QUICKLISP-CLIENT:QUICKLOAD) {1002CBDA4B}>) [fast-m..
 9: ((:METHOD QUICKLISP-CLIENT:QUICKLOAD (T)) :LISP-STAT :PROMPT NIL :SILENT NIL :VERBOSE NIL) [fast-method]
10: (QL-DIST::CALL-WITH-CONSISTENT-DISTS #<FUNCTION (LAMBDA NIL :IN QUICKLISP-CLIENT:QUICKLOAD) {1002CAF0CB}>)
11: (SB-INT:SIMPLE-EVAL-IN-LEXENV (QUICKLISP-CLIENT:QUICKLOAD :LISP-STAT) #<NULL-LEXENV>)
12: (EVAL (QUICKLISP-CLIENT:QUICKLOAD :LISP-STAT))
13: ((LAMBDA NIL :IN SLYNK-MREPL::MREPL-EVAL-1))
14: (SLYNK::CALL-WITH-RETRY-RESTART "Retry SLY mREPL evaluation request." #<FUNCTION (LAMBDA NIL :IN SLYNK-MREPL::MREPL-EVAL-1) {1002CAE0AB}>)
      Locals:
        MSG = "Retry SLY mREPL evaluation request."
        THUNK = #<FUNCTION (LAMBDA () :IN SLYNK-MREPL::MREPL-EVAL-1) {1002CAE0AB}>
15: ((LAMBDA NIL :IN SLYNK-MREPL::MREPL-EVAL-1))
16: ((LAMBDA NIL :IN SLYNK::CALL-WITH-LISTENER))
17: (SLYNK::CALL-WITH-BINDINGS ((*PACKAGE* . #<PACKAGE "COMMON-LISP-USER">) (*DEFAULT-PATHNAME-DEFAULTS* . #P"/Users/stefan/Nextcloud/Dokumente/eBooks/03_Technik/Programmieren/Lisp/") (*) (**) (***) (/) ...
18: (SLYNK-MREPL::MREPL-EVAL-1 #<SLYNK-MREPL::MREPL mrepl-1-1> "(ql:quickload :lisp-stat)")
19: (SLYNK-MREPL::MREPL-EVAL #<SLYNK-MREPL::MREPL mrepl-1-1> "(ql:quickload :lisp-stat)")
20: (SLYNK:PROCESS-REQUESTS NIL)
21: ((LAMBDA NIL :IN SLYNK::SPAWN-CHANNEL-THREAD))
22: ((LAMBDA NIL :IN SLYNK::SPAWN-CHANNEL-THREAD))
23: (SLYNK-SBCL::CALL-WITH-BREAK-HOOK #<FUNCTION SLYNK:SLYNK-DEBUGGER-HOOK> #<FUNCTION (LAMBDA NIL :IN SLYNK::SPAWN-CHANNEL-THREAD) {1001A9800B}>)
24: ((FLET SLYNK-BACKEND:CALL-WITH-DEBUGGER-HOOK :IN "/Users/stefan/.emacs.d/.local/elpa/sly-20220713.1433/slynk/backend/sbcl.lisp") #<FUNCTION SLYNK:SLYNK-DEBUGGER-HOOK> #<FUNCTION (LAMBDA NIL :IN SLYNK:..
25: ((LAMBDA NIL :IN SLYNK::CALL-WITH-LISTENER))
26: (SLYNK::CALL-WITH-BINDINGS ((*PACKAGE* . #<PACKAGE "COMMON-LISP-USER">) (*DEFAULT-PATHNAME-DEFAULTS* . #P"/Users/stefan/Nextcloud/Dokumente/eBooks/03_Technik/Programmieren/Lisp/") (*) (**) (***) (/) ...
27: ((LAMBDA NIL :IN SLYNK::SPAWN-CHANNEL-THREAD))
28: ((FLET SB-UNIX::BODY :IN SB-THREAD::RUN))
29: ((FLET "WITHOUT-INTERRUPTS-BODY-11" :IN SB-THREAD::RUN))
30: ((FLET SB-UNIX::BODY :IN SB-THREAD::RUN))
31: ((FLET "WITHOUT-INTERRUPTS-BODY-4" :IN SB-THREAD::RUN))
32: (SB-THREAD::RUN)
33: ("foreign function: call_into_lisp_")
34: ("foreign function: funcall1")
</code>
Why doesn't it compile? Any help very appreciated.
Answer: Cephes had a problem where it wasn't loading on MacOS which has been corrected as of 2022-10-13.
Quicklisp has been a bit slow in updating as of late, and you don't want to use the version that's there now.  A better bet is to get the source code and then go from there.
Comment: Thank you for the tip. Cloned the repositories, ran `(asdf:load-system :lisp-stat)` but still get the same error when building cephes. `Building #P"/Users/stefan/common-lisp/cephes.cl/scipy-cephes/libmd.so"
; Debugger entered on #`
Comment: This is likely a problem in building the shared library on MacOS.  I don't have a darwin machine to test on, but what you need to do is figure out the flags to produce a shared library (it won't be .so, I believe they are .dylib extensions).


XmlDocument Exception: valor hexadecimal 0x1a, é um caractere inválido

Question: Tenho um projeto que lê um XML gerado por outro programa na qual eu não tenho acesso ao código fonte. O problema é que o XML gerado vem com um caractere especial no final, e quando vou tentar ler o XML a exception é lançada.
Segue o código:
XmlDocument xmlDoc = new XmlDocument();
try
{
   xmlDoc.Load(localMontaXML);
}
catch (Exception ex)
{
   erros.Add(ex.Message);
}
ErrorChecker.Check(erros);

Têm alguma forma de ignorar esse caractere?
Utilizo Windows Forms com .Net 3.5
Comment: Você poderia editar o arquivo com `StreamWriter` e remover esse caractere antes de abrir como um `XmlDocument`
Answer: Tem sim cara, mas antes você deve considerar a possibilidade de o arquivo estar vindo corrompido ou algo do tipo. Se você tem certeza que este arquivo está íntegro, e que apenas existe um caractere inválido no final por alguma razão desconhecida (?), você pode jogar o arquivo em memória exceto o último caractere, obtendo o seu xml válido.
Existem duas formas que eu conheço de fazer isso. Observe o código a seguir:
METODO 1
using (MemoryStream ms = new MemoryStream()) // cria um stream de memória
using (var fs = new FileStream(@"C:\sample.xml", FileMode.Open, FileAccess.Read))
// abre o arquivo xml. No caso C:\sample.xml
{
    byte[] bytes = new byte[fs.Length]; // onde ficará o conteúdo do arquivo - 1
    fs.Read(bytes, 0, (int)fs.Length); // lê o arquivo
    ms.Write(bytes, 0, (int)fs.Length-1); // escreve tudo exceto o último byte (length - 1)

    ms.Seek(0, SeekOrigin.Begin); // volta para o início do stream

    XDocument doc = XDocument.Load(ms); // carrega o arquivo em memória
    Console.WriteLine(doc.Root.Value); // teste de leitura
}

METODO 2
using (var fs = new FileStream(@"C:\sample.xml", FileMode.Open, FileAccess.Read))
// cria um arquivo mapeado em memória a partir do seu FileStream
using (var mmf = MemoryMappedFile.CreateFromFile(fs,"xml",fs.Length,MemoryMappedFileAccess.Read,null,System.IO.HandleInheritability.None,true))
{
    // cria um stream que enxerga até o final do arquivo - 1
    using (var str = mmf.CreateViewStream(0, fs.Length - 1, MemoryMappedFileAccess.Read))
    {
        XDocument doc = XDocument.Load(str); // lê a partir do stream
        Console.WriteLine(doc.Root.Value);
    }
}

O segundo utiliza Memory-Mapped Files.
Um detalhe é que estes métodos copiam o conteúdo do arquivo para a memória, não é a coisa mais performática do mundo então tome cuidado ao fazer isso com um XML grande, e nunca se esqueça dos using para "descartar" seus Stream após o uso.
Boa sorte e espero ter ajudado.
Answer: Boa resposta @Conrad Clark
Tenho uma terceira sugestao caso nao se saiba quantos caracteres a mais o ficheiro tem no fim.
xmlDoc.LoadXml(System.Text.RegularExpressions.Regex.Match(localMontaXML, @"<[\w\W]+>").ToString());
Answer: No meu caso, o erro que ocorreu foi similar hexadecimal value 0x00, is an invalid character, talvez a solução seja proxima, mudando apenas o caracter a ser substituido no final.
Quando ocorreu o erro estava assim:
xmlObj = new XmlDocument();
xmlObj.Load(arquivo.fullPath);

A correção foi:
StreamReader sr = arquivo.OpenText(); //carrega o texto do arquivo
string xmlText = sr.ReadToEnd(); //lê o texto do arquivo e salva na variavel xmlText
xmlText = xmlText.Replace("\0", string.Empty); // retira os caracteres nulos;
xmlObj = new XmlDocument(); // cria o xml
xmlObj.LoadXml(xmlText); // Carrega a string diretamente para ser lida como xml

Espero que possa ajudar.


Firing ajax_callback on textfield after a minimum number of character

Question: Ive created a textfield with an ajax callback with 'keyup' event.
In need the callback function to be fired only after a certain number of character ...
I can control the number of character of the input in the callback function, but this is not the way I want it...
There's maybe a javascript way to avoid the callback to be fired before 5 character ?
My form field :
<code>        $form['myitem'] = array(
          '#type' => 'textfield',
          '#size' => 6,
          '#maxlength' => 5,
          '#default_value' => '',
          '#name' => "my_name",
          '#disabled' => FALSE ,
            '#ajax' => array(
                'callback' => 'mymodule_mycallback_ajax_callback',
                'wrapper' => "mywrapper",
                'method' => 'replace',
                'event' => 'keyup',
                'progress' => array('message' => NULL),
            ),
        );
</code>
Answer: One option is to use a custom jQuery event, eg. something like "startajaxCall". Set $form['my_input']['#ajax']['event'] = 'startajaxCall' and provide some JS to trigger your custom event after an appropriate number of keys is entered.
Comment: Hmmm seems nice ...Im going to test it and report to you after , thanks!
Comment: Did this solotion work out for you?
Answer: I also faced same challenge in one my project. Fixed it by below logic.

// Update the event to change instead of keyup.

<code> 'event' => 'change',
</code>

// Add below js line.

<code>  // Trigger ajax event on myitem only after 5th character typed.
  $('.myitem-class').on('keyup', function() {
    if ($(this).val().length == 5) {
      $(this).trigger('change');
    }
  });
</code>


Calculate type I and II error - solution verification

Question: There are 7 balls in urn. $Q$ of them are white and the rest are black. We have hypothesis $H_0:Q=3$ and $H_1:Q=5$. To test this we draw 2 balls (balls don't come back to the urn - i.e. they are drawn without replacement).
We reject $H_0$ when both balls drawn are white. Calculate probability of type I and type II errors.
MY PROBLEM - what are probabilities of $H_0$ and $H_1$? Are they actually needed?
SOLUTION SKETCH:
Let $x$ be number of drawn white balls.
$\alpha=\mathbb{P}(x>1|H_0)=\frac{\frac{3}{7}\cdot\frac{2}{6}}{\frac{3}{7}}=\frac{2}{6}$
or it is
$\alpha=\mathbb{P}(x>1|H_0)=\frac{3}{7}\cdot\frac{2}{6}=\frac{1}{7}$
and for II type error:
$\beta=\mathbb{P}(x<2|H_1)=\frac{\frac{5}{7}\cdot\frac{2}{6}+\frac{2}{7}\cdot\frac{1}{6}+\frac{2}{7}\cdot\frac{5}{6}}{\frac{5}{7}}=\frac{11}{15}$
Or is it wrong?
Comment: I'm not sure what role H1 plays here. Normally, in a problem like this you either reject the null hypothesis (H0) or determine that you can not reject the null hypotheses. The only reasonably H1 would be Q >= 4 (ie, the actual number of white balls is more than 3), not actually having Q set to a specific number.
Answer: I believe you need an a priori estimate for P(Q3) and P(Q5)
If you assume these two events to be equally likely (before pulling balls), then let each be 0.5
From Bayes $P(x=2)*P(Q_3|x=2) = P(x=2|Q_3)*P(Q_3)$
$P(Q_3|x=2) = \frac{P(x=2|Q_3)*P(Q_3)}{P(x=2)}$
$P(x=2)=P(x=2|Q_3)*P(Q_3)+P(x=2|Q_5)*P(Q_5)$
$P(x=2|Q_3)=\frac{3}{7}*\frac{2}{6}=\frac{1}{7}$
$P(x=2|Q_5)=\frac{5}{7}*\frac{4}{6}=\frac{10}{21}$
$P(x=2)=\frac{1}{7}*\frac{1}{2}+\frac{10}{21}*\frac{1}{2}=\frac{13}{42}$
$P(Q_3|x=2) = \frac{P(x=2|Q_3)*P(Q_3)}{P(x=2)}=\frac{\frac{1}{7}*\frac{1}{2}}{\frac{13}{42}}=\frac{3}{13}$
$P(Q_5|x=2) = \frac{P(x=2|Q_5)*P(Q_5)}{P(x=2)}=\frac{\frac{10}{21}*\frac{1}{2}}{\frac{13}{42}}=\frac{10}{13}$
Thus a Type I is $\frac{3}{13}$
A Type II error you have to complete a similar analysis for each of the cases (one of each and zero white) which would not have rejected H0 in favor of H1
Answer: Your question seems to be incorrect regarding the hypotheses "H0:Q=3 and H1:Q=5"
Null and alternative hypotheses are mutually exclusive and exhaustive statements.
It can be of the form:
H0:Q is equals to 3 and H1:Q not equals to 3
Please edit your question to get a sensible answer.
Comment: I may be wrong, but I think you're talking about **Fisher** hypothesis testing, while this question is about **Neyman-Pearson** hypothesis testing. Thus the question is sensible.


How to list members in a group using views Drupal 7?

Question: I am using Profiles 2 and Organic groups.
I was successful in listing users via views > Users.
I am using "profiles 2" module to collect and store details of users rather than the core drupal user management.
I have created few groups using "organic groups" module.
My question is how to list all the "PROFILES" (created via profile2 module) of members belonging to a group using views ?
Comment: Please don't use the title to replicate tags.
Comment: can you please be more specific, am new to this stuff...thanks
Comment: You tagged the question with "profile2", which makes sense, but you also duplicated the tags in the title, by writing something like "[profile2]" there. I removed them, and simply wanted to make you aware why I did so. :)
Answer: I had forgotten to add Groups Audience as a field in the Profile type created by Profile 2 which in my case was "Main Profile".
Answer: I haven't used neither OG nor Profile2, but since no-one else has given you a more specific answer, I will provide a general one.
When you create a View, your first choice is, "What do list", it's possible that "Profile2" provides a "profile" specific choice here, but most likely, you should go with the regular "user" list.
Then, the filtering on a specific group, is done with a contextual filter, probably on group id.
I would recommend you learn to understand the basic structure for Views first, and you will be able to understand the answer to a whole class of questions similar to this one. Some video tutorials can be found here.
Comment: well thank u for the answer but i found out, that in profile 2 fields i should have added groups audience...which solved the problem...


display strikethrough data in java server faces

Question: I display a table of values contained in a list of Data objects

In each Data object, I have a boolean attribute isStrikethrough.
I would like that, when the value isStrikethrough is set to true, the corresponding line should be strikethrough.
Could you provide me with some hints ?
Comment: by crossed you mean http://en.wikipedia.org/wiki/Strikethrough ?
Comment: yes exactly thanks for the precision, I am not a native speaker
Answer:

<ui:fragment rendered="#{mydata.crossed}">
Crossed Text
</ui:fragment>
<ui:fragment rendered="#{!mydata.crossed}">
Normal Text
</ui:fragment>

Comment: As `` is [deprecated in HTML 5](http://www.w3schools.com/tags/tag_strike.asp) you could use `` instead.
Comment: Thanks a lot,but is there a way not to duplicate the data, because it was a simplified example, and I have a lot of stuff ?
Comment: Build two separate fragments for `` and ``.
Answer: You can do it by this way also,

      <rich:column styleClass="#{mydata.isStrikethrough ? 'strikeClass' : 'normalTextClass'}">


CakePHP & Subselects

Question: I got app that need to be recoded in CakePHP.
I got following select with subselects:
<code>        SELECT COUNT(*) AS item1,
            (SELECT COUNT(*) FROM portal_members) AS item3,
            (SELECT COUNT(*) FROM portal_reviews) AS item3,
            (SELECT COUNT(*) FROM portal_downloads) AS item4
        FROM portal_articles
        WHERE 1 = 1
</code>
Anyone have any idea how to create that query using CakePHP find($type, $params) ?
Answer: If that is your exact query, I'd recommend doing it in four passes.
<code>$item1 = $this->PortalArticle->find('count');
$item2 = $this->PortalReview->find('count'); // etc..
</code>
It might take a wee bit longer to run, but your intentions are much clearer and the code would be much cleaner.
Comment: This is the way I did it first time, but thought there might by more strict method. Thanks for reply. Will do this that way!
Answer: Please try this code
<code>$this->loadModel('PortalArticle');
$db = $this->PortalArticle->getDataSource();
$a = $db->fetchAll(
    ' SELECT COUNT(*) AS item1,
    (SELECT COUNT(*) FROM portal_members) AS item3,
    (SELECT COUNT(*) FROM portal_reviews) AS item3,
    (SELECT COUNT(*) FROM portal_downloads) AS item4
FROM portal_articles
WHERE 1 = 1'
);
</code>
Answer: The CakePHP cookbook contains some subquery examples here:
http://book.cakephp.org/view/74/Complex-Find-Conditions
Comment: Yeah, found them, but cannot apply them to my sub-selects
Comment: Dang Yo. 502 Bad Gate Way.

CakePHP & Subselects


What mapping solution do people use that has a proximity filter?

Question: For D6 I used gmap, which allowed me to easily create map-based views and include proximity filters and sorts. With D7 I've been tempted to move to OpenLayers - I like the idea of learning one powerful mapping tool that can be used to solve more problems than presumably gmap could. However I can't for the life of me find anything that looks close to stable for proximity filters and sorts. I find this a bit surprising - does anyone know of anything I've missed? The best lead I've found so far is this sandbox project, but I haven't given it a go yet.
So can anyone recommend a way, with or without OpenLayers, to have Views-based mapping and proximity filters on D7?
Comment: Generally speaking, it is not the mapping solution that provides the proximity searching functionality, it is the geo-data storage module. For example, if you use the geofield module to store your location data and openlayers and views to display your data and provide data filtering, the filtering and searching functionality is provided by the geofield module. The open layers module is just displaying the data that gets sent to it. In the case you mention with gmap, it is actually the location module doing the proximity search, not the gmap module.
Answer: As of writing this, jpstrikesback's sandbox: Proximity is really solid. I have it running on a few production sites without issues. Once he feels it's 100% it is either going to be released as the D7 version of OpenLayers Proximity or use the new namespace "Proximity" (as it really does not require OpenLayers to function).
I recently wrote up a walkthrough of how to get this up and running for another question on stack exchange. See Need a simple Google Maps solution; lost in the labyrinth of modules.
As you mentioned GMap was ok in D6, but using OpenLayers is much more robust and flexible. It's worth spending the extra time to get it set up. Good luck


Can Entity Framework do what Linq To SQL does?

Question: I'm a bit confused, I have worked with Linq To SQL and gather we can query anything in the dbml or entities e.g:
var query = from i in db.mytable
            select i;

But in the Entity Framework (which supposedly Microsoft are replacing Linq To SQL with) how can we do the same thing? Is it even possible? How does it replace Linq To SQL?
Would be grateful of any examples of the Entity Framework - i.e how the above is done in the Entity Framework! Thanks.
Comment: Entity Framework, is not as of yet a complete replacement for L2S. EF still has lot's of linq operators not implemented.
Comment: Yes, that query will work. But as soon as your query goes even slightly more complex you will notice some major differences; inefficient and overly complex SQL queries generated by EF, and as Pop Catalin mentioned above - a whole heap of operators are not implemented/supported in L2E or are translated to less-than-optimal SQL. Things like 'LIKE' comparisons, left joins, various math functions (e.g. Round()) works fine with L2S but will throw a runtime error when used with L2E.
Comment: @KristoferA Thanks for the valuable information . :)
Answer: Yes more or less the same - you have Linq-to-Entities, which should definitely support that simple LINQ query.
Entity Framework is much more than just a "bloated" Linq-to-SQL - see some points here.
This article shows quite nicely how to write Linq-to-Entities queries in your code.
Linq-to-Entities does not support the full Linq-to-SQL set of functionality for now, but EF4 (with .NET 4.0) is around the corner (should be released before the end of 2009, says Microsoft) and will bring massively more functionality and goodness to the EF space! Stay tuned.
Marc
Comment: The *points here* link to Julie Lerman's blog is broken, it has a trailing '$'. Use [this](http://thedatafarm.com/data-access/linq-to-sql-vs-entity-framework/)
Comment: @FelipeRomero: sorry 'bout that - I fixed the URL, link should work again. Enjoy!
Answer: The same thing only you want to write
var query = from i in db.mytable
            select i;

i think you are not created the object(db) properly for Entity Framework
LINQ To SQL Vs. Entity Framework
Comment: how does it know what database you are saving to then?


MailKit: Message not delete from Inbox when gmail setting Conversation view on

Question: I'm working with MailKit lib and have a problem.
My application is read specify email in Inbox (Gmail), and delete them.
IList<UniqueId> listUid = inbox.Search(query);
for (int i = 0; i < listUid.Count; i++)
{
  var message = inbox.GetMessage(listUid[i]);
  inbox.AddFlags(msg.Uid, MessageFlags.Deleted, true);
  inbox.Expunge();
}

It run OK, But when Gmail setting Conversation View = Conversation view on, the message that marked as deletion will comback in Inbox if have same email subject and same sender. In next-time I count message, all of deletion message will be re-count. How to avoid it? (save Uid of deletion message is one way but when message number increase, processing will be slow)
Thanks very much.
Answer: GMail unfortunately does not behave the same way most other IMAP servers behave and so when you mark a message as \Deleted, it gets moved to the Trash folder automatically and so the Expunge does nothing.
What you need to do is go to your GMail settings and change the behavior of your IMAP account so that it doesn't move the messages to Trash.
Either that or MoveTo() the message to the Trash folder yourself so you can get the UID of the message in the Trash folder (hint: use the return value of the MoveTo() method) and then open the Trash folder and expunge the message from there.
Note: this code is untested, but it should look something like this:
var trash = client.GetFolder (SpecialFolder.Trash);
var moved = client.Inbox.MoveTo (uid, trash);
if (moved.HasValue) {
    trash.Open (FolderAccess.ReadWrite);
    trash.AddFlags (moved.Value, MessageFlags.Deleted, true);
    trash.Expunge (new [] { moved.Value });
}

Comment: Thank you. I followed your suggest and resolved this problem.
But when I using yahoo email. `var trash = client.GetFolder (SpecialFolder.Trash);` has been throw an exception
`The IMAP server does not support the SPECIAL-USE nor XLIST extensions.`
With mail server that not support to get special folder, how to do that?
Comment: I think that in this case, I will use `AddFlags` and `Expunge` normally. it's seem working now.
Comment: how about pop3? I know that call `DeleteMessage` to delete a message, but when `Conversation View = Conversation view on` the message that has been deleted will be back in inbox and count it again. how to avoid this?
Comment: Right. Not all servers support SPECIAL-USE and so you can't use the SpecialFolder enum to get the special folders. For servers like that, you'll either have to use the method you were originally using or else have custom logic for determining the Trash folder (perhaps a user specified folder?). For POP3, I'm not sure how to work around that - perhaps there is a GMail setting for that as well?


Should DKIM selector names be unguessable?

Question: The M³WAAG DKIM Key Rotation Best Practices document (pdf) recommends a "sufficiently" random DKIM selector name so that it cannot be guessed by browsing the DNS. A literal quotation:

4.3 Key Selector Naming Scheme
Define a naming scheme for the DKIM key selectors that is both
  meaningful for forensic analysis and is sufficiently random so the
  keys cannot be easily guessed by browsing the DNS.
NOTE: The selector naming scheme should also be designed to
  mitigate the risk that attackers can easily predict the names of future
  selectors and retrieve the associated keys. See Section 5 for a
  description of the process for publishing keys for future use

This may be relevant for short 512-bit RSA keys, but it does not seem to make sense to me for longer, say 2048-bit, RSA keys. The DNS holds public keys which are not secret and can be discovered by reading just a single signed mail. Security by obscurity with very little security?
Why would a random DKIM selector name be better, when would it make sense to follow their recommendation?
Answer: I reviewed the document and found the author(s) don't understand DNS propogation of new entries.  When updating old entries there are configurable cache times that can be several days.  However, new entries need to be fetched from the authoritative name servers before the can be cached.
If keys are being rotated by the suggested process of rotating keys behind three CNAMEs, the there may be significant delays while cached entries are updated.  This can be mitigated by dropping the TTL on record to be updated in the period before it is updated.  The CNAME rotations may also be problematic in the case an emergency key rotation is required.
Randomizing the key names does provide some small measure of protection against the public key being retrieved in advance of use.  Once the key is in use, I would assume that it could have been harvested for the purpose of generating an alternate signing key.
Comment: Caching should not matter (even if it is weeks) given the rotation time. Initially, set key1 + key2 and use key1. When its time to rotate keys, use key2 and set a new key3. Selectors should not be re-used... You mention *protection against the public key being retrieved in advance of use*, what exact benefit does this bring to an attacker? Consider GPG, those public keys are also public and nobody made a complaint about it.
Comment: @Lekensteyn When using CNAMES the cached CNAME may point to an old selector record.  The CNAME needs to be updated early enough that the old value ages out of caches before the new key is used.  If someone gets the public key before it is used, they would have more time to attempt to generate a signing key.
Comment: If the administrator(s) responsible for the DNS are the same responsible for the DKIM keys and mail infrastucture, no problem.  At several large companies I know of this adjusting the TTL of an individual record would require  suits in meetings (not a good thing).
Comment: @quadruplebucky If the request is done right, it should take a meeting of the suites for the first update.  This can be extremely difficult for many organizations who don't trust the people doing this kind of thing.  If the TTL, can't be changed, the schedule may need to be extended accordingly.
Answer: The current version(march 2019) of the guidelines only mentions random names for selectors once, on an image. Quoting the changes overview:

The suggested key naming convention was reworked (section 5.1.3)

Section 4.2:

A naming convention using rotation dates can help keep selectors ordered.
An example may be: "sales-201309-1024". This example indicates that it belongs to the "sales" email stream, is intended to be rotated into active duty in September 2013 and references a 1024-bit key.

The image in Section 5.1 states on a post-it note:

selector may contain key length, date, random string

Section 5.1.1 states:

...This selector should carry enough information to facilitate the key rotation process.
Answer: Two benefits:

attacker would not be able to begin an attack without discovering
selector name (posession of a signed message, typically)
you can publish the key and ensure propagation into DNS before
it's actually rotated into use with minimum risk of reducing the
key's effective lifetime.

Just a (somewhat weak) extra layer of protection it seems.
Comment: (1) What kind of attack are you referring to? Finding the private key matching the public key? 2048-bit RSA is considered uncrackable with current technologies. (2) Cached DNS failures can be migitated by publishing keys some weeks in advance, this can still happen even if the selector names are known. I am not convinced.
Comment: @Lekensteyn Some DNS services won't allow 2048 keys because containing the required text exceeds the maximum allowed DNS record length. Just few days ago (Dec 2015) I experienced this issue configuring a domain on a fairly large French VPS / DNS provider called OVH.
Comment: I think those suggestions are overly cautious, I'm not trying to convince you of anything.  BTW 2048 bit keys exceed the max length of a txt field (RFC 1035) and have problems in some DKIM implementations.
Comment: What are the known DKIM implementations having issues? Google uses 2048-bit keys everywhere, I consider it a good trade-off in favor of stronger keys.
Answer: That's bad advice in 2023. Might have been somewhat valid in 2014/2015, but not any more. It's possible to autodetect selector names now, so using obscurity on them is useless and will just make your life as an admin more difficult.
Besides that, when DKIM is implemented, we really don't care if someone has access to the key that is published in DNS. It's a public key in a key pair. The private key is used to encrypt a hash value for the email content, and the public key decrypts it. The recipient compares the received hash with one it calculates for the message. If the two match, DKIM validation succeeds.
The important part of DKIM validation is access to the private key used to encrypt the hash value, and that isn't publicly available. The only thing that is encrypted is a hash value, which anyone who has access to the email can duplicate. Since only the private key can successfully encrypt a message that can be decrypted with the public key, the encrypted signature package that contains the hash value can only come from someone who has access to the private key. If someone is able to decrypt and read that package, the only thing they can do with it is verify the source. So access to the key that decrypts the signature gives an attacker absolutely nothing useful.


What are the primary disadvantages of Dummit and Foote's abstract algebra text (3rd ed.)?

Question: I have done a fair amount of research concerning which abstract algebra book to "settle down into"; that is, I wanted to pick an algebra text and really commit to it as my "primary text," more or less, and I have chosen Dummit and Foote's 3rd edition of Abstract Algebra.
My goal is to obtain a solid foundation in algebra at the beginning graduate level (I am self-learning). I have gone through a fair amount of John Durbin's Modern Algebra (6th ed.), but I know this is more of a "warm-up text." I have heard of algebra books by Herstein, Artin, etc., but I am no longer interested in a comparative analysis.

What are the chief drawbacks of using Dummit and Foote's text as my primary algebra text?

I know it has been criticized for being somewhat bland, but that it has a ton of excellent problems and examples and is fairly encyclopedic. I am more interested in mathematical drawbacks. Do they leave out any important topics in modern algebra? Does the book have extensive errata? Basically, what are the downsides of using this text? Preferably, I'd like to hear from people who have used this text before and have some background in abstract algebra who can look at my question from a more retrospective outlook.
Comment: It has almost no category theory.
Comment: I don't know if this is a disadvantage though.
Comment: Did you choose Dummit and Foote over Hungerford?  Or was Hungerford not part of your comparative analysis?  I think Hungerford is one of the best math books ever.  I also tried several in graduate school and settled on that one as by far the best.
Comment: @Gamamal Yes, that was one of the first things I noticed--there are only 8 pages devoted to it, and even those come in an appendix and are not treated in the main text.
Comment: Hungerford has about 30 pages on category theory.
Comment: @GregoryGrant I didn't so much choose it *over* Hungerford so much as I simply chose it. The enormous number of exercises and comprehensive treatment are the features that appealed to me the most, but like I said--I really would like to know some of the *mathematical* issues people might take with D&F.
Comment: @GregoryGrant Hmm. The second appendix of the third edition is devoted to category theory and there are only 8 pages there. Is there a different section in the text that I may have missed somehow?
Comment: @MagicMan That's strange, Chapter X in my copy is called "Categories" and it's 21 pages.  There is also a section in Chapter I called "Categories: Products, Coproducts and Free Objects" that is 8 pages.  So 29 pages altogether.
Comment: @MagicMan Just to be clear, I was referring to Hungerford, I think you may have misunderstood and thought I was talking about Dummit and Foote.
Comment: @GregoryGrant Ah, yes, you are right--I thought you were referring to D&F. That makes sense. Thanks for clarifying!
Comment: There are category theory bits sprinkled throughout.  It's certainly not a great text for learning category theory, but I found it to be good preparation for a more advanced study of the subject.  At this level of understanding, I think that a very large wealth of category-flavored examples (which D&F provides) is more important than studying extremely general concepts.  For instance, adjoint functors are far easier to learn when you've seen dozens of them.
Comment: I think people could better answer your question if you give an idea of what general direction you may be headed in.  Are you going to study algebra itself in the long term or are you preparing for something that uses algebra like number theory, algebraic topology, etc.?
Comment: @GregoryGrant Studying algebra in the long term is really what I had in mind. I'm trying to round out my undergrad education with solid books like Rudin's POMA, Real and Complex Analysis, and Munkre's Topology, and then a good algebra text. D&F seemed like a good fit, but it sounds like maybe I should check out Hungerford as well.
Comment: I see.  Well, unless you go on to do something like algebraic geometry or algebraic topology, you probably don't need to spend an inordinate amount of time studying commutative algebra, or category theory.  I don't think those subjects are too deep and interesting in and of themselves.  Since you don't know where you're headed and time is finite, you should probably focus on the most broadly applicable topics.
Comment: @GregoryGrant What topics would you say those are? Is such a pursuit more appropriate using D&F or Hungerford? It sounds like Hungerford could give me a great foundation and would be manageable while it might take half my life to complete D&F.
Comment: Well, I'd hate to dissuade you from D&F since I've only ever cursorily looked at it.  But it is about twice as long as Hungerford.  I honestly don't think anybody reads these books cover-to-cover.  I think everybody reads the basic material on groups, rings, modules and Galois theory.  Then people refer to the other stuff as needed when they actually use algebra in other subjects.  You want to get to the point where you can pick stuff up quickly later, but you don't need to learn all the algebra you will ever need now before moving on.
Comment: @GregoryGrant Good points. Thanks for all of your feedback. I appreciate it.
Comment: Good luck with it, I honestly believe math is the most empowering major you can do, the world really really needs more people with those skills.
Answer: Dummit and Foote's Abstract Algebra text is definitely not lacking in terms of mathematical content. Although the comments above are correct when they say there is almost no category theory, the number of topics covered in the text makes up for it. I have the text in front of me and it totals 7 pages of category theory. On the other hand, I have found each main section of the text has a fairly good treatment of the respective topic. Here I am mainly talking about the Group Theory, Rings and Modules, and Field and Galois Theory sections. There are several chapters on more advanced topics at the end but from what I can tell those are pretty introductory. I would contend that if you wish to have a single textbook that is very comprehensive, relatively easy to follow, and all around good for learning Abstract Algebra, Dummit and Foote is the way to go.
If you already have a solid mathematical background though you may want to check out Serge Lang's Algebra, which is just as comprehensive but considered more of a "graduate level" text. It also includes more Category Theory if that is a factor.


Saving data in rails session to use in form on next request

Question: Let's say I have a table called positions (as in job positions). On the position show page I display all the detail about the job - awesome. At the bottom I need the prospective applicant to input their professional license # before continuing onto the next page which is the actual applicant creation form. I also need to take that license # and have it populate that field on the applicant form (again on the proceeding page).
I realize there are a couple ways to do this. Possibly the more popular option would be to store that value in the session. I am curious how to do this in the simplest manner?
My idea:

Create a table specifically for license #'s.
Add a small form on the position show page to create license # (with validation)
Store newly created license in session - not sure what to put in which controller?
On applicant creation form populate from session the license #.

This would assume applicants only have one license.
Thoughts?
Appreciate the help!
Answer: Don't store this in the session! Pass that as an hidden field.
Let's say the user starts the form, then open the form again in a new window or something... then the session variable would be shared between the two forms. Other problems would occur if the cookie gets removed (session expire, user clear cache...)
This is not good. The best way is using a POST variable. GET works as well but messes up the URL
Comment: In a normal, logical scenario, why would the user start a form then start it again in a new window?  True, this could be problematic, but on a basis of UX it makes no sense.  Plus, from my understanding, the form itself is to create the license number, not to pass the license number, so a hidden field would not really work.
Comment: In an app I worked on, I thought the user wouldn't... and then the user did. If you create the license number you can then inject it in the next screen or whatever and keep it here.
Comment: Ah, yes, I see that #4 now states a second form.  Yes, it would be easiest and most logical to just pass the license number as an @variable (or the license object, if you need to access more details of it's object), and then use the hidden_field_tag / hidden_field helpers to set it up.
Comment: Great suggestions! Thanks for catching that pitfall. OK still trying to wrap my head on how rails passes @variables. Is it best to create the license using <% form_for(License.new) do |f| %> and then redirect_to new_candidate_path(@license). Then use hidden_field in that form? Still learning the Rails way of doing things here... thanks again!
Comment: mike, it would be best that, in the controller method which calls the view for here, do '@license = License.new', then in the view do 'form_for @license'.  Then use the hidden_field.
Comment: yep makes total sense - I wasn't thinking clearly about the redirect - obviously everything disappears when you send that new request. Thanks Eric and marcgg!
Answer: Seems like a good idea.  As for #3, for whatever controller is called in the transition from 2 -> 4, that would be the controller where you store the session, as such:
<code>session[:license_number] = your_license_number_information
</code>
From there, it can be called the same way (session[:license_number]) to get it.
Comment: Like I said in my answer, using a session could work, but it might lead to issues. An hidden field is safer and more solid. What if the user takes forever submiting the form and the session expires?
Comment: It's entirely possible that session expiration is desired functionality
Answer: The hidden field is safer for data persistence.  However is not not then coded in the HTML output?  That can be a great data security issue.
This is a trade-off to be considered.
Comment: I have that security issue. I have a quiz score that gets built up as the user answers questions. I do not want some smartiepants post an inflated quiz score.


Infinite product involving powers of 2

Question: I have the following infinite product:
$2/1 * 3/2 * 5/4 * 9/8 * 17/16 * 33/32 * 65/64...$
What does it converge to?
I can take its $\ln()$ to get
$\ln(2) + \ln(3/2) + \ln(5/4)....$
Which using the quotient difference rule resolves to
$S(n) = \ln(2^n + 1) - n\ln(2)$ for $n = 0$ to $\infty$
At this point I don't know how to evaluate this: so I took its derivative to see if I could recognize anything:
$S'(n) = 2^n * ln(2) / (2^n + 1) - ln(2)$
Which really looks like it converges to 0...
Integrating $S(n)$ hasn't been much to avail unless its because I lack knowledge.
What's this come out to?
Comment: Wolfram alpha [gives an exact evaluation](http://www.wolframalpha.com/input/?i=product+of+%282%5En+%2B+1%29%2F2%5En+for+n+%3D+0+to+n+%3D+infinity).
Comment: [A related question.](http://math.stackexchange.com/questions/141705)
Comment: @JavaMan: Really? When I follow your link I get only an approximation.
Comment: @Henning: Oops, you are correct.  I meant that there is an exact evaluation for the partial product.  Turning that exact evaluation into an exact evaluation for the infinite product looks highly nontrivial, however.
Answer: Drop the first term for a moment.
$$
\frac{3}{2}\frac{5}{4}\cdots\frac{2^k+1}{2^k}\cdots = \prod_{k=1}^{\infty} (1 + \frac{1}{2^k})
$$
When the product is expanded, what is the coefficient of $\frac{1}{2^n}$? A term comes from any number of distinct factors of the form $\frac1{2^k}$.  And so, each partition
$$
n = k_1 + k_2 + \cdots + k_m
$$
provides a term in the $\frac{1}{2^n}$.  So, the product is:
$$
\sum_{n=0}^{\infty} \frac{q(n)}{2^n}
$$
where $q(n)$ is the number of partitions of $n$ into distinct integers. I don't think this has a closed form.
Answer: There is no nice answer to this. Here is a way to approximate it.
$$\sum_{n=0}^{\infty} \ln\left(1+\dfrac1{2^n}\right) = \sum_{n=0}^{\infty} \sum_{k=1}^{\infty}(-1)^{k-1} \dfrac{1}{k2^{kn}} = \sum_{k=1}^{\infty} \dfrac{(-1)^{k-1}}k \sum_{n=0}^{\infty} \dfrac1{2^{kn}} = \sum_{k=1}^{\infty} \left(\dfrac{(-1)^{k-1}}k \dfrac{2^k}{2^k-1} \right)$$
Answer: 4.768462058062755
According to Wolfram Alpha.  Look it up it is explained there.
Comment: This is better as a comment as it is not instructive as an actual solution to the OP.

Infinite product involving powers of 2


Input a command result in a command line program

Question: I got a command line program ./a.out which asks me to input something as shown below:
$ ./a.out
Adress is 0x8048508
Please input a choice:

And I want to input
python -c 'print "A"*56 + "BBBB" + "\x08\x85\x04\x08"'

Despite from using pip(cannot use here cuz the address is dynamic).
How can I do it?
Many thanks for any thoughts or ideas.
Answer: If the program just reads from standard input then python -c 'print "A"*56 + "BBBB" + "\x08\x85\x04\x08"' | ./a.out should work.
If it is reading from the terminal then that won't and you would have to fake an interactive session (with something like expect to inject the input you want.
Comment: Interesting! I got the impression that the output from `a.out` was supposed to be re-jigged and fed into the python!
Comment: @MarkSetchell Interesting indeed. Re-reading it I don't quite see your interpretation (though I almost do) but I do see an alternative which is that the literal string of the python command is supposed to be the input instead. But that's the same basic concept as my current answer.


How can I get my Ruby gem 'Mechanize' to work?

Question: I need to install the Ruby gem 'Mechanize' for a class that I am taking and do a project using it. I am using windows and I have tried installing versions 2.6.1 and 2.5.3 with the devkits from the website rubyinstaller.org. After installing these versions I have then done 'gem install mechanize' and the gem installs correctly. However when I try to use even " require 'mechanize' ", I get a sizable stacktrace and I cannot figure out what is wrong. I have tried to uninstall and reinstall everything multiple times.
The stacktrace:
C:/Ruby25-x64/lib/ruby/gems/2.5.0/gems/net-http-persistent-3.0.0/lib/net/http/persistent.rb:205:in `<class:Persistent>': uninitialized constant Process::RLIMIT_NOFILE (NameError)
    from C:/Ruby25-x64/lib/ruby/gems/2.5.0/gems/net-http-persistent-3.0.0/lib/net/http/persistent.rb:190:in `<top (required)>'
    from C:/Ruby25-x64/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'
    from C:/Ruby25-x64/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require'
    from C:/Ruby25-x64/lib/ruby/gems/2.5.0/gems/mechanize-2.7.6/lib/mechanize.rb:6:in `<top (required)>'
    from C:/Ruby25-x64/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:135:in `require'
    from C:/Ruby25-x64/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:135:in `rescue in require'
    from C:/Ruby25-x64/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:39:in `require'
    from test.rb:1:in `'

Any help or suggestions would be greatly appreciated. Thank you!
Answer: It seems this is a known windows problem in one of this gem's dependencies, see: uninitialized constant Process::RLIMIT_NOFILE (NameError)
You might try the hack given there to put this line before your require
Process::RLIMIT_NOFILE = 7 if Gem.win_platform?
require 'mechanize'

You could also try running ruby inside some kind of virtualized environment if you are serious about becoming a ruby dev and you must use windows.  See Developing in Ruby on Windows
UPDATE: This is a known issue not for mechanize but one of its' dependencies see this issue and the proposed workaround:
Locate the source path of the mechanize gem.  You should find it one of the paths shown in the results section from running
 gem env
 #look for a section that says:
 - GEM PATHS:

CD to the path from step 1, then lib/net/http/persistent.rb in your text editor: and modify this:
Find and remove this line:
DEFAULT_POOL_SIZE = Process.getrlimit(Process::RLIMIT_NOFILE).first / 4

Then add the following in it's place:
if Gem.win_platform? then
  DEFAULT_POOL_SIZE = 256
else
  DEFAULT_POOL_SIZE = Process.getrlimit(Process::RLIMIT_NOFILE).first / 4
end

and save the file. Keep in mind if you use bundler and plan to run bundle update or bundle upgrade you will lose these changes. But this will hopefully be fixed in a some future release.  I have not tested this as I don't use windows, but you can try it.
Comment: This fixed it for me. Windows 10 v1803 x64, using rubyinstaller-devkit-2.5.3-1-x64.exe from https://rubyinstaller.org/ . Thanks!


Html.EditorFor perdendo valor ao reiniciar a página

Question: estou iniciando meu html.editorfor com "0,00" assim:
<code>@Html.EditorFor(model => model.Preco, new { htmlAttributes = new { @Value = "0,00"} })
</code>
Porém quando o usuário recebe alguma mensagem de validação (ModelState.IsValid=false) o editorfor acaba perdendo o valor e volta para "0,00" . A pergunta é: Teria como eu iniciar o editorfor com "0,00" e depois que o usuário digitar o novo valor eu mantê-lo mesmo se o ModelState.IsValid retornar false?
Comment: E se você passar ao invés de passar {Value = "0,00"}, passar por {Value = model.Preco.ToString("0,00")}, ai a primeira vez é só iniciar o model (não  passar null) e depois que testar o ModelState (no httpPost) passar o mesmo model que recebeu por parâmetro de volta a view
Answer: Há várias formas de conseguir isso.
Talvez a mais simples seja:
<code>@Html.EditorFor(m => m.Preco, new { htmlAttributes = new { Value = Model != null? Model.Preco.ToString("0.00") : "0.00" }})
</code>
Comment: Valeu Daniel, deu certo!


Forecasting - Performance measures, BIAS and Mean Percentage Errors

Question: I have calculated BIAs and MPE for a forecasted decompositional model, BIAS comes out as underpredicting and MPE comes out as overpredicting. Is this possible seen as they both measure how biased a forecast is?
Comment: Hi there and welcome. In the interest of your question... 1) Could you please elaborate on what BIAS (in capitals) is? 2) What do you mean by "underpredicting" and "overpredicting"? Does it mean that one is on average too high and the other on average too low? 3) Is this finding statistically significant? 4) What are your own thoughts? – *Reviewer*
Answer: The Mean Percentage Error does not measure the bias. It measures a kind of "percentage bias".
Suppose you have two identical point forecasts, $\hat{y}_1 = \hat{y_2} = 100$. However, the corresponding actuals are $y_1 = 50$ and $y_2 = 150$. Your forecast is unbiased, since the mean error is zero. However, the first forecast has a percentage error of $100\%$, and the second of $-33\%$, for a mean percentage error of $33\%$.
This earlier thread concerns the Mean Absolute Percentage Error, but may still be helpful: What are the shortcomings of the Mean Absolute Percentage Error (MAPE)?
Comment: Not much. That's my point. I don't use it much.
Comment: [The thread on the MAPE should give you some food for thought then.](https://stats.stackexchange.com/q/299712/1352) Good luck!
Comment: Wouldn't it be -100% and 33% and then the average is 33.5 %? But doesn't this mean overall on average the forecast is underpredicting? If you have more data, this becomes a more valid measurement?
Comment: Whether it's + or - depends on how you define your error, as $y-\hat{y}$ or $\hat{y}-y$, both are common (Green & Tashman, 2008, *Foresight*). If you prefer your calculation, then you would get an MPE of -33%. I personally prefer my calculation, because with $e=\hat{y}-y$, positive errors correspond to overforecasts. And no, with more data, this will not change - just imagine repeating this pattern many times; the mean errors won't change.
Comment: Okay so what does the MPE actually show you then?
Comment: Ahhh... Ive been asked to comment on it for my degree, this should be interesting


How do I get the current node from a Block module?

Question: I'm looking to create a block that renders differently, depending on the content (metadata, really) of the node in which it is embedded.
The "Title" block is a good example of what I'm trying to do, I think. When you put "Page title" in a section (from the Structure menu), it displays the title of the node being displayed.
I'd like to do something similar. The end goal is to read the workflow state data from the node in order to provide large visual clues to readers that the document they are reading is approved/unapproved/et cetera.
There are some other similar ends to which I may put this technique as well, provided I figure it out.
Here's what I have:
/**
 * Provides a 'Workflow Block'.
 *
 * @Block(
 *   id = "workflow_tag_block",
 *   admin_label = @Translation("Workflow Block"),
 * )
 */
class WorkflowTagBlock extends BlockBase implements ContainerFactoryPluginInterface {
        protected $node;

        public function __construct(array $configuration, $plugin_id, $plugin_definition, $node) {
                parent::__construct($configuration, $plugin_id, $plugin_definition);

                $this->node = $node;
        }

        public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
                return new static(
                        $configuration,
                        $plugin_id,
                        $plugin_definition,
                        $container->get /*... something here, I think. I need this to be the node I'm rendering. */
                );
        }

        /**
         * {@inheritdoc}
         */
        public function build() {
                // do things with $this->node;

                return [
                        '#markup' => $this->t('Here Be Dragons! '),
                ];
        }
}

Obviously, there's an important line I don't have complete in there. The most obvious attempt would be: $container->get('request_stack')->getCurrentRequest()->get('node'). But that returns the WorkflowTagBlock object itself, not the primary content node.
I'm aware that multiple nodes might be rendered on the screen at once (for example, in a list), so I can't just try to snag the node id from the uri or anything like that.
This is done in other places, so surely there's a way to do it. How?
Answer: Update your plugin definition to require the node context:
 *   context_definitions = {
 *     "node" = @ContextDefinition("entity:node", label = @Translation("Node"))
 *   }

Then in your build() method, you can access it like this:
$node = $this->getContextValue('node');

If the block is displayed on a node page, then the node will be stored in the $node variable.
When dealing with an existing block, make sure to either replace the block with a new one once the code is updated; or add the following to the settings: of the block.
If not done, your block will return empty due to missing config.
context_mapping:
  node: '@node.node_route_context:node'

Comment: This definitely works. I just wanted to point out that, as the answer says, if you had the block created before you added the context you must remove the block or add the setting to the block. When you add the block again you should be able to add the node as context. If you don't you will likely get an error like this: `Drupal\Component\Plugin\Exception\MissingValueContextException: Required contexts without a value: node in Drupal\Core\Plugin\Context\ContextHandler->applyContextMapping()`. Hope this helps!
Answer: The Book module implements a block that needs to access to the currently viewed node, and it uses the following code, in BookNavigationBlock::build().
if ($node = $this->requestStack->getCurrentRequest()->get('node')) {
  $current_bid = empty($node->book['bid']) ? 0 : $node->book['bid'];
}

$this->requestStack is initialized from the following code.
  public function __construct(array $configuration, $plugin_id, $plugin_definition, RequestStack $request_stack, BookManagerInterface $book_manager, EntityStorageInterface $node_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);

    $this->requestStack = $request_stack;
    $this->bookManager = $book_manager;
    $this->nodeStorage = $node_storage;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
    $configuration,
    $plugin_id,
    $plugin_definition,
    $container->get('request_stack'),
    $container->get('book.manager'),
    $container->get('entity.manager')->getStorage('node')
    );
  }

The code is essentially like the one you are using, but it seems that in your case, a module is messing up with what $container->get('request_stack')->getCurrentRequest()->get('node') is returning.
As workaround, if you find in which cases it happens, you could override BlockBase::blockAccess() to avoid your build() method is called in those cases.
Answer: You can also try:
$node = \Drupal::routeMatch()->getParameter('node');

Comment: According to the documentation, this is deprecated and not recommended, right?
Comment: I don't see it here: https://api.drupal.org/api/drupal/core!lib!Drupal.php/function/Drupal%3A%3ArouteMatch/8
Answer: I'm not sure that creating a block directly is the most Drupalistic way to achieve this?
I would think in terms of creating a field or pseudo-field. Once you've done that, there's a number of routes (Views with contextual filter and block display, "Field as block" module, and ctools D8) to displaying the field as a block (if you even need to).


Why local directory is empty after "ADD ." on dockerfile?

Question: In my main directory :

docker-compose.yaml
php.Dockerfile
foo.txt
htmlhtml (dir)

Docker-compose.yaml content
version: "3.7"
services:
  web-server:
    build:
      dockerfile: php.Dockerfile
      context: .
    #    restart: always
    volumes:
      - "./htmlhtml/:/var/www/htmlhtml/"
    ports:
      - "8080:80"

php.Dockerfile content
FROM php:7.4.3-apache

WORKDIR /var/www/htmlhtml

ADD . /var/www/htmlhtml/

The ADD instruction should put the file 'foo.txt' in the htmlhtml directory.
And the htmlhtml directory should be connected with the htmlhtml container's directory ?
But it doesn't.
Why ?
thx
Answer: It does but you mount a volume on top of the directory which is presumably empty.

First you build the container, which will copy the files to /var/www/htmlhtml via the ADD directive
After that, the container is started via docker-compose and the volumes are mounted, in this case ./htmlhtml is mounted to /var/www/htmlhtml, being an overlay to your copied files

The solution is to decide what you want. You can either

supply the served files via a mounted volume and only copy static files, or
copy all files to the container and use the volume for whatever you intended it to
Comment: In other words, it copies the files and then destroys them?
How to copy the files, be able to use them in the dockerfile (i.e. script.sh) and leave them after ?
Comment: No. It just mounts a directory *on top* of that directory. The contents are still there. Remove the `volume` directive in the `docker-compose.yml` and you will see the files. Alternatively, add a file to `./htmlhtml` and you will see the file appear in the container. Nothing is destroyed.


Postmark::InvalidMessageError when attempting to send mail

Question: I use Rails 3 + Postmark-Rails.
At first, I created account on postmarkapp.com to get my api key.
I Activated my signature by email link [for example, "firstname.lastname@example.com"]
-- After that, I added this to application.rb
config.action_mailer.delivery_method   = :postmark
config.action_mailer.postmark_settings = { :api_key => "fdcb..." }

I use this method to send emails:
class UserMailer < ActionMailer::Base
  default :from => "email@example.com"

  def do_my_mail(to, subj)
    mail(:to => to, :subject => subj)
  end

I get this error:
Postmark::InvalidMessageError
Sender signature not defined for From address.

Any ideas?
Comment: Did you add DKM and SPF records to your domain name? http://support.postmarkapp.com/customer/portal/articles/64739-what-is-dkim-and-spf-and-why-should-i-use-it-
Comment: No, I skipped that step. Is it can be answer to my question?
Comment: I think this is just recommendation: "In order to ensure effective email delivery, we highly recommend that you setup email authentication in your DNS records.."
Answer: SPF and DKIM are recommended, not required. However, sender signature is required (as stated in the documentation).
Are you sure you are using the same From address as the one used to create the sender signature? This can happen if you are using different email.
Comment: Actually, you must use exactly the same address as you defined signature for. If you defined sender signature for email@example.com, you can only send using From: firstname.lastname@example.com. If you want to use one address for several purposes, you can make them distinct by using + syntax. For example: firstname.lastname@example.com and email@example.com are valid addresses to use as From when you have signature defined for firstname.lastname@example.com
Comment: Maybe, I need use the **Sender Signature**, that match the Server domain? For example, if My Server domain is http://beer.com, the email signature should be 'email@example.com'?
Comment: In addition, it is also possible to send using many different From addresses without defining sender signature for each. For example, if you are hosting forum and need to send on behalf of many users. In that case, contact Postmark support and support staff will lead you through the process of enabling that feature.
Answer: Postmark uses sender signatures to make sure you don't use their service for spam purposes:
From http://developer.postmarkapp.com:
"Sender signatures are needed in order to verify that, well, you really own the mailbox, and that you are not a spammer (yes, we hate spam too). You must have a sender signature for each from address used in your application."
Comment: I'm guessing that documentation page is a little outdated. Maybe sender signatures were just a recommendation at one point, but the developer homepage is pretty explicit that it's a requirement now.
Comment: Sorry, but I don't think that SPF and DKIM on my side is important. The error message is tell about "not defined signature".
Comment: I already read the article "What is DKIM and SPF and why should I use it?" there http://support.postmarkapp.com/customer/portal/articles/64739-what-is-dkim-and-spf-and-why-should-i-use-it- , it says that DKIM and SPF are recommendation only


Installing and Configuring Windows 2008 SMTP Server

Question: Trying to work out the process of enabling SMTP server on a Windows 2008 Server. I've enabled the SMTP feature within the Server Manager but I don't see where to configure it.
I need to be able to configure it to use a SmartHost.
Walk throughs appreciated.
Answer: Use the IIS6.0 compatible console in Windows/system32/inetsrv/iis.mmc (assuming it's been installed)
Cheers,
jmi
Comment: didn't realize there was a separate console for that. Thanks
Answer: To add to what Jamie said, my understanding is you basically have to use the IIS 6 tools at this time. You can install them as a feature as outlined in this article and from that point on it is fairly straight forward just like it is in 2003.


How can I allow users to search for other users based on profile information

Question: I have two profiles for my users. First, is "Infomation" machine name "main" and second "About Me" machine name "about_me" and I want to create a page where other users can search for users with specific attributes in their "Information" or "About Me" profile. I'm just starting out with drupal 7.10 so any help would be appreciated.
Answer: You can achieve this by using views contextual filters.
or you can use advanced search for users
<code>http://www.yoursite.com/search/user
</code>
set the user permission accordingly to view advanced search
Answer: I achived this by making a view called "Search Users". I couldn't figure out contextual filters so I tried using "Fields Criteria."
I first selected that I wanted the field to show users. Then I added the fields that I wanted. Then I added the field criteria that I wanted to filter by and check "Expose this filter to visitors, to allow them to change it." That was all I needed to do.


Expected BEGIN_ARRAY but was STRING at line 1 column 2 path $

Question: I have an API, that for getting data I must send a Parameter of JSON. Here is the JSON that must need to be sent in the @Body to get the data.
{
    "ViewName": "Members_HousholdAdmin",
    "DataRequest":{
      "filter":[{
        "field":"",
        "logic":"",
        "operator":"",
        "value":""
       }],
        "offset":0,"take":0,
        "Sort":[{"field":"","dir":""}]
    },
    "parameters":[
    {"key": "%FundId","value": "1" }
    ]
}

It works in postman, but in Android, I have the following error:
Expected BEGIN_ARRAY but was STRING at line 1 column 2 path $

I guess this is a problem in my models, but I can not fix it.
My Models :
public class SendParametersGetData {

    @SerializedName("ViewName")
    public String ViewName;

    @SerializedName("DataRequest")
    public DataRequest DataRequest = null;

    @SerializedName("Parameters")
    public List<Parameters> parameters = null;
}

public class DataRequest  {
    @SerializedName("take")
    public int take=0;

    @SerializedName("offset")
    public int offset=0;

    @SerializedName("filter")
    public ArrayList<Filter> filter;

    @SerializedName("Sort")
    public ArrayList<Sort> Sort;
}

public class Parameters {

    @SerializedName("value")
    public String value;

    @SerializedName("key")
    public String key;

    public Parameters(String key, String value) {
        this.value = value;
        this.key = key;
    }
}

There is 2 more models for sort and filter. I use retrofit & RXJava.
@POST("test.php")
Single<ArrayList<Members>> getMembers(@Body SendParametersGetData sendParametersGetData);

I set SendParametersGetData with the constructor function (in this example only ViewName and Parameters are set) and I give as input to the getMembers method.
ArrayList<Parameters> parameters = new ArrayList<>();
parameters.add(new Parameters("%FundId",String.valueOf(fund.getFundId())));
SendParametersGetData sendParametersGetData = new SendParametersGetData("Members_HousholdAdmin",parameters);
dataSource.getMembers(sendParametersGetData).subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new SingleObserver<ArrayList<Members>>() {
            @Override
            public void onSubscribe(Disposable d) {
                compositeDisposable.add(d);
            }

            @Override
            public void onSuccess(ArrayList<Members> members) {
            }

            @Override
            public void onError(Throwable e) {
                view.hideProgress();
                TastyToast.makeText(view.getContext(), e.toString(), 6000, TastyToast.ERROR);
            }
        });

Answer: I found the following error in your model class.
The Parameters needs to be renamed as parameters to match with the JSON key.
@SerializedName("parameters")
public List<Parameters> parameters = null;

This should solve your problem I guess. I think the other model classes are fine.


Como mudar o posicionamento inicial do modal?

Question: Como eu consigo mudar o posicionamento inicial do Modal Box do Bootstrap?
Gostaria que ele ficasse um pouco mais para baixo, coisa que com 3
 já resolvem, mas da maneira citada parece mais uma gambiarra, do que uma solução correta.

<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

                <button type="button" class="close"
                   data-dismiss="modal">
                       ×
                       Close
                </button>

                    Modal title

                <form class="form-horizontal" role="form">

                    Email

                        <input type="email" class="form-control"
                        id="inputEmail3" placeholder="Email"/>

                    Password

                        <input type="password" class="form-control"
                            id="inputPassword3" placeholder="Password"/>

                            <input type="checkbox"/> Remember me

                      <button type="submit" class="btn btn-default">Sign in</button>

                </form>

                <button type="button" class="btn btn-default"
                        data-dismiss="modal">
                            Close
                </button>
                <button type="button" class="btn btn-primary">
                    Save changes
                </button>

Answer: Para posicionar elementos utilize CSS,
 deve ser utilizado em quebra de linha de texto. Usei style="margin-top:100px;" no modal para posicionar da forma que você queria;

  <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

                <button type="button" class="close"
                   data-dismiss="modal">
                       ×
                       Close
                </button>

                    Modal title

                <form class="form-horizontal" role="form">

                    Email

                        <input type="email" class="form-control"
                        id="inputEmail3" placeholder="Email"/>

                    Password

                        <input type="password" class="form-control"
                            id="inputPassword3" placeholder="Password"/>

                            <input type="checkbox"/> Remember me

                      <button type="submit" class="btn btn-default">Sign in</button>

                </form>

                <button type="button" class="btn btn-default"
                        data-dismiss="modal">
                            Close
                </button>
                <button type="button" class="btn btn-primary">
                    Save changes
                </button>