sequelize findAll sort order in nodejs

Question: I'm trying to output all object list from database with sequelize as follow and want to get data are sorted out as I added id in where clause.
exports.getStaticCompanies = function () {
    return Company.findAll({
        where: {
            id: [46128, 2865, 49569,  1488,   45600,   61991,  1418,  61919,   53326,   61680]
        },
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at']
    });
};

But the problem is after rendering, all data are sorted out as follow.
46128, 53326, 2865, 1488, 45600, 61680, 49569, 1418, ....

As I found, it's neither sorted by id nor name. Please help me how to solve it.
Answer: In sequelize you can easily add order by clauses.
exports.getStaticCompanies = function () {
    return Company.findAll({
        where: {
            id: [46128, 2865, 49569,  1488,   45600,   61991,  1418,  61919,   53326,   61680]
        },
        // Add order conditions here....
        order: [
            ['id', 'DESC'],
            ['name', 'ASC'],
        ],
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at']
    });
};

See how I've added the order array of objects?
order: [
      ['COLUMN_NAME_EXAMPLE', 'ASC'], // Sorts by COLUMN_NAME_EXAMPLE in ascending order
],

Edit:
You might have to order the objects once they've been recieved inside the .then() promise. Checkout this question about ordering an array of objects based on a custom order:
How do I sort an array of objects based on the ordering of another array?
Comment: I want to order like that by `46128, 2865, 49569,  1488,   45600,   61991,  1418,  61919,   53326,   61680`.
Comment: Hmmm. You won't be able to do that (as far as I know)! You'll have to look into sorting the objects once you've received them in the .then() promise?

Why do you need to order them in this specific range?! Is there a order clause that could maybe do it for you? @ppshein
Comment: I tried to do the same with a table associated with another, It did not worked. How can we do this with association  @james111
Answer: If you want to sort data either in Ascending or Descending order based on particular column, using sequlize js, use the order method of sequlize as follows
// Will order the specified column by descending order
order: sequelize.literal('column_name order')
e.g. order: sequelize.literal('timestamp DESC')

Answer: If you are using MySQL, you can use order by FIELD(id, ...) approach:
Company.findAll({
    where: {id : {$in : companyIds}},
    order: sequelize.literal("FIELD(company.id,"+companyIds.join(',')+")")
})

Keep in mind, it might be slow. But should be faster, than manual sorting with JS.
Answer: You can accomplish this in a very back-handed way with the following code:
exports.getStaticCompanies = function () {
    var ids = [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680]
    return Company.findAll({
        where: {
            id: ids
        },
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'],
        order: sequelize.literal('(' + ids.map(function(id) {
            return '"Company"."id" = \'' + id + '\'');
        }).join(', ') + ') DESC')
    });
};

This is somewhat limited because it's got very bad performance characteristics past a few dozen records, but it's acceptable at the scale you're using.
This will produce a SQL query that looks something like this:
[...] ORDER BY ("Company"."id"='46128', "Company"."id"='2865', "Company"."id"='49569', [...])

Answer: May be a little late but want to mention an approach.
Sorting based on the [46128, 2865, 49569,  1488,   45600,   61991,  1418,  61919,   53326,   61680] can be done using ARRAY_POSITION function of postgreSQL.
const arr = [46128, 2865, 49569,  1488,   45600,   61991,  1418,  61919,   53326,   61680];
const ord = [sequelize.literal(`ARRAY_POSITION(ARRAY[${arr}]::integer[], "id")`)];

return Company.findAll({
    where: {
        id: arr
    },
    attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'],
    order: ord,
});

Answer: I don't think this is possible in Sequelize's order clause, because as far as I can tell, those clauses are meant to be binary operations applicable to every element in your list. (This makes sense, too, as it's generally how sorting a list works.)
So, an order clause can do something like order a list by recursing over it asking "which of these 2 elements is older?" Whereas your ordering is not reducible to a binary operation (compare_bigger(1,2) => 2) but is just an arbitrary sequence (2,4,11,2,9,0).
When I hit this issue with findAll, here was my solution (sub in your returned results for numbers):
var numbers = [2, 20, 23, 9, 53];
var orderIWant = [2, 23, 20, 53, 9];
orderIWant.map(x => { return numbers.find(y => { return y === x })});

Which returns [2, 23, 20, 53, 9]. I don't think there's a better tradeoff we can make. You could iterate in place over your ordered ids with findOne, but then you're doing n queries when 1 will do.
Answer: if required, databases order their output by the generic order of values in the order by fields.
if your order is not like this, you may add to the select an order_field, and give it a value based upon the value in id:
case
when id=46128 then 0
when id=2865 then 1
when id=49569 then 2
end as order_field

and order by order_field.

if there are lots of values, you may stuff them in their original order in a temporary table with an identity primary key order_field, and inner join your select to that temporary table by your value field, ordering by order_field.
i don't know how to do this in sequelize, but found here answers on how it does things that i needed.
Answer: Worked for me by using "" quotes surrounding the property name.

For Debugging You can see what is the query that is getting generated by sequelize and then try to run  it on the particular DB console.
In My Case I was not able to sort the data by last updatedAt column

Code Snippet :
exports.readAll = (req, res) => {
  console.log("Inside ReadAll Data method");
  let data;
  if (!req.body) {
    data = CompanyModel.findAll({  order: [[sequelize.literal('"updatedAt"'), 'DESC']]});
  } else {
    data = CompanyModel.findAll({  order: [[sequelize.literal('"updatedAt"'), 'DESC']]});
  }
  data
    .then((data) => {
      res.send(
        data
      );
    })
    .catch((err) => {
      res.status(500).send({
        message: err.message || "Some error occurred while retrieving data.",
      });
    });
};

SQL Query getting formed in my case :
Inside ReadAll Data method

Executing (default): SELECT "company_name", "company_id", "on_record", "createdAt", "updatedAt" FROM "companies" AS "company" ORDER BY "updatedAt" DESC;

Answer: Incase anyone is using uuid type, using example by @Agniveer from above but modified
const ids = [
'f01a057e-5646-4527-a219-336804317246',
'ee900087-4910-42b4-a559-06aea7b4e250',
'b363f116-1fc5-473a-aed7-0ceea9beb14d'
];

const idsFormat = `'${ids.join("','")}'`;

const order = [sequelize.literal(`ARRAY_POSITION(ARRAY[${idsFormat}]::uuid[], "<insert_table_name>"."id")`)];

sequelize findAll sort order in nodejs


html not linking to css file in Visual Studio Code

Question: Environment

Windows 8.1 64bit
Visual Studio Code 1.15.1

Related question

HTML wont link to CSS file in Visual Studio Code

Issue
html doesn't link to css

Classes and ids in css don't show up on Intellisense in html.
When I put the cursor on a class or id in html and press F12 to jump to css, a window pops up and says "the definition wasn't found."

However, when I open the html in a browser, the webpage is shown perfectly fine. So it seems like there is something wrong with my Visual Studio Code.
html
<!DOCTYPE html>

  <title>Test</title>
  <link rel="stylesheet" type="text/css" href="./css/style.css">

css
.abc{
    width: 100px;
    height: 100px;
    background: red;
}

#xyz{
    width: 100px;
    height: 100px;
    background: blue;
}

files
index.html
css
|
+---style.css
webpage

I'd like to know how to get rid of this issue.
Edit 17/9/3 19:03
Thanks for the answers, guys.
The following didn't work.

href="../css/style.css"
href="~/css/style.css"
href="css/style.css"
Embedding stylesheet in  tag (And I want to keep css in a separate file)
Answer: I don't believe jumping to css classes and ids is supported natively by Vscode.  Try the CSS Peek extension, it does what you want nicely.
Answer: Make sure that the path you provided to access style.css file is correct.
If that doesn't work, try adding inline css in index.html:
<!DOCTYPE html>

<title>Test</title>

This is an alternative Solution.
According to me your browser is not refreshing the file so you can refresh/reload the entire page by pressing     CTRL + F5    in windows for mac
    CMD + R
Try it if still getting problem then you can test it by using firebug tool for firefox.
For IE8 and Google Chrome you can check it by pressing F12 your developer tool will pop-up and you can see the Html and css.
You can also try this syntax:
<link href="./css/style.css" rel="stylesheet" type="text/css" media="screen, projection"/>

Make sure that the browser actually makes the request and doesn't return a 404.
Hope It Helps!!
Comment: Maybe ./css should be ../css too ?
Comment: Depends in which directory you are. Depending on that you should be able to generate a relative path.
Answer: If html and css are in the same directory, it should work.
How could it be it doesn't?
Well, if the preview copys the html to a temporary directory before showing it, the css will not be there. That's the only way I can imagine this problem exists.


Asking 2011 Putnam B6

Question: I wish to ask today's Putnam problem B6:
Suppose $p$ is an odd prime. Prove that for $n\in \{0,1,2...p-1\}$, at least $\frac{p+1}{2}$ number of $\sum^{p-1}_{k=0} k! n^{k}$ is not divisble by $p$.
For example, for $p=3$, we have $(0,1,2)$ corresponds to $(0, 1+1+2,1+2+2*4)$. For $p=5$, we have $(0,1,2,3,4)$ corresponds to $(0,1+1+2+6+24,1+2+2*4+6*8+24*16..)$.
It is to be expected that an official solution can be found in somewhere (the Putnam archive, American Mathematical Monthly, AOPS, etc). My point of raising this question is not to ask a solution of it, because I am not interested in problem solving techniques. Instead I want to ask the following questions:
1) Is the function $\sum\limits_{k=0} ^{p-1}  k! n^{k}$ well known? Can it be expressed in some closed form via generating functions or other combinatorical tools? My combinatorical background is very weak so I think I should ask others.
2) In general how strong the statement is? For example, for $p$ quite large, how many elements in $\mathbb{Z}_{p}$ tend to satisfy $\sum \limits_{k=0} ^{p-1} k! n^{k}=0$?
3) It is possible to see the problem via some 'high level' proof? (I know David Speyer is found of this kind of thing). Because I am not specialized in number theory, the limited number theory knowledge I have in Dedekind domains and valuations seems to be quite irrelevant to this problem. But I think there should be some way this small problem generalizes to something more interesting to an expert.
Comment: I actually thought of this question for a while during the exam, and sadly enough it got me nowhere good. I see that you don't look very busy during the putnam exam if you have the time to think about that kind of generalization! XD Great thoughts on it though.
Comment: @ChangweiZhou: Usually these types of modular arithmetic sum questions are very similar.  Rearrangements with basic theorems is usually a good place start.  Here, since it is talking about the set of all $n$, we notice that it is a question about how many zeros a polynomial has.  Keeping this in mind, we try to recall facts about polynomials mod p.  In a finite field, a polynomial has no more zeros then its degree, and the the gcd of the polynomial with the derivative tells us about double roots.  These basic ideas are then enough to solve the question.
Comment: @PatrickDaSilva: I spent about one hour in this problem after I solved B2,B3 and B1, but due to my poor number theory background I could not reach anywhere.
Comment: @EricNaslund: I feel this problem is actually more than modular arithmetic. It is nice to see a relatively closed form in your answer, but as I stated I am more interested in how the function behaves in $\mathbb{Z}_{p}$ instead of finding techniques to solve it. I am sure there is some way to solve this without using fancy theoretical machinery as every Putnam problem, but I am more interested to **understand** the problem properly, not just to get why the statement is true.
Comment: @ChangweiZhou: It is likely that Noam Elkies could tell you everything you wanted to know about this problem, it might be worth posting on Math Overflow just to get his attention.
Comment: @EricNaslund: I agree that the truncated exponential might be the only nice way to approach it in $\mathbb{Z}_{p}$, it does not look very likely the formula can be further simplified. You article is helpful, though my number theory/algebra background is not enough to read it very quickly. But I disagree that "the most generalizations and deeper questions" will necessarily come from the truncated exponential. For example, the numerical analysis of the distribution of the zeros of the function probably will not be simplified if we use the truncated exponential instead of the original function.
Comment: @EricNaslund: I need to rush for a concert so I am sorry I cannot comment any further. I will accept your proof as you positive answered both (1) and (3) in my questions. I will try to read your article and see what I can get from hands on computation myself first. Thanks for the info on Noam Elkies.
Comment: @ChangweiZhou: There are some good answers on overflow.  Check the link at the top of my answer.
Answer: Edit: Asked on Overflow:  There are some very good answer which can be found here which explain some deeper meaning:  https://mathoverflow.net/questions/82648/truncated-exponential-series-modulo-p-deeper-meaning-for-a-putnam-question
I feel that looking at $\sum_{k=0}^{p-1} k!n^k$ without changing its form is the wrong way to approach this problem, and if there are deeper solutions they will come by modifying this first.  After some rearrangements modulo $p$, what we are really looking at is the truncated exponential series.
Rephrasing the question:
 First, let us ignore $n=0$, as in this case the sum is just $1$, and instead consider only the multiplicative group.  Letting $k=p-1-l$ and using Wilsons theorem and Fermats little theorem we can rewrite our sum as $$\sum_{k=0}^{p-1}k!n^{k}\equiv\sum_{l=0}^{p-1}(p-1-l)!n^{p-1-l}\equiv-\sum_{l=0}^{p-1}\frac{1}{(p-l)(p-l+1)\cdots(p-1)}n^{-l} $$  $$\equiv -\sum_{l=0}^{p-1}(-1)^{l}\frac{n^{-l}}{l!}.$$ Using the fact that $n\rightarrow p-n $ and $n\rightarrow n^{-1}$  are isomorphisms of the multiplicative group, we have reduced the problem to considering for which $n$ we have $$-\sum_{l=0}^{p-1}\frac{x^{l}}{l!}=0.$$ This means that the original problem is equivalent to bounding the number of zeros modulo $p$ of the truncated exponential function $$E(z)=\sum_{l=0}^{p-1}\frac{z^{l}}{l!}.$$

Proof of the question: Consider  $$Q(z)=z^{p}-z+\sum_{l=0}^{p-1}\frac{z^{l}}{l!}.$$ Then for each integer $Q(n)=E(n).$ However, $$Q^{'}(z)\equiv E^{'}(z)-1=E(z)-\frac{z^{p-1}}{(p-1)!}-1\equiv E(z)+z^{p-1}-1.$$ Then, if $Q(n)=0$  for $n\neq0$ , we must also have $Q^{'}(n)=0$  so that $n$ is a double root of $Q(n).$ Since $\deg Q(n)=p$, we see that at most half of the integers $p\in\left\{ 1,2,\dots,p-1\right\}$ satisfy $E(n)=0.$ Since $E(0)=1$, we conclude the desired result.

Motivation: The first idea I had looked at $E(z)-E(-z)$, but if you carry through with the computations you can only show that at least $\frac{p-1}{4}$ are non zero.  Instead, lets just look at the derivative of $E(z)$ which is $E(z)+z^{p-1}$.  Knowing that multiple zeros are what we want as it means less zeros total, we must add a function whose derivative is $-1$ since this will force multiple zeros.  The obvious choice is then $x^p-x$, as it leaves the original polynomial invariant.
Remark: If you ask about the truncated exponential, there are many papers in existence and probably a high level way to see the problem.  For example, see the first part of http://www.science.unitn.it/~mattarei/Ricerca/Preprints/AH.pdf
Comment: I have a technical question. Why we have $\frac{1}{\prod^{i=l}_{i=1}(p-i)}=(-1)^{l}*\frac{1}{l!}$? I cannot see this directly via Wilson's theorem (which asserts that $(p-1)!\equiv -1$(mod p).
Comment: @ChangweiZhou: Because $(p-i)\equiv -i \pmod{p}$.
Comment: My first idea was to see that if $n$ is a root then $p-n$ is not, but I only conjectured it and got me nowhere... seeing that roots are double roots is very clever. +1!
Comment: @PatrickDaSilva: That was my first idea too.  I wanted to show that $E(z)+E(-z)$ or $E(z)-E(-z)$ is never zero, but I couldn't do this.  I could show that it didn't have too many double zeros which isn\t great and only gives us $\frac{p-1}{4}$.
Answer: I'm not sure about a complete generalization, but I approached it from a partial-general point in which I turned all terms after 1 + n into a partial sum which was always even. With some basic modular arithmetic the statement appeared pretty well closed, though for the extremely large primes it's anyone's guess.
As the test still runs until tomorrow for religious exceptions I'm not yet comfortable writing out my solutions. I'll extend my response tomorrow night.
Comment: @ChangweiZhou BeRi can't comment without having 50 reputation, although in either form I would welcome more detail in this response!
Comment: I think this is more appropriate as a comment instead of an "answer" at here. Could you more elaborate on the the "pretty well closed" form you found?

Asking 2011 Putnam B6


Catching the white ball.

Question: I have a question.
There are $19$ black balls and 1 white balls (total $20$ balls) in the bin. You pick one ball each time without replacing. When is the maximal likelihood that you pick white ball?
I suspect it is on the middle (after $10$ times) but I can't prove.
Please explain in details.
Thanks in advance.
Comment: "Maximal likelihood" is almost certainly the wrong term to use here. Fortunately, your question is clear enough without the right words ...
Comment: There are three different interpretations to the question that it sounds like you might be asking.  The first interpretation: On average, how many draws are required to draw the white ball?  The second interpretation: What is the minimum number of draws you must perform to have at least a 50% chance of having drawn a white ball?  The third interpretation: Which specific draw (or draws) has the highest chance of the ball being white?  Each of these questions have different answers.
Comment: The answers to the questions in my previous comment are: 1) $10.5$, 2) $10$, 3) All draws are equally likely to be the draw to have the white ball.
Comment: @JMoravitz; I am asking for (1), i.e. on average how many draws are required to draw the white ball?
Comment: To see why the answer is $10.5$, begin by noting the third question and the answer that all draws are equally likely to be the white ball.  Then, remember the definition of the [expected value of a random variable](https://en.wikipedia.org/wiki/Expected_value) and use the interpretation that it is the weighted average of the possible results.  As they are all weighted the same, this is simply the average.  We have then the final result of $\frac{1+2+3+\dots+20}{20}=\frac{21}{2}=10.5$
Comment: Thank you @JMoravitz!
Answer: Guide:
Try computing the probability explicitly.
$P(X=1)= \frac{1}{20}$
$P(X=2)=\frac{19}{20}\frac{1}{19}$
Hopefully you can spot a pattern.
Answer: I'm guessing you're asking the third of JMoravitz's questions (but the other two could be right as well).
The probability of not having picked W after $k>0$ picks is $\frac{19}{20} \cdot \frac{18}{19} \cdots \frac{20-k}{21-k} = \frac{20-k}{20}$.
The probability of then picking the white ball is $\frac{1}{20-k}$.
So the probability of picking the white ball on the $k+1$ pick is
$\frac{1}{20-k} \cdot \frac{20-k}{20} = \frac{1}{20}$.
Comment: Given that the first pick was not the white ball, there remain $18$ black balls and one white ball out of $19$ balls total, it is no longer $20$ balls remaining.  The way you have written this as well is ambiguous without the use of $\cdots$ as it appears as though you are suggesting that each result has the product of exactly three fractions, only one of which depending on $k$.
Comment: Pure stupidity on my part and typing too fast when I had something on the stove beeping at me to deal with it...I'll fix.  Done (I think!)  (The missing "\cdots" came from my typing "\cdot". Sigh.)
Comment: @JMoravitz; I am asking for (1), i.e. on average how many draws are required to draw the white ball? – dice 1 min ago   edit

Catching the white ball.


Difference of C type and compile-time type in Cython

Question: I am new to Cython and trying to learn how to use it with numpy to accelerate the code. I have been following the tutorial in this link.
I have copied their code here:
from __future__ import division
import numpy as np

# "cimport" is used to import special compile-time information
# about the numpy module (this is stored in a file numpy.pxd which is
# currently part of the Cython distribution).
cimport numpy as np
# We now need to fix a datatype for our arrays. I've used the variable
# DTYPE for this, which is assigned to the usual NumPy runtime
# type info object.
DTYPE = np.int
# "ctypedef" assigns a corresponding compile-time type to DTYPE_t. For
# every type in the numpy module there's a corresponding compile-time
# type with a _t-suffix.
ctypedef np.int_t DTYPE_t
# The builtin min and max functions works with Python objects, and are
# so very slow. So we create our own.
#  - "cdef" declares a function which has much less overhead than a normal
#    def function (but it is not Python-callable)
#  - "inline" is passed on to the C compiler which may inline the functions
#  - The C type "int" is chosen as return type and argument types
#  - Cython allows some newer Python constructs like "a if x else b", but
#    the resulting C file compiles with Python 2.3 through to Python 3.0 beta.
cdef inline int int_max(int a, int b): return a if a >= b else b
cdef inline int int_min(int a, int b): return a if a <= b else b
# "def" can type its arguments but not have a return type. The type of the
# arguments for a "def" function is checked at run-time when entering the
# function.
#
# The arrays f, g and h is typed as "np.ndarray" instances. The only effect
# this has is to a) insert checks that the function arguments really are
# NumPy arrays, and b) make some attribute access like f.shape[0] much
# more efficient. (In this example this doesn't matter though.)
cimport cython
@cython.boundscheck(False)
def naive_convolve(np.ndarray[DTYPE_t, ndim=2] f, np.ndarray[DTYPE_t, ndim=2] g):
    if g.shape[0] % 2 != 1 or g.shape[1] % 2 != 1:
        raise ValueError("Only odd dimensions on filter supported")
    assert f.dtype == DTYPE and g.dtype == DTYPE
    # The "cdef" keyword is also used within functions to type variables. It
    # can only be used at the top indendation level (there are non-trivial
    # problems with allowing them in other places, though we'd love to see
    # good and thought out proposals for it).
    #
    # For the indices, the "int" type is used. This corresponds to a C int,
    # other C types (like "unsigned int") could have been used instead.
    # Purists could use "Py_ssize_t" which is the proper Python type for
    # array indices.
    cdef int vmax = f.shape[0]
    cdef int wmax = f.shape[1]
    cdef int smax = g.shape[0]
    cdef int tmax = g.shape[1]
    cdef int smid = smax // 2
    cdef int tmid = tmax // 2
    cdef int xmax = vmax + 2*smid
    cdef int ymax = wmax + 2*tmid
    cdef np.ndarray[DTYPE_t, ndim=2] h = np.zeros([xmax, ymax], dtype=DTYPE)
    cdef int s, t
    cdef unsigned int x, y, v, w
    # It is very important to type ALL your variables. You do not get any
    # warnings if not, only much slower code (they are implicitly typed as
    # Python objects).
    cdef int s_from, s_to, t_from, t_to
    # For the value variable, we want to use the same data type as is
    # stored in the array, so we use "DTYPE_t" as defined above.
    # NB! An important side-effect of this is that if "value" overflows its
    # datatype size, it will simply wrap around like in C, rather than raise
    # an error like in Python.
    cdef DTYPE_t value
    for x in range(xmax):
        for y in range(ymax):
            s_from = int_max(smid - x, -smid)
            s_to = int_min((xmax - x) - smid, smid + 1)
            t_from = int_max(tmid - y, -tmid)
            t_to = int_min((ymax - y) - tmid, tmid + 1)
            value = 0
            for s in range(s_from, s_to):
                for t in range(t_from, t_to):
                    v = <unsigned int>(x - smid + s)
                    w = <unsigned int>(y - tmid + t)
                    value += g[<unsigned int>(smid - s), <unsigned int>(tmid - t)] * f[v, w]
            h[x, y] = value
    return h

There is one thing I did not understand. I know that cdef defines a C type from this link about Cython language basics. However, the example above also defined a compile-time type called np.int_t, for example, in the line where it says cdef DTYPE_t value, where DTYPE_t is actually np.int_t.
My question is: what is the difference between an np.int and np.int_t? It that similar to python int versus ctypes.c_int, but more specific for numpy? In that case, would it be the same if I simply use cdef int instead of cdef np.int_t?
Also, I did test that what would happen if I replace cdef DTYPE_t value with cdef int value. The result shows no difference between them two.
This is for the original cdef DTYPE_t value
1 loops, best of 10: 93.9 ms per loop
This is for the modified cdef int value
1 loops, best of 10: 93.8 ms per loop
Any help would be appreciated. Thanks!
Answer: np.int is a Python object that references the integer dtype in Python code. np.int_t is a C typedef that only exists in Cython. (It corresponds to C long, I believe, not int.)
Comment: Thank you so much! So `cdef np.int_t` would be equivalent to saying `cdef long`, is that correct?
Comment: I guess I am mainly confused because in the example code, he used both `cdef int s, t` and then `cdef np.int_t value`. I was wondering whether there is a functional difference between these two notations, or it is just him trying to show different ways of doing the same thing.
Comment: Pretty much, yes. When using with NumPy, prefer the NumPy types to prevent confusion.


React router: Expected "state" to be defined when moving to /

Question: I have a React app which doens't have a route to / setup, so I placed a redirect inside the Switchcomponent, so whenever the user  tries to access home they are redirected to the UserHome component.
The Switch set-up is as follows:
    const AppRoutes = () => (
    <Switch>
    <Redirect
      exact
      from="/"
      to={ROUTES.CITIZEN}
    />

    <Route
      exact
      path="/login"
      component={Login}
    />

    <AuthenticatedRouteRedirect
      path={ROUTES.CITIZEN}
      component={UserHome}
    />

    <AuthenticatedRouteRedirect
      path={ROUTES.ADMIN_REPORT_LIST}
      component={reportList}
    />

    <Route
      path="/404"
      component={ErrorView}
    />

    <Route
      component={ErrorView}
    />
</Switch>

And AuthenticatedRouteRedirect as follows:
const AuthenticatedRouteRedirect = ({
  component: Component, path = '', exact = false, ...rest
}) => {
  const { user } = useAuth();
  return (
    <Route
      path={path}
      exact={exact}
      render={() => (user
        ? <Component {...rest} />
        : <Redirect to="/login" />)}
    />
  );
};

export default AuthenticatedRouteRedirect;

And my UserHome component:
const Dashboard = () => (
  <>
    <Navbar />
    <Container>
      <ActionMenu />
    </Container>
  </>
);

where ActionMenu component uses a custom hook called useReportsLocations, which its implementation is:
import React from 'react';
import { useHistory, useParams } from 'react-router-dom';
import { getMapPolygons, mexicoMap } from 'core/map-locations';

const useReportsLocations = (selectedGroup) => {
  const { push } = useHistory();
  const { state, municipality } = useParams();
  const locationData = React.useMemo(() => {
    const currentSelection = {
      country: mexicoMap,
      state,
      municipality,
      group: selectedGroup,
    };

    return getMapPolygons(currentSelection);
  }, [municipality, selectedGroup, state]);

  React.useEffect(() => {
    if (!locationData?.stateData
      || !Object.keys(locationData?.stateData?.municipality
      || {}).includes(municipality)) {
      push('/404');
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [municipality]);

  return {
    locationData,
    state,
    municipality,
  };
};

export default useReportsLocations;

Here's a little demo on CodeSandBox
But when trying to access /, this error message is displayed with the next stacktrace, sorry if it's too large:

What is the cause for this to happen? And how to fix it?
I'm having a bad time trying to figure out whatever the cause is, but simply I can't.
Thank you for your answer and replies.
Pd
Comment: Can you share the full error message and associated stacktrace? It's unclear where the error originates from.
Comment: Sure. I'll edit further the post, then.
Comment: Can you share also the `UserHome` component? Do you know of anything attempting to access route state? If it's not route state do you know what `state` is being referred to?
Comment: Sure, no problem. And as to something trying yo access state route, there's nothing trying to get access the route `state`
Comment: You know, so far I don't see any overt issues. Think you could create a running codesandbox that reproduces the issue that we can inspect and debug live.
Comment: Sure. I'll add the codesanbox the.
Answer: I finally figured out what's happening.
After I read the docs, as Redirect leads me to a route where some params are required, but I don't provide any ones to to (as seen in the ROUTES file), it has only the placeholders of {ROUTES.CITIZEN} route, and path-to-regexp@^1.7.0 will complaint that it has been passed nothing and coudn't not resolve to anything.
This behaviour is expected.


extjs4 - is there a non json/xml writer for proxies?

Question: I'm building some models to interact with an existing API from a previous project.
The API relies on standard POST methods to save the data.
I've configured a model and proxy up to the point where it does push the data onto the server but there only seems to be two writer types, json & xml.
proxy: {
        /* ... */
        reader: {
            type: 'json',
            root: 'results'
        },
        writer: {
            type: '???' // <-- can only see json or xml in the docs
        }
    }

Isn't there a standard POST writer that simply submits data in post fields?
I'm surprised that wouldn't be a standard writer type.
(Parsing the json format wouldn't be too hard to implement but that would mean updating a lot of the old api files.)
Answer: Ok, I was able to create that writer quite easily by checking the existing writers' source code.
One thing those existing writers are able to do - and that may be why the dev team only implemented a json and xml version - is that they can push multiple records at once.
That could be implemented in POST but would be a bit more complicated.
This writer will work if you're trying to push a single model to an api using POST:
Ext.define('Ext.data.writer.SinglePost', {
    extend: 'Ext.data.writer.Writer',
    alternateClassName: 'Ext.data.SinglePostWriter',
    alias: 'writer.singlepost',

    writeRecords: function(request, data) {
        request.params = data[0];
        return request;
    }
});

and the use this for the writer in the proxy:
writer: {
            type: 'singlepost'
        }

Comment: There may be a rather big problem with this method that I've only just spotted. If you use this writer on a grid, for example, and you have selected multiple rows in a random order, because you're only ever using data[0], you will end up pushing the same record to the server over and over again.
Comment: @Jangla Definitely, this is for a limited case scenario. Feel free to build upon to make a better one.
Comment: This is also pretty old, haven't done extjs for ages, couldn't help you with it.
Answer: Based on Ben answer I've implemented my own writer that will collect all properties of all models into arrays.
For example if you have model like with some fields:
fields:[
  {name:'id', type:'int'}
  {name:'name', type:'string'}
  {name:'age', type:'date'}
]

A request string will be
id=1&id=2&id=...&name=oleks&name=max&name=...&age=...

Code:
Ext.define('Ext.data.writer.SinglePost', {
    extend: 'Ext.data.writer.Writer',
    alternateClassName: 'Ext.data.SinglePostWriter',
    alias: 'writer.singlepost',
    writeRecords: function(request, data) {
        if(data && data[0]){
            var keys = [];
            for(var key in data[0]){
                keys.push(key);
            }
            for(var i=0;i<keys.length;i++){
                request.params[keys[i]] = [];
                for(var j=0;j<data.length;j++){
                request.params[keys[i]].push((data[j])[keys[i]]);
            }
        }
        }
        return request;
    }
});

Comment: Something like `id=1&id=2` wouldn't work in PHP. The second id parameter would overwrite the first one..
Comment: Thanks for your contribution. Which server language did you target that for?
I'm not sure this is going to work for PHP
Comment: Hi Ben, I am using a Java on the server side. But I think it is a no problem to get arrays in PHP also.
Comment: Sometimes ago I posted this comment. But now I wish implement something similar - so, it helps me remind all things :)
Answer: For Sencha touch 2.0, change the writeRecords method to:
writeRecords: function (request, data) {
        var params = request.getParams() || {};
    Ext.apply(params, data[0]);
    request.setParams(params);
    return request;
}

Answer: Here's my version, adapted from answers above:
// Subclass the original XmlWriter
Ext.define('MyApp.utils.data.writer.XmlInAPostParameter', {

    extend : 'Ext.data.writer.Xml',

    // give it an alias to use in writer 'type' property
    alias : 'writer.xml_in_a_post_parameter',

    // override the original method
    writeRecords : function(request, data) {

        // call the overriden method - it will put the data that I
        //   want into request.xmlData
        this.callParent(arguments);

        // copy the data in request.xmlData. In this case the XML
        // data will always be in the parameter called 'XML'
        Ext.apply(request.params, {
            XML: request.xmlData
        });

        // Already copied the request payload and will not send it,
        //   so we delete it from the request
        delete request.xmlData;

        // return the modified request object
        return request;
    }
});

Ext.define("MyApp.model.MyModel", {
    extend : "Ext.data.Model",
    requires : [
        'MyApp.utils.data.writer.XmlInAPostParameter'
    ],

    fields : [ 'field_A', 'field_B' ],

    proxy : {
        type : 'ajax',

        api : {
            read : '/mymodel/read.whatever',
            update : '/mymodel/write.whatever'
        },

        reader : {
            type : 'xml'
        },
        writer : {

            // use the alias we registered before
            type : 'xml_in_a_post_parameter'
        }
    }

});


Activity extending ActionBarActivity and YouTubeBaseActivity

Question: In my application I need to getSupportActionBar() in order to change its title and enable home as back button. I also need to have a YouTubePlayerView to display a video. I cannot extend ActionBarActivity and YouTubeBaseActivity in the same time. What is the proper way to solve such problem?
Comment: You can see here: http://developer.android.com/reference/android/support/v7/app/ActionBarActivity.html, that ActionBarActivity extends FragmentActivity
Comment: you can use YouTubePlayerFragment
Comment: @brightstar ok, now in order to get to `getSupportFragmentManager()` which I need I have to extend `FragmentActivity' so I am back with the same problem
Comment: @brightstar Yes, that solved all my problems. Thank you!
Comment: great, I added it as answer
Answer: You should use YouTubePlayerFragment instead of YouTubeBaseActivity. You will be able to extend your activity from ActionBarActivity which will allow to use both getSupportActionBar() and fragments.


Boundedness of an implicit function

Question: I have a function $h(u) : \mathbb{R}^N \rightarrow \mathbb{R}^N$ in an implicit form:
$$
A(h, u) = 0.
$$
What conditions could we put on $A$ to guarantee that $h$ is bounded? And if we have an explicit functional $F$, what would be the conditions to guarantee that $F(h(u))$ is bounded as a function of $u$?
Comment: Do you know anything about $A$? Why can it not be the constant $0$ function?
Comment: @Clayton, $A$ will be basically given explicitly, once I plug in the assumptions, however it will not have an explicit solution for $h$. I would like to find some conditions on $A$ that guarantees boundedness of $h$ and/or $F(h)$, so that I can fiddle with the assumptions.
Comment: Ah, so maybe your question can better be worded something like: What conditions can we put on $A$ to guarantee that $h$ is bounded? Or have I misinterpreted your comment?
Comment: @Clayton, fixed, thanks!
Answer: The following are evidently equivalent:

$\|h(u)\|\le M$ for all $u\in \mathbb R^N$
$A(h,u)\ne 0$ whenever $\|h\|>M$

Since the set $\{h\in \mathbb R^N : \|h\|>M\}$ is connected when $N>1$, condition 2 means that either

(2a) $A(h,u)> 0$ whenever $\|h\|>M$, or
(2b) $A(h,u)< 0$ whenever $\|h\|>M$.

Given explicit $A$, it is usually not difficult to check that  (2a), (2b) hold or fail.
For the second question: $F\circ h$ is bounded if and only if $F$ is bounded on the range of $h$. So, if $\|h(u)\|\le M$ for all $u$  (as above), then you only need $F$ to be bounded on the closed ball of radius $M$. In particular, the continuity of $F$ will be enough to conclude that $F\circ h$ is bounded in this case.

Boundedness of an implicit function


Swift calculating a new point x distance in y direction

Question: I'm doing some code in sprite kit and want to calculate a position of a sprite based on a start location and moving it In a given direction and distance. For example, assuming I'm using degrees with 0 meaning straight up, I want to move the sprite from it's current position in the 45 degree (up and right) direction 10 points.
Trigonometry isn't my strength and I've been struggling to figure out how to apply it. Moving in the 45 degree direction seems pretty straight forwards, but I'm not sure how to calculation for directions like 110 (down and right) or 225 (down and left).
My first attempt looks like this:
public func offset(byDistance distance:CGFloat, inDirection degrees:CGFloat) {
    let vertical = sin(degrees) * distance
    let horizontal = sqrt(pow(distance, 2.0) + pow(vertical, 2.0))
    self.position = self.position.applying(CGAffineTransform(translationX:horizontal, y:vertical))
}

But I don't think it's working as the results look like this:
Direction 45, distance 88.26 -> New location {75.10, 115.88}
Direction 135, distance 88.26 -> New location {7.79, 88.60}
Direction 225, distance 88.26 -> New location {-82.09, 120.53}
Direction 315, distance 88.26 -> New location {65.76, 110.06}

Can anyone give me some clues as to where I've gone wrong?
Answer: Here are a few clues:

sin() takes radians not degrees, so you need to convert.
0 is right, not up so you need to adjust for that.
use cos() for horizontal.

This is closer to what you need:
public func offset(byDistance distance:CGFloat, inDirection degrees:CGFloat) {
    let radians = (degrees - 90) * .pi / 180
    let vertical = sin(radians) * distance
    let horizontal = cos(radians) * distance
    self.position = self.position.applying(CGAffineTransform(translationX:horizontal, y:vertical))
}

Comment: Thank you that worked perfectly. Trig was always something I struggled with at school because I always had problems trying to understand how it worked. I've been coding for over 30 years now and it still drives me nuts trying to understand it. I'm still reading internet sites on maths so I'll keep plugging away :-)
Comment: I think the one big thing I missed was that the functions work in radians. All the math sites I'd looked at worked in degrees. I also noticed that if I used the OS X calculator, it uses degrees by default where as if I type in 'sin(45)' or similar in OS X's Spotlite search, it uses radians.
Comment: iOS and Mac OS trig functions ALWAYS use radians. Most sites that describe trig functions use degrees because they're more intuitive. If you understand that the circumference of a circle is 2∏ • radius, and you assume the radius is 1 unit, you can think of an ant walking along the outside of the circle. If it walks ∏/2 units, it will have traveled 1/4 of the way around the circle. Once it's walked ∏ units, it will be halfway around the circle. When it's walked 2∏ units, it will have completed a full circle. That's how radians work.
Answer: There are 2 (actually 3, but let's ignore the 3rd) separate notations for trigonometric functions like sine and cosine: Degrees and Radians. Both describe angles. Degrees range from 0 to 360, and radians range from 0 to 2π.
Converting between them is trivial:
degrees = 180 * radians / π
radians = degrees / 180 * π

iOS and Mac OS use radians for their trig functions.
You can either continue to track your angles using degrees and then convert to radians before feeding the values into your trig functions, or convert to using radians.
If you understand that the circumference of a circle is 2π • radius, and you assume the radius is 1 unit, you can understand radians by thinking of an ant walking along the outside of the circle. The total path along the circumference (outside) of the circle is 2π units in distance. If the ant walks π/2 units, it will have traveled 1/4 of the way around the circle. Once it's walked π units, it will be halfway around the circle. When it's walked 2π units, it will have completed a full circle. That's how radians work.
Comment: Man, the pi symbol in the SO font is ugly! The lower-case pi looks like 2 Ts, and the upper-case PI looks like an upside-down U. Both are barely recognizable. The lower case pi in the code font is the only one that looks halfway decent.
Answer: If you would prefer simpler way without trigonometry - you can use point distance:
func CGPointDistanceSquared(from: CGPoint, to: CGPoint) -> CGFloat {
    return (from.x - to.x) * (from.x - to.x) + (from.y - to.y) * (from.y - to.y)
}

func CGPointDistance(from: CGPoint, to: CGPoint) -> CGFloat {
    return sqrt(CGPointDistanceSquared(from: from, to: to))
}


Appending multiple objects to an element

Question: I'm trying to append the same object multiple times to the same area, but its not working.
 $("div").each(function(){
   var $input = $("<input type=text/>").css("display","none");
   $(this).append($input).append($input);  // <--this only shows 1 box
 }

I tried $(this).append($input + $input);, but it shows [object Object] twice instead. Suggestions?
Comment: $(this).append($input.clone()).append($input.clone())
Comment: http://api.jquery.com/append/: _"If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned)"_
Answer: what about
var $input = $(document.createElement('input')).attr('type','text').css({display:'none'});
$(this).append($input.clone()).append($input.clone())

Comment: works fine, but don't see why you need `.clone()` on both appends
Comment: you need to use .clone() for second .append(). When you appending element to container, the element disapears from the previous location. Dom element must have only one parent.
Answer: by doing $input + $input they both get their .toString() methods ran so you're basically running .append("[object Object][object Object]")
and by doing .append($input).append($input); you are attempting to append the same DOM Element twice in the same containing element, which is impossible because only one instance will ever exist. The solution is to clone the DOM Element, you can do this in jQuery by .clone() and in vanilla javascript by .cloneNode().
you can try
$("div").each(function(){
    var $input = $("<input type=text/>").css("display","none");

    $(this)
        .append($input) // use the original element
        .append($input.clone()); // clone the original element
}

Comment: @ZeeTee: because this is the answer.
Comment: @DavidKnipe i did provide a suggestion
Comment: @ZeeTee i also added a explanation to why your other attempt didn't work


Passar id de objeto de activity para outra

Question: Estou tentando passar o id do meu objeto para outra activity utilizando Serializable, mas está me retornando um maldito erro que eu não sei consertar.

Obs: meu objeto já implementa serialiable

O meu código é o seguinte:
if (view == btnTeste) {
        try {
            repositorioUsuario = new RepositorioUsuario(this);
            repositorioUsuario.insertUsuario(inserirUsuarioTeste());

            Intent it = new Intent(this, Parceble.class);
            it.putExtra("usuario", modeloUsuario.getId());
            startActivity(it);
        } catch (Exception e) {
            Log.i(CATEGORIA, e.toString());
        }
    }

E na outra activity:
Usuario user = (Usuario) getIntent().getSerializableExtra("usuario");

    int id = 1;
    if(user != null){
        id = user.getId();
        if ( id != 0){
            Toast.makeText(Parceble.this, "id: " + id, Toast.LENGTH_SHORT).show();
        }
    }

E o erro que está dando é:

10-07 19:23:28.031  18317-18317/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
      Process: br.com.refsoft.refsoft, PID: 18317
      java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.refsoft.refsoft/br.com.refsoft.refsoft.activity.Parceble}: java.lang.ClassCastException: java.lang.Integer cannot be cast to br.com.refsoft.refsoft.domain.Usuario
              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
              at android.app.ActivityThread.access$800(ActivityThread.java:135)
              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
              at android.os.Handler.dispatchMessage(Handler.java:102)
              at android.os.Looper.loop(Looper.java:136)
              at android.app.ActivityThread.main(ActivityThread.java:5001)
              at java.lang.reflect.Method.invokeNative(Native Method)
              at java.lang.reflect.Method.invoke(Method.java:515)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
              at dalvik.system.NativeStart.main(Native Method)
       Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to br.com.refsoft.refsoft.domain.Usuario
              at br.com.refsoft.refsoft.activity.Parceble.onCreate(Parceble.java:18)
              at android.app.Activity.performCreate(Activity.java:5231)
              at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
              at android.app.ActivityThread.access$800(ActivityThread.java:135)
              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
              at android.os.Handler.dispatchMessage(Handler.java:102)
              at android.os.Looper.loop(Looper.java:136)
              at android.app.ActivityThread.main(ActivityThread.java:5001)
              at java.lang.reflect.Method.invokeNative(Native Method)
Answer: O erro acontece porque você não está passando um objeto Usuario no intent e sim apenas o seu id, que é um inteiro. Passe um objeto da classe Usuario que irá funcionar.
Note que será necessário fazer um "cast" (forçar mudança de tipo) de Usuario para Serializable para a operação funcionar. Por exemplo, supondo que o objeto modeloUsuario seja do tipo Usuario:
it.putExtra("usuario", (Serializable)modeloUsuario);

Agora se a sua intenção for realmente passar apenas o id e não o usuário inteiro, então o problema está na outra ponta. Na segunda Activity pegue o id usando getIntExtra() em vez de getSerializableExtra().
Comment: Entendi! mt obrigado!!!
Answer: Você esta passando o id, um tipo inteiro
it.putExtra("usuario", modeloUsuario.getId());

E o erro acontece nesta linha abaixo, pois você está tentando recuperar um Objeto do tipo usuario quando na verdade é um numero inteiro.
Usuario user = (Usuario) getIntent().getSerializableExtra("usuario");

Troque por
int id = getIntent().getIntExtra("usuario",-1);

Comment: Entendi! mt obrigado!!!


What does the following mean for sets?

Question: What does the following mean in terms of sets? Can someone explain this in words?
$$\{x \mid I \vDash \varphi(x)\}$$
where $I$ is an interpretation
Answer: All $x$ such that $\varphi(x)$ is true in this interpretation.
Answer: $\{x \mid I \vDash \varphi(x)\}\;\;$ is the set of all $\;x\;$ such that $\;\varphi(x)\;$ is true in the given interpretation $I$.

What does the following mean for sets?


A batter overruns first base, but misses the bag. Is then tagged out. Does the runner on 3rd score?

Question: Here's something that happened at a game recently and I can't find the answer to it: 2 outs, runner on 3rd. Batter hits a slow roller to third. The third baseman picks it up but makes a bad throw to first, pulling the first baseman off the bag.
The batter-runner runs right over the bag, never touching the base.
The runner on third has now crossed the plate. The first baseman sees that the runner missed the bag and tags the runner as he is walking back to the base. Runner is out.
But does the run score? The umpire ruled that he did not score.
I've read that a runner cannot score on a third out unless the batter reaches first safely. But I've also read that the umpire should have called the batter-runner safe at first when he crossed base (even though he didn't touch it) as it gives an un-fair advantage to not make any call at all. I've seen this in the MLB, so I'm pretty sure that's true. If the runner is initially safe at first, then that means the run does in fact score. Any idea?
Answer: This is actually addressed pretty specifically in a comment in the 2016 version of the Official Baseball Rules pdf.
The comment to Rule 5.08 (pages 37-38) has this approved ruling:

APPROVED RULING: No run shall score during a play
  in which the third out is made by the batter-runner before
  he touches first base. Example: One out, Jones on second,
  Smith on first. The batter, Brown, hits safely. Jones
  scores. Smith is out on the throw to the plate. Two outs.
  But Brown missed first base. The ball is thrown to first,
  an appeal is made, and Brown is out. Three outs. Since
  Jones crossed the plate during a play in which the third
  out was made by the batter-runner before he touched first
  base, Jones' run does not count.

and this approved ruling:

APPROVED RULING: Two out, bases full, batter hits
  home run over fence. Batter, on appeal, is declared out
  for missing first base. Three outs. No run counts

In both cases, the batter-runner is the third out on the play for missing first base. No runs score.
Answer: Lifting much of my answer heavily from Wax Eagle's answer here:
From MLB rule 5.09(c)(2)

[The runner is out on appeal when] With the ball in play, while advancing or returning to a base, he fails to touch each base in order before he, or a missed base, is tagged.

This basically means that a runner is considered safe after they've rounded first base without touching it, that is until either he or the base he missed is tagged before he returns to it and the fielding team appeals to the umpire.
However, this specific scenario is addressed in rule 5.09(d)

Unless two are out, the status of a following runner is not affected by a preceding runner's failure to touch or retouch a base. If, upon appeal, the preceding runner is the third out, no runners following him shall score. If such third out is the result of a force play, neither preceding nor following runners shall score.

I read this as meaning that a "missed base out" (i.e. missed the base and then tagged out) can still be effectively counted as a force play out; being the third out of the inning, no runner can score.  In the situation you describe, the umpire might have technically needed to have been appealed to, but in practice there often isn't an official verbal appeal--the umpire knows the deal.
Although the batter/runner would have been safe if he touched the bag and although he was considered safe for a few moments before getting tagged, he ultimately did not safely reach first base to avoid the force out.
Answer: The umpire was correct. Batter /Runner is assumed to have touched first base when he passes by it even if he missed it. When the throw comes late he is not automatically out just because he missed the base. Defensive team must appeal to umpire before batter/runner comes back to touch the base. Then with the ball step on first or tag batter/runner. "Hey ump he missed the bag."  If on appeal he is called out the run does not count.
Comment: The rules and explanations quoted in Duncan's answer *from over a year ago* make it clear that the batter-runner is out for not touching the base and no runs count.
Comment: Welcome to Sports SE, like other answer to this question try to add reference to your answer.


Flutter - ConstrainedBox does not work if it contains a Row() or a Column()

Question: The title pretty much says it all - I am finding that the ConstrainedBox widget does not work if it contains a Row or a Column.
Here is my code:
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Testing ConstrainedBox'),
      ),
      body: ListView(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 25),
        children: [
          ConstrainedBox(
            constraints: const BoxConstraints(maxWidth: 600),
            child: Card(
              color: Colors.yellow,
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 15),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(right: 20),
                      child: Container(
                        color: Colors.red,
                        height: 50,
                        width: 50,
                      ),
                    ),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        mainAxisAlignment: MainAxisAlignment.center,
                        mainAxisSize: MainAxisSize.min,
                        children: const <Widget>[
                          Text('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'),
                          Padding(
                            padding: EdgeInsets.only(top: 20),
                            child: Text('Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'),
                          ),
                          Padding(
                            padding: EdgeInsets.only(top: 20),
                            child: Text('Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.'),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

If you run this and make the window bigger then the "maxWidth" does not apply and instead the Card grows to the full width available to it.
I tried putting the ConstrainedBox inside the Row but that makes no difference, presumably because of the Col. Note also that getting rid of the ListView does not change anything.
Anyone got any idea why this doesn't work?
Answer: ListViewis forcing its children to have max width. You can wrap the children with another widget that will cover it.
body: ListView(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 25),
        children: [
          Align(
            alignment: Alignment.centerLeft,
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 600),

Comment: No, that doesn't work. Note that if I remove the ListBox altogether I get the same problem
Comment: can you try `flutter clean` and rebuild the app.
Comment: well that does seem to fixed it, but why did I need to clean and then rebuild my packages - is this something that has just been fixed and I just happened to have an old version of the "material" package (or maybe another package) with a bug?
Comment: ig sometime cache issue on debug mode,
Comment: OMG that is horrible! thanks for your advice :-)


Ubuntu Cordova - Build com problema

Question: Pessoal estou subindo o cordova no Ubuntu 64, mas estou com problema no build.
[Error: Failed to find 'ANDROID_HOME' environment variable. Try setting setting it manually.
Failed to find 'android' command in your 'PATH'. Try update your 'PATH' to include path to valid SDK directory.]

ERROR building one of the platforms: Error: /home/boschini/Desktop/Cordova/ProjetoX/platforms/android/cordova/build: Command failed with exit code 2

You may not have the required environment or OS to build this project
Error:
/home/boschini/Desktop/Cordova/ProjetoX/platforms/android/cordova/build: Command failed with exit code 2

Meu ~/.bashrc
JAVA_HOME=/usr/lib/jvm/java-7-oracle
export JAVA_HOME
PATH=$PATH:$JAVA_HOME

export ANDROID_HOME=/home/boschini/Android/Sdk
export ANDROID_TOOLS=/home/boschini/Android/Sdk/tools
export ANDROID_PLATFORM_TOOLS=/home/boschini/Android/Sdk/platform-tools

export PATH=${PATH}:/home/boschini/android-sdk-linux/platform-tools
export PATH=${PATH}:/home/boschini/android-sdk-linux/tools

Quando chamo android no console, ele abre o SDK Manager normal, consigo abrir o AVD, mas quando vou dar build no cordova, ele apresenta esse erro.
Meu android studio funciona, ja consegui compilar um projeto de widget que tenho, sem problemas, o Cordova que está dando zica.
Answer: Consegui resolver algumas horas e muitos copos de café depois.
O problema ocorre por conta de permissões, quando rodei o cordova build sem sudo ai o problema nao ocorreu.
Então para não cair nessa situação eu dou sudo su e trabalho sem sudo com o cordova, ai nao deu problema.
Caso o problema persista, tem que analisar permissão de algumas pasta.

Ubuntu Cordova - Build com problema


How to export and use results of PCA from R?

Question: My ultimate goal is to run a cluster analysis on a data set with > 1 million records. The input variables for the cluster analysis will be the results of a Principal Component Analysis, as well as other variables not included in the PCA, for a total of maybe 10 variables input into the clustering (the variables I input into the PCA were all very highly correlated with one another while the other variables are not so I chose not to include them in the PCA).
<code>#read data
mydata <- read.csv('mydata.csv')

#import library for robust methods because my data contained outliers
library(rrcov)

#run robust PCA method called PcaCov
pcaR <- PcaCov(~., mydata, na.action=na.omit, center=TRUE, scale = TRUE, k=8)

#look at results
summary(pcaR)
screeplot(pcaR)
pcaR@loadings
</code>
From the results, I have decided I would like to retain the first three components, which capture ~87% of the total variance in the dataset.
Now I want to extract/save/export these first three components for use in the cluster analysis with my other variables. How do I do this?
Answer: For each variable obtained by PCA you have a loading vector (for example $v=(1,-2,5,5)$ this vector define your new variable as combination of the original ones. $x_1-2x_2+5x_3+5x_4$.
You can define a new matrix where the variables are obtained as the linear combination defined by the loadings obtained with PCA. So for example $z_1=x_1-2x_2+5x_3+5x_4$.
Comment: Thanks @Donbeo. I have edited the code above based on your suggestion (basically if I understand correctly, I multiply the loadings by the original variables?). I don't do anything with the scores??
Comment: No wait this is not what I meant. If the function allows you to extract the scores than this is already the representation of X in the new base. This would probably be of the same number of columns of the original X. Be careful that usually PC and loadings are the same thing. Be also careful that probably you are not doing the matrix multiplication with the right command
Comment: Ok so I guess I just export the scores!


Chrome window.print() missing page elements

Question: I am currently having an issue with Chrome (47.0.2526.111, OS X) not rendering the whole page both in preview and when printed when using a button, with a onclick=window.print() event.
Certain elements are not rendered, such as some paragraph blocks and occasionally some images.
This issue is not replicated in an other browser, and oddly enough only appeared once I added a print button, and the behaviour is not observable when using Ctrl+P or in the Chrome print stylesheet media emulation.
The issue seems very temperamental, if I have rendered the print view via a Ctrl+P I am able to go back and use the print button successfully with all elements rendering.
Comment: are u using a separate css file with `media="print"` or not?
Comment: yes I am using a seperate print stylesheet
Comment: Still experiencing this issue, as mentioned above, I do use a seperate print media stylesheet. Issue cannot be reproduced when using Ctrl + P, and no problem whatsoever with Safari, Firefox or even IE11.
Comment: @Trix, as mentioned above, it does not.
Answer: Use separate print.css file for media="print":
<link rel="stylesheet"  type="text/css" href="path/to/print.css" media="print">

in your media queries:
@media print{
    div.print{
      width: 100%;
    }
}


Openshift permission denied for upload and changing directories through sftp in filezilla

Question: I can't upload or change directory permission through sftp in filezilla; copying is fine though. I'm getting permission denied for this. Even through PuTTy sftp, sudo returns a permission denied. How do i get around to accessing files just so i can change the alias for phpMyAdmin?
I'm using the login details given by Openshift.
Comment: Are you trying to use SSH or SFTP to view and modify file contents? If you instead meant SSH please edit your question. If you're using SFTP, using SSH instead would give you a shell and allow you to sudo.
Answer: Users of OpenShift Online do not have access to sudo.
Thought you can(this is 100% unsupported) copy https://github.com/openshift/origin-server/tree/master/cartridges/openshift-origin-cartridge-phpmyadmin to its own git repo and add that as a custom cartridge instead of phpMyAdmin.
If you did that you can edit https://github.com/openshift/origin-server/blob/master/cartridges/openshift-origin-cartridge-phpmyadmin/versions/shared/conf.d/phpMyAdmin.conf and change the alias.


Test series for convergence: $\sum\limits_{n=0}^{\infty} (-1)^n \frac{\sqrt{n}}{n+1}$

Question: Test the series for convergence $\sum\limits_{n=0}^{\infty} (-1)^n \frac{\sqrt{n}}{n+1}$.
By using the Leibniz criterion, I'd have to show that the sequence $a_n = \frac{\sqrt{n}}{n+1}$ is monotonous and that it converges to $0$.
For the limit, I have $\lim\limits_{n \to \infty} \frac{\sqrt{n}}{n+1} = \lim \frac{\frac{\sqrt{n}}{n}}{\frac n n + \frac 1 n} = \frac 0 1 = 0$.
Is there any other step I could put in-between to make it more obvious or correct?
However, for the monotony, I'm kind of stuck. I've tried by induction, but I can't see how to get from $a_{n+1} \le a_n$ to $a_{n+2} \le a_{n+1}$
Comment: Simply continue proofing $a_{n+1}2$ $$\frac{1-n}{2 \sqrt{n} (n+1)^2}<0$$
Comment: @Raffaele: No derivation necessary. The OP wants to use simply the Leibniz criterion.
Comment: @user90369 thanks, that worked, so stupidly simple.
Comment: Now you've got it! (You were on the right track right from the start) :-D
Answer: Your series converges by Leibniz test.
Indeed, Setting the function $$f(x) = \frac{\sqrt{x}}{x+1} \implies f'(x) =\frac{1-x}{2\sqrt{x}(x+1)^2} \le 0~~for ~~x\ge 1$$
Then, the sequence $${n \mapsto} \frac{\sqrt{n}}{n+1} \qquad \text{is stictly decreasing } $$ and and we also have,
 $$\lim\limits_{n \to \infty} \frac{\sqrt{n}}{n+1}  = 0\qquad \text{ } $$
Hence your series $$\sum\limits_{n=0}^{\infty} (-1)^n \frac{\sqrt{n}}{n+1}$$converges by Leibniz test.
Comment: I have added the prove of the monotonicity? as well.
Comment: I am fine now, sorry if I triggered a downvote, (+1) to counter-act it.
Comment: Unfortunately, I haven't learned about it yet, so I'm not allowed to use it.
Comment: @JackD'Aurizio maybe I did write in a wrong way . But did not meant that the limit goes to 0 implies that the sequence is decreasing. Here I meant goes to zeros and decrease.:)
Comment: I fixed it now tell if it is correct or not?
Comment: Why did someone down vote this?
Answer: In order to prove that $n\mapsto \frac{\sqrt{n}}{n+1}$ is decreasing on $\mathbb{N}^+$, it is enough to prove that $g:n\mapsto\sqrt{n}+\frac{1}{\sqrt{n}}$ is increasing. Since $g(n) = 2\cosh\left(\frac{1}{2}\log n\right)$ that is trivial by composition of non-negative and increasing functions on $\mathbb{R}^+$. It follows that $\sum_{n\geq 1}\frac{\sqrt{n}}{n+1}(-1)^n$ is (conditionally) converging by Leibniz' test.
Answer: There's no induction needed here -- i.e., you don't need to get from $a_{n+1}\le a_n$ to $a_{n+2}\le a_{n+1}$.  Instead, you just need to prove that $a_{n+1}\le a_n$, which is straightforward: Since all the $a_n$'s are non-negative, we have the string of equivalences
$$\begin{align}
{\sqrt{n+1}\over(n+1)+1}\le{\sqrt n\over n+1}
&\iff{n+1\over(n+2)^2}\le{n\over(n+1)^2}\\
&\iff(n+1)^2\le n(n+2)^2\\
&\iff n^3+3n^2+3n+1\le n^3+4n^2+4n\\
&\iff 1\le n^2+n
\end{align}$$
The final inequality is clearly true for $n\ge1$, hence so is the inequality $a_{n+1}\le a_n$ (for $n\ge1$).
Remark:  It would make sense to start the summation with $n=1$ rather than $n=0$, since $a_0=0$.
Answer: 1)Limit:
$a_n := √n/(n+1).$
$0 \lt √n/(n+1) \lt √n/n = 1/√n.$
$\lim_{n \rightarrow \infty} a_n \le \lim_{n\rightarrow \infty }(1/√n) =0.$
2) Monotonicity:
$a_n = √n/(n+1) = \dfrac{1}{√n + 1/√n)}$
is strictly decreasing.
Consider: $ f(x)= x +1/x, x >1.$
$f'(x) = 1 -1/(x^2) >0$, I.e
$f(x)$ strictly increasing.
$\rightarrow:$
$[f(x)]^{-1}$ strictly decreasing.
Can you take it from here?
Answer: For the limit, equivalents are much shorter: $n+1\sim_\infty n$, so
$$\frac{\sqrt n}{n+1}\sim_\infty\frac{\sqrt n}{n}=\frac1{\sqrt n}\to 0.$$
\begin{align}
&\text{For the monotony: }& a_{n+1}<a_n&\iff a_{n+1}^2=\frac{n+1}{(n+2)^2}<a_n^2=\frac  n{(n+1)^2}&\qquad\qquad&\\
&&&\iff (n+1)^3<n(n+2)^2\iff1<n^2+n.
\end{align}
Answer: Let $f(x)=\frac{\sqrt x}{x+1}$. Then $a_n=f(n)$. Since
$$ f'(x)=\frac{1-x}{2\sqrt x(x+1)}\le 0 $$
$\{a_n\}$ is decreasing. Noting $ \lim_{x\to\infty}f(x)=0$, one obtains that $\sum_{n=1}^\infty(-1)^na_n$ converges.


how to get pre-populated result for custom google search in javascript

Question: Wanted to achieve google custom search result like below
expected result (without any popup):

But i'm getting result something like below one

Observe the above result is not pre-populated and does not give resume tags like Indeed,LinkedIn
When i search for software developer resume  then it will give me result like below one

Question: please help me to get pre-populated result like 1st image without any popup
Here is what i have tried:

(function() {
    var cx = '005502706694827175734:jh1_mjmyukc';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
    '//www.google.com/cse/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
  })();
<gcse:search linktarget="_parent" resultsUrl="https://cse.google.com/cse/home?cx=008650345519931166596:ni_z2d9ca00#gsc.tab=0&gsc.sort=&gsc.ref=more%3Alinkedin"></gcse:search>

// this url gives Indeed,LinkedIn related results https://cse.google.com/cse/home?cx=008650345519931166596:ni_z2d9ca00#gsc.tab=0&gsc.sort=&gsc.ref=more%3Alinkedin
Answer: Try using the "two page" layout as described on these pages:
https://support.google.com/customsearch/answer/2633315
https://developers.google.com/custom-search/docs/tutorial/implementingsearchbox


function definition with function

Question: I would like to know if defining a function within a function is a good practice in JavaScript.
Here is an example:
module.exports = function() {
  function foo() {
    // do something
  }

  ...
  foo()
  ...
}

To me, this looks very strange. But I see this often when reading open source projects.
Is it better to define foo outside of the scope of module.exports in the above example? Why and why not?
Comment: inside a module, it doesn't really matter where you define it, but if exports is expensive to execute, it might make more sense to use closure to pull the function in from inside so as to not re-init that supporting functionality.
Comment: Please explain how I can improve this question when downvoting. I know It might be a nooby question, but I was genuinely curious.
Comment: @MikeC—don't expect down voters to explain their vote, not everyone has good manners. One up is worth 5 down so not difficult to overcome. ;-)
Answer: In Javascript a function can be defined at the global scope or in any function scope.  As a general good design practice, you want to limit the scope of a function to only that scope that needs to call it.  That means that often you define locally used functions within other functions.
In addition, function declarations declared within another function scope can also access all the other variables within that scope which can be extremely useful.
This serves a number of general benefits:

It keeps the function private to only the scope that needs to use it (it cannot be called from outside the scope in which it is defined unless a reference is explicitly passed to some other function or variable outside the scope).
It keeps you from polluting a top level scope with zillions of named functions, some of which might even have conflicting names in a very large project.  In node modules, this is not so much the case because a node module is already a limited scope.
It allows a function to have access to the other variables within that scope.

That was the "general" discussion.  Now, within a node module, the code in the module is already within a private scope so it is not as important to declare a function within the exports function as you've done, but I generally follow a practice of declaring a function only in the scope in which it will be used.
In addition, many functions can be declared inline and anonymously and don't even need a name.
In your specific example:
module.exports = function() {

  var cntr = 0;

  function foo() {
    // do something
  }

  ...
  foo()
  ...
}

It really depends upon what you're using foo for.  If you are never using it in any other scope, then I would favor declaring it within that scope as you've done.
If you need or want to access other variables within that scope such as the cntr variable I've shown, then it must be declared within the scope.
Comment: The same person that down voted my post, did the same for your post. Since, yours is a far more detailed answer, I will remove mine (+1 from me).
Comment: @dandavis I had exactly the same question...:(
Comment: just to clarify my first comment, if a thing like `var cntr = 0;` above were expensive to init, then it might make sense to move it out of the exports function, since that gets executed each time require() is used on the module...
Comment: @dandavis - actually, it doesn't get called on just the `require()`.  The function shown here would only get called if they actually loaded it with `require()` and then called the module constructor explicitly as in `var myModule = require('moduleName');   myModule();`.  But, to your point, variables should be declared in the appropriate scope so something in the module constructor will get reinitialized each time the module constructor is called (which is sometimes what you want and sometimes not).
Comment: Downvoter, please explain so I can address whatever concern you apparently had.
Comment: fair enough, but what's the point of requiring a function that doesn't get used? to be even more clear: assuming it gets used, assuming it's expensive, assuming it can be "stale", and assuming it's required/init'd 1+ times, then moving a depend above the exports-assigned function can save time instantiating.
Comment: @dandavis - the module can have other methods or properties that are accessed.  One does not always have to call the module constructor.  The location of a variable like `cntr` is not about saving time - it's about whether it is supposed to be initialized only once when the module is first loaded or whether it's supposed to be initialized each time the constructor is called.  Those are different use cases for different types of variables and what type of variable it is should drive where it is declared.
Comment: i was trying to give one example of when not to inner-declare, but given the elaborate qualifications, it stand to reason that most of the time, you probably want to declare inside as shown ;)

function definition with function


How do properly repaired cracks in the body of an acoustic guitar affect sound (if at all)?

Question: A guitar I'm looking to buy (acoustic flamenco guitar, Alhambra) has a crack in the top (is that the correct term for the "audience-facing wooden panel"?), running closely alongside the neck all the way from the hole to the edge where the neck leaves the body. The crack has been repaired by a professional.
I assume that the crack is properly repaired, so that there is no risk for the crack reopening, growing or causing further problems (I understand that cracks running perpendicular to the neck are more dangerous in that respect, since they are constantly under stress due to string tension). But is it likely that the sound of the guitar is affected by a crack such as the one described? I am particularly worried since the crack connects with the sound hole.
(EDIT: I realize the question in the title is more generally posed than the one in the post. However, a more general answer, discussing different body crack types, would also be very welcome)
Comment: Caution is advised as per your assumption "...that the crack is properly repaired." I suggest you request the seller to allow you to have a luthier inspect the repair before you purchase. Getting an expert to examine this guitar is well worth the investment as there may be other issues with the instrument that are not visible to you. A crack such is this is not common and invites the question, was the instrument in an accident?
Comment: "Top" is the correct term. "Soundboard" is a synonym.
Answer: The sound will absolutely be affected; how much is hard to say.  You should definitely play it and see how it sounds.
The soundboard of an acoustic guitar is designed to amplify the vibration of the strings, and if it's not one piece the pieces are laid together carefully to help prevent dampening of the vibration.  It's generally best if the grain of the wood is all one direction, for example.  A crack interrupts the vibration and stops it from transmitting.
If repaired, some vibration continues to be transmitted across the crack, but not as much.  It's similar to cutting a wire and then soldering it back together — electricity can still pass through, but the soldered point is higher resistance than it was before.  The extreme case would be a crack that completely splits the soundboard in half, which would have a major negative effect (similar to not soldering the wire together properly).
Your crack, being on the upper portion only, may not be as significant, though certainly more so than (for example) a small split in the middle of the wood.  I think it's probably also good that the crack is parallel to the neck, since I would expect most of the vibration to also be parallel to the neck at that point.
Comment: Thanks! In the end, I decided not to buy. I became increasingly worried about the effect of the crack on the structural integrity and the sound.
Answer: My father has a 1979 Ramirez guitar that got damaged. He took it to a local luthier who repaired it. The guitar still sounds wonderful. I would imaging that your guitar should retain the sound that it had before. If you like how the guitar sounds then you should buy it.


store mechanism between array and arraylist?

Question: in java, if we store 4 elements in array and array list, is it same at low level in memory OR does it make any difference in order to store elements ?
Answer: It's going to be different.  An ArrayList is a wrapper around the array with several other helper functions.  The memory footprint is going to be a little bit bigger for ArrayList, and it will resize itself as necessary.
Answer: It differs, ArrayList  internally manages its own array for storage and has own attributes also
Answer: An array is pretty different from a List, even if the list happens to be an ArrayList and internally uses just an array as well.
For the array there exists just the array (for this discussion I'll ignore the memory the elements will occupy). Thus you have one object in the heap, the array itself.
For the ArrayList, there exists the ArrayList instance and that instance internally has an array. So there are two objects on the heap. Also, while you have exact control over the size of an array you create, the array held by the ArrayList can have any size that is >= number of elements <= Integer.MAX_VALUE.
Coincidentily, ArrayList uses an elements index directly as array index internally, so the order of elements is the same as in a plain array. But thats an implementation detail, and you normally don't care how a List organizes its data internally (after all the purpose of Lists is to abstract the messy details away).


Using (Or ||) syntax inside of React useState for assignment

Question: I'm observing a new syntax I haven't seen before in the react useState hook. It's

const [thing, setThing] = useState(thing || otherThing);

I've never seen that or construction used inside of useState before. I know it is a javascript native logic operator, but I'm curious exactly how to interpret it inside the context of useState.
Does it essentially mean, "if either of these things are true, set it to thing? " Is it assuming both of them can never be true at the same time?
Comment: If `thing` is truthy, it will be used to initialize the `useState`. If it is falsy, `otherThing` will be used.
Comment: Does this answer your question? [JavaScript OR (||) variable assignment explanation](https://stackoverflow.com/questions/2100758/javascript-or-variable-assignment-explanation)
Comment: https://stackoverflow.com/questions/2100758/javascript-or-variable-assignment-explanation
Answer: Its just used as a terse syntax for declaring a fallback. If the first variable is falsy, it will fall back to the second.
Example with null first value:

const {useState} = React;

const test = null;
const fallback = 'fallback';

const Example = () => {
  const [state, setState] = useState(test || fallback);

   console.log("state: ", state); // Logs the value of fallback

   return
}

ReactDOM.render(<Example />, document.getElementById('root'));

But if the first variable is truthy, it gets used:

const {useState} = React;

const test = 'first priority';
const fallback = true;

const Example = () => {
  const [state, setState] = useState(test || fallback);

   console.log("state: ", state); // Logs the value of test

   return
}

ReactDOM.render(<Example />, document.getElementById('root'));

Answer: The Double Pipe Operator (Logical OR) in Javascript will return the first value that could be converted to true.
This is not exclusive to React, it is a baked in vanilla-JS operator that you may use anywhere.
Here are some examples (taken from MDN):
o1 = true  || true       // t || t returns true
o2 = false || true       // f || t returns true
o3 = true  || false      // t || f returns true
o4 = false || (3 == 4)   // f || f returns false
o5 = 'Cat' || 'Dog'      // t || t returns "Cat"
o6 = false || 'Cat'      // f || t returns "Cat"
o7 = 'Cat' || false      // t || f returns "Cat"
o8 = ''    || false      // f || f returns false
o9 = false || ''         // f || f returns ""
o10 = false || varObject // f || object returns varObject

Note: If you use this operator to provide a default value to some variable, be aware that any falsy value will not be used. If you only need to filter out null or undefined, consider using the nullish coalescing operator
Answer: const [thing, setThing] = useState(thing || otherThing);
If either one of thing or otherThing evaluates to a truthful expression, then useState(true) is called and returns a tuple of 2 items.
If both thing and otherThing do not evaluate to a truthful expression, then useState(false) is called and returns a tuple of 2 items.
Some example of non-truthful expressions:

false
null
undefined
""
[]
{}
1+1==3


How to get bundle machine name when viewing the creation form?

Question: From the creation form (any bundle), I need to get the content type label/name to use it in a link (in a block, for example) and pre-filter the View opened by this link.
Example :
The user wants to add a new Article and opens the Article creation form.
In a special block (let's say in Highlighted region), a link is displayed : "Clone existing".
This link leads to a View listing the existing Articles with a clone button for each.
This View can be filtered by content type.
So the link would be something like :
Clone existing

How to get the [node:content-type] (just here to clarify, good old token) from the form?
Any tip would be nice.
Answer: Writing your own question is always useful.
I may have a solution, even if you may have something different, so please share.
I have built a Views block with a custom text (my link) as unique field (only show one result, you do not need to repeat the link, of course).
I have added a contextual filter based on content type with a default value provided by url, raw value, third component (node/add/mybundle_name), with case transform in lower case.
My link looks like :
Clone existing

And it works.


DNS Records (Nettica.com)

Question: If someone uses Nettica.com (to manage DNS records), is there any chance, how to find out hosting provider?
Example
http://who.is/dns/evernote.com/
evernote.com NS 1 day  dns5.nettica.com
evernote.com NS 1 day  dns1.nettica.com
evernote.com NS 1 day  dns2.nettica.com
evernote.com NS 1 day  dns3.nettica.com
evernote.com NS 1 day  dns4.nettica.com

Questions

Which hosting provider does Evernote use?
Why Evernote use Nettica.com? What's the advantage?

Thank you.
Answer: check to what ip does evernote.com point:
pqd:~$ dig +short evernote.com
188.8.131.52

[ or just http://www.robtex.com/dns/evernote.com.html ]
and 18.104.22.168 belongs to Quality Technology Services Santa Clara.
[ http://www.robtex.com/ip/126.96.36.199.html#whois ]
Answer: The DNS and webserver hosting can be totally independent. As is in this case.
Your best bet is:

Check the DNS records:
host evernote.com

should give you something like this:
evernote.com has address 220.127.116.11
evernote.com mail is handled by 30 aspmx5.googlemail.com.
[...]

We know that web hosting is done at 184.108.40.206, and e-mail gets handled by Google (Apps for Your Domain).
Try checking the obtained IP in RIPE database: Query RIPE Database
Here it's a nondescript IANA-BLK, so we don't know much.
In that case we can try a traceroute to the web host:
traceroute evernote.com
[...]
18  border3.pc1-bbnet1.sje.pnap.net (220.127.116.11)
19  qts-28.border3.sje.pnap.net (184.108.40.206)
20  126.96.36.199 (22.214.171.124)
21  www.evernote.com (184.108.40.206)

Looking at this we can make a guess that evernote is using www.internap.com
Correction: As pointed out - ARIN database is more accurate in this case:
http://ws.arin.net/whois/?queryinput=184.108.40.206
Comment: Now when I look at pQd answer - it's probably more precise. Internap could be an intermediary provider of some sort.

DNS Records (Nettica.com)


Repetir linhas de uma tabela usando JavaScript

Question: Minha dúvida é a seguinte: eu tenho esse código onde ele alimenta uma tabela com 3 campos (valor da parcela, data de inicio, data do fim). Das minha inúmeras tentativas que não tive sucesso eu estou tentando por um while para fazer o preenchimento automático da tabela.
Ex: se eu por um valor = 200,00 com data de inicio = 17/04/2019 data de fim = 17/06/2019.
ele já preencha pelo while as datas e valores correspondentes na tabela... Alguém pode me ajudar com essa dúvida, creio que seja algo bobo mas como ainda estou começando vale cada ajuda como aprendizado! Obrigado.
function GerarTabela() {
    var valor = $("#txtParcela").val();
    var data1 = $("#datepicker1").val();
    var data2 = $("#datepicker2").val();
    var linha = document.createElement("tr");
    var campo_data = document.createElement("td");
    var campo_valor = document.createElement("td");
    var tabela = document.querySelector(".myBody");
    var rs = "R$ ";
    var valor_completo = `${rs} ${valor}`;

    var data_parcela = document.createTextNode(data1);
    var data_parcela2 = document.createTextNode(data2);
    var valor_parcela = document.createTextNode(valor_completo);

    if (valor == null || valor == "") {
        alert("Inserir valor da Parcela.");
    } else if (data1 == null || data1 == "") {
        alert("Inserir data primeiro dia.");

    } else if (data2 == null || data2 == "") {
        alert("Inserir data ultimo dia.");

    } else {
        while (data_parcela < data_parcela2) {
            campo_data.appendChild(data_parcela);
            campo_valor.appendChild(valor_parcela);
            linha.appendChild(campo_data);
            linha.appendChild(campo_valor);
            tabela.appendChild(linha);
            //condição que faça incrementar os meses até o ultimo mês.
        }
    }
};

Comment: Essa função `.addMonth(1)` é de onde?
Comment: foi uma função que eu estava testando, mas não deu certo e esqueci de apagar essa linha.
Answer: Acho que você está fazendo uma mistura desnecessária de métodos JS e jQuery. Já que está usando jQuery, não precisa criar nós, basta inserir um template string com os valores usando .append().
Agora, para comparar as datas e ir incrementando os meses no laço while, use o objeto Date(), veja:

function GerarTabela() {
   var valor = $("#txtParcela").val();
   var data1 = $("#datepicker1").val();
   var data2 = $("#datepicker2").val();
   var tabela = $(".myBody");
   tabela.empty();
   var rs = "R$ ";
   var valor_completo = `${rs} ${valor}`;

   if (valor == null || valor == "") {
      alert("Inserir valor da Parcela.");
   } else if (data1 == null || data1 == "") {
      alert("Inserir data primeiro dia.");
   } else if (data2 == null || data2 == "") {
      alert("Inserir data ultimo dia.");
   } else {
      var d1_array = data1.split("/");
      var d2_array = data2.split("/");

      var data_ini = new Date(d1_array[0], d1_array[1]-1, d1_array[2]);
      var data_fim = new Date(d2_array[0], d2_array[1]-1, d2_array[2]);

      while (data_ini <= data_fim) {

         var dia = data_ini.getDate().toString();
         var mes = (data_ini.getMonth()+1).toString();

         var data = (dia.length == 1 ? "0"+dia : dia)
         + "/"
         + (mes.length == 1 ? "0"+mes : mes)
         + "/"
         + data_ini.getFullYear();

         tabela.append(`<tr><td>${data}</td><td>${valor_completo}</td></tr>`);
         data_ini.setMonth(data_ini.getMonth()+1);
      }
   }
}
.myBody td{
   border: 1px solid black;
}

Valor: <input type="text" id="txtParcela" value="200">

Data1: <input type="text" id="datepicker1" value="2019/04/17">

Data2: <input type="text" id="datepicker2" value="2019/06/17">

<button onClick="GerarTabela()">Gerar</button>

Só veja em que formato as datas são retornadas em:
var data1 = $("#datepicker1").val();
var data2 = $("#datepicker2").val();

No exemplo acima eu assumi o formato aaaa/mm/dd. Se for no formato dd/mm/aaaa terá que alterar a ordem nas linhas abaixo, colocando o índice [2] como primeiro argumento e o índice [0] no terceiro argumento do Date():
var data_ini = new Date(d1_array[0], d1_array[1], d1_array[2]);
var data_fim = new Date(d2_array[0], d2_array[1], d2_array[2]);

Para:
var data_ini = new Date(d1_array[2], d1_array[1], d1_array[0]);
var data_fim = new Date(d2_array[2], d2_array[1], d2_array[0]);

Comment: Incrível. Funcionou perfeitamente! Irei observar mais em relação a misturas de js e jQuery... Afinal a intenção do framework é facilitar o codigo js. Ainda estou estudando alguns livros e muita pesquisa na internet! Peço desculpas se cometi alguma gafe e fico muito agradecido pela ajuda e principalmente pelas dicas! Obrigado.
Comment: Estou vendo o problema. Não coloque como resposta o problema que ocorreu, blz.
Comment: O problema é que novembro só tem 30 dias, e vc colocou dia 31. O que fazer nesse caso?


Calling Static Methods with Data Contexts in LINQPad

Question: I am using LINQPad to develop a new data access method. In the method, which performs a LINQ-to-SQL query against a table in MySchemaContext, I am using a parameter for which I am loading a default value from the same DataContext object using a static method.
When I call this static function in LINQPad (using the "C# Program" setting) - one that works fine when called from with an application, and that is public - I get a null reference exception on the line that assigns the return value of the static function to a variable. If I change the logic of the function, it works if I do not reference MySchemaContext (for instance, if I assemble the List by hand and return that), but throws the exception if I do reference MySchemaContext.
My guess is that this has something to do with the way LINQPad is connecting to my database - that the DataContext is not valid when the library function is called from LINQPad, and that the null reference exception is being thrown by GetTable<MyClassTable> in the library. Is this a limitation of LINQPad, or is there something obvious I'm missing?
Here is a sample of the sort of function I'm having a problem with. The first part is the code in my library (which I am calling from the LINQPad query):
namespace MyLibrary
{
 public class MyClass : MyClassTable
 {
   //There are reasons not to just add stuff to the partial class MyClassTable
   //that aren't shown in this generic example

  public int MyClassTemplateID {get; set;}
  public int MyInt {get; set;}
  public string MyString {get; set;}

  public MyClass() {}
  public MyClass(int myClassTemplateID, int myInt, string myString)
  {
   MyClassTemplateID = myClassTemplateID;
   MyInt = myInt;
   MyString = myString;
  }
  public static List<MyClass> GetMyClassesTemplate(int myClassTemplateID)
  {
   //MySchemaContext is a LINQ-to-SQL DataContext object, i.e., inherits from System.Data.Linq.DataContext
   using (MySchemaContext myContext = new MySchemaContext())
   {
    return (from mct in myContext.GetTable<MyClassTable>().AsQueryable()
     where mct.MyClassTemplateID == myClassTemplateID
     select new MyClass
     {
      MyClassTemplateID = mct.MyClassTemplateID,
      MyInt = mct.MyInt,
      MyString = mct.MyString
     }).ToList<MyClass>();
   }
  }
 }
}

The library function works well in my application. This second part is in my LINQPad query, trying to call this same function:
/*
    Call from LINQPad
    MyLibrary.dll is in "Additional References," and MyLibrary is in "Additional Namespace Imports."
*/

void Main()
{
 List<MyClass> myClassList = MyClass.GetMyClassesTemplate(1);
 //get error "NullReferenceException: Object reference not set to an instance of an object.
 //However, this exact line of code works fine in VisualStudio.
 //Have correct connection string for MySchemaContext in LINQPad.exe.config and lprun.exe.config
}

Comment: Did you try putting the connection string in LINQPad.config (rather than LINQpad.exe.config) ?
Comment: Break the contents of that `using` block into a bunch of different lines of code, instead of trying to do the whole thing at once. Then, you might be able to narrow down the actual cause of the exception a bit more closely, instead of taking a guess at it. Also, perform a check on `myContext` to ensure it's not null. It could very well be. If this is using Entity Framework or something else, it's possible LINQPad isn't using the right connection string.
Comment: You may need to fully qualify the MyClass including the namespace. `List myClassList = MyLibrary.MyClass.GetMyClassesTemplate(1);`
Comment: Try putting the call to GetMyclassTemplate(1) in a try.. catch block and output the callstack. I suspect the issue is somewhere inside of your actual implementation that you didn't copy here for security reasons.
Comment: Another idea, you may need to inject the connection string because it can't be picked up from the config file when using LinqPad with `MySchemaContext myContext = new MySchemaContext())`.
Comment: Thanks, @Steve; alas, I have already tried that (edited to clarify). If I remove the line `MySchemaContext mySchemaContext = new MySchemaContext()` (whether with or without a using block) and anything depending upon `mySchemaContext`, it works fine. It just breaks if I try to use `MySchemaContext` in the called function.
Comment: Thanks, @JimWooley, tried that, didn't work!
Comment: By the way, for now I'm just adding static functions that hard code some test vectors, so there's no urgency; but I'd like to know what I'm doing wrong here (if I can manage to explain what I'm actually doing, that is ;-).
Comment: @sgmoore: There wasn't an existing LINQPad.config, so I'll try that.
Comment: @JimWooley: thanks. I'll try the try ... catch block in LINQPad; as I said, the code works just fine *in situ*. I think the config string issue is the problem.
Answer: I suspect your issue is the use of the separate namespace. I was able to access a static method in LINQPad using the following code. Nptice in particular the mismatch of the opening and closing brackets.
    void Main()
    {
        tName.test.DoIt(); // Fully qualify the static method name
    }

} // Close the generated context's class

namespace tName
{
    public class test
    {
    // Define other methods and classes here
        public static void DoIt()
        {
            Console.WriteLine("Done");
        }
    }
// } Don't close the namespace. Let LinqPad do it.

With LinqPad, you are essentially injecting the code you type into a generated context. As a result, you need to fake it out thinking that the context's class is closed before injecting the new namespace/class. If you didn't use the namespace, you would be able to create a new class, but that class would be a child of the hosting class, not directly under the namespace in question. I discussed this further in this blog post.
Comment: Sorry, better clarify: the namespace is in the code I'm calling from LINQPad, it's not in the LINQPad workspace at all. See edits above.
Comment: Never *quite* resolved this issue, but this answer got me closest to where I needed to go.


PostgreSQL 7.x archiving

Question: I'm trying to get PostgreSQL 7.4 setup to use PITR mode (as described here). It appears that the "archive_mode" option isn't recognised. Can anyone shed light on when this first appeared in PostgreSQL? I don't want to upgrade to a newer version unless I absolutely have to.
(For what it's worth, I was planning on using this to replicate PostgreSQL database updates across the wire to a warm standby database.)
Answer: PITR was introduced in 8.0, as seen in feature list:
http://www.postgresql.org/docs/8.4/static/release-8-0.html

Point-In-Time Recovery
<code>In previous releases there was no way to recover from disk drive failure
</code>
except to restore from a previous
  backup or use a standby replication
  server. Point-in-time recovery allows
  continuous backup of the server. You
  can recover either to the point of
  failure or to some transaction in the
  past.

PostgreSQL 7.x archiving