How can I order objects according to some attribute of the child in OData?

Question: I'm trying to do some custom sorting in OData using this URL
localhost:82/odata.svc/ComponentPresentations?$filter=TemplateId eq 2894 and publicationId eq 10&$expand=Component/Keywords?$orderby=Title desc

Where Componentis a property of ComponentPresentation and Keywords is property of Component, and I want to sort the ComponentPresentation according to the keyword's Title attribute. But keywords nor title is a property of Component Presentation
Is there a way to sort the results according to the attribute of Keword's title? Which is a Child of Component, which is a child of ComponentPresentation?
Comment: @VladL above... (sorry, I don't have the rep points to comment), I don't think that works either. I just tried it and added Quantity to the select statement for the Order_Details: http://services.odata.org/V4/Northwind/Northwind.svc/Orders?$select=OrderID&$expand=Order_Details($select=UnitPrice,Quantity;$orderby=Quantity) It does not appear that the Order_Details are being sorted by Quantity.
Answer: Just want to mention that it is possible since OData V4. You can nest as many expands/selects/orderby/filters as you wish. Now it is as simple as
http://services.odata.org/V4/Northwind/Northwind.svc/Orders?$select=OrderID&$expand=Order_Details($select=UnitPrice;$orderby=Quantity)
Comment: @inane v1, v2 and v3 - impossible
Comment: the syntax is correct, but the nested orderby doesn't seem to change anything in the result.
Comment: This syntax is correct but the problem is it doesn't sort the Orders it only sorts the order_details within each of the orders.
Comment: @sroll I've spent a lot of time with sample OData services from odata.org and noticed that you get different results at different times, if the service is not down at all ;) Try it with TripPin http://www.odata.org/odata-services/
Comment: If the syntax is correct, it's weird that it doesn't work then :s
Comment: As far I understand, it would not be possible with the version 2??
Comment: @inane not even in V3
Comment: But with the v2 is impossible?
Comment: @RonnBlack sure, because it is applied to order_details :)
Comment: @VladL  In my `$expand=az_Job($select=az_JobId,az_Code,az_Name;$orderby=az_Name desc)`, I have specify `desc` in `$orderby`, unfortunately it didn't work.  What did I miss?
Comment: Can I ask you where did you find that syntax rule? I mean the comma to separate more statement inside an `$expand`. Thank you.
Answer: It is possible to sort the results by a nested single-cardinality property, for example: http://services.odata.org/V3/Northwind/Northwind.svc/Orders?$top=50&$expand=Customer&$orderby=Customer/City
AFAIK, it's not possible to do this with a navigation property that has a cardinality of many (though it would be useful in expand scenarios to order what comes back in the expanded feed).
Answer: append order by with  expand object/field on the end of the query
localhost:82/odata.svc/ComponentPresentations?$filter=TemplateId eq 2894 and publicationId eq 10&$expand=Component/Keywords?$orderby=Component/Title desc


How to provide parameters to commands called by `system()`?

Question: I want to execute the following commands from a C program:
amixer --quiet set Master 5+
amixer --quiet set Master 6-

Here, 5 and 6 are not fixed values. They are Input Arguments of the code which can have different values.
Can anybody please guide me on how to achieve this?
Comment: What did you try and why didn't it work ?
Comment: Related: http://stackoverflow.com/q/6787318/577167
Answer: Did you try:
system("amixer --quiet set Master 5+");
system("amixer --quiet set Master 6-");

Comment: use a buffer, `sprintf` the command you want, then call `system` with this buffer.
Comment: I have already tried this solution. But can't modify the values 5/6 to others using this way.
Answer: The following code can achieve this:
#include <stdio.h>
#include <stdlib.h>     /* For system() */

#define SIZE 28

int main()
{
    char action;
    unsigned int level;

    char CommandString[SIZE];

    printf ("\nTo Increase\\Decrease volume press 'i'/'d': ");
    scanf  ("%c", &action);

    if (action!='i'&& action !='d')
    {
        printf ("\nInvalid Choice, please try again\n");
        main();
    }

    printf ("\nEnter Voice Change Level: ");
    scanf  ("%u", &level);

    if (action=='i')
    {
        printf ("\nIncreasing Voice level by: %u\n", level);
        sprintf (CommandString, "amixer --quiet set Master %d+", level);
    }
    else
    {
        printf ("\nDecreasing Voice level by: %u\n", level);
        sprintf (CommandString, "amixer --quiet set Master %d-", level);
    }

    system (CommandString);

    return 0;
}


Range implications of C extension on double bass

Question: I know the C-extension allows playing C1 on a double bass, but it's not entirely clear to me what the implications are of using it:
AFAICT if none of the mechanical fingers are used you can play C1 by bowing the open string, but it's impossible to play a C#, D, D#? (Based on this picture)
Since you can't reach for those notes due to the mechanical fingers being in the way?
Answer: Look at this video, particularly from 1'35"
You finger from the left (player's view).   The 'clips' are on the right.  They don't obstruct fingering.
Comment: Haha, ah yes of course. Silly me :)
Answer: Also, you set the bottom note required in the piece you are playing by clipping that note off.  Sometimes you might have time to clip off a note during a passage and then unclipping it again, depending on what the music requires.  You have to initially read through the music to find out what clips you need to where and write instructions in the relevant places (a bit like a harp player with their pedalling instructions).


How do I multiply SQL rows

Question: I have this table:
TableA
ID       Value
1        "10,20"
2        "101,102,103"
3        "50,60"
4        "100,200,300"
5        "81,82,83,84"

I want this:
TableB
ID       Value
1        10
1        20
2        101
2        102
2        103
3        50
3        60
4        100
4        200
4        300
5        81
5        82
5        83
5        84

I'm using SQL Server V18, so I have access to the built-in STRING_SPLIT() function, if needed.
Answer: Am I missing something?  You seem to know to use string_split() and there isn't any other complication as far as I can see:
select t.id, s.value
from t cross apply
     string_split(value, ',') s;

You can use insert or into to put the data in another table.
If the double quotes are actually part of the value, you can get rid of them:
string_split(replace(value, '"', ''), ',')

Comment: @Joe . . . `string_split()` returns a table with one column called `value`.  The `s` is assigned as the table alias for that result.  Hence, `s.value` is the element returned by `string_split()`.
Comment: No, the double quotes are not part of the data, I just wanted to point out that the data was string/nvarchar type.
Comment: Thanks, this works, but where does the term "s.value" dome from?  It seems to have nothing to do with my column names. If I change my column names from "value" to "widget", I still need to select "s.value".
Comment: Thanks for the clarification.

How do I multiply SQL rows


taking average of several models and feature sets

Question: just a quick question that i cant seem to find a definitive answer for. When im doing feature selection, i end up with a list of the top performing sets.  Would it make sense to use the top 10 sets instead of just the top one, and then average the results when making predictions?  Im assuming using 10 different models and averaging them would increase performance.
Answer: You can expect an improvement if all of your models perform better than random chance and if the models are sufficiently un-correlated. Winning entries in data mining competitions such as Kaggle are very often ensembles of models similar to your description. See for example this interview http://blog.kaggle.com/2016/03/23/telstra-network-disruption-winners-interview-1st-place-mario-filho/
with the winner of a recent Kaggle competition where the winning solution was an ensemble of 15 models.
It's not a completely one way street though - if you were models were easily interpretable beforehand, your averaged model will be less interpretable, and if you intend to implement your model, using the average of ten models instead of just one model adds to the computational requirements (whether or not this an issue will obviously depend heavily on your application).


Chosing the right setup for stochastic process

Question: Consider a stochastic process $Y_k:=x+k-(X_1+\dots +X_k)$ for $k=1,2,...$, where $x \in \mathbb{N} $ and $X_1$ are i.i.d. random variables which are integer valued and non negative.
The process starts at $Y_0=x$.
$P_x$ is the measure under the condition that $Y_0:=x$
Let $(\Omega, \mathbb{F},\mathcal{F}, P_x)$ a filtered probability space where $\mathbb{F}:= \{ \mathcal{F_k}: k \in \mathbb{N}\}$,  is the natural filtration generated by $X_k$, i.e. $\mathcal{F_k}= \sigma(X_s \mid s \leq k)$
Is $R_0 $ measurable, although my sigma-Algebra starts at $k=1$?
Since my process starts at $k=1$, I know  $R_0$ by computing $P_x(Y_k=s)$ for any $k=1,2,...$
Is this sufficient?
Comment: All you need is for your $X_{i}$'s to be measurable functions from $\Omega$ into the reals (integers here). Such functions do exist, as a probability space is a measurable space.
Comment: I believe the $X_{i}$'s are $\mathcal{F}_{i}$-measurable, yes. Since you can write $X_{2} = Y_{2} - x - k - X_{1}$, and $X_{1}$ is $\mathcal{F}_{1}$-measurable. You can then do this for any $k$.
Comment: I am honestly not sure about your intuition, since the parts of the sum are not uniquely determined from the value of the sum. Mathematically speaking, you have that $X_{1} = Y_{1} - x - k$, which is obviously measurable wrt. $\mathcal{F}_{1}$, as $x$ and $k$ are constants. Seeing as $\mathbb{N}$ is countable, I think you could even get away with choosing the powerset of $\mathbb{N}$ as your sigma-algebra. As far as I'm concerned, we don't generally bother too much with the sigma-algebras on discrete spaces, as all subsets of these are measurable.
Comment: Regarding your intuition: you know $Y_{1}$, $k$ and $x$, so you just isolate to obtain $X_{1}$. You then get that for general $Y_{k}$ you know $Y_{k}$, $S_{k-1}$, $k$ and $x$, and therefore you must also know $X_{k}$.
Comment: Yes. I am quite confident (without having checked, but should not be hard), that the filtrations are the same, whether you generate with $X$ or $Y$.
Comment: Yes. That would be correct.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/116570/discussion-between-user7924249-and-sarah).
Comment: Are the $X_i$ measurable in $\mathbb{F}$
Comment: So you mean $X_1^{-1}(B)  \in \mathbb{F}$, where B is measurable,
Comment: What do I choose for the $\sigma$ algebra in $\mathbb{N}$ referring to $X_i : \Omega \rightarrow \mathbb{N}$
Comment: @user7924249: Sorry for my late answer.  Why should $X_1$ be measurable? Maybe I can give my intuiton on that: I know $Y_n$, so I have to know $S_n$ and therefore I have to know $X_i$ for $i\leq n$
Comment: What $\sigma-$ algebra would I choose  in $\mathbb{N}$?
Comment: Ok perfect. Is it maybe better that the filtration is generated by $X_k$?
Comment: Then $x+k -(X_1+...+X_k)$ is measurable. and therefore $Y_k$?
Comment: So I have my filtered probabiliity space where the filtrations are generated by $X_k$. The $X_k$ map von $\Omega$ into $\mathbb{N}$ with the powerset of $\mathbb{N}$ to make it a measurable space.
Comment: By construction of $\mathbb{F}$ X_i are measurable.
Comment: The last thing I am not sure. The sum of random variables is computed using convolution. Therefore $X_1+..+X_k$ is measurable in the product sigma algebra in general. Would this make a problem here? Maybe I mix something up
Comment: @user7924249: If I consider the $X_1+...+X_N$, where N is an stochastic process. In that case Y shouldgenerate my filtration, isn't it
Comment: Sorry for the additional question.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/116689/discussion-between-sarah-and-user7924249).
Answer: It depends on what you are attempting to model.
For example, I've come across some stochastic processes where the paths have to be cadlag and the process predictable with regards to its underlying filtered sigma algebra.
edit
@Sarah; It sounds like your comments are along the right lines. I can't be more specific since its been about a decade since I've looked at this kind of material. I'd add though, that often the measure space is usually the Borel algebra of the space in question; that is one takes the minimal Borel algebra generated by the opens of the underlying topological space of the process in question.


Question About Notation In Field Theory $F(x)$ vs. $F[x]$

Question: I have a question about notation specifically square brackets $[$ and round brackets $($.
My textbook doesn't explain any of this and I cannot find a reliable source online to confirm the difference.
So my question is: What is the difference between round brackets and square brackets in terms of notation in Field Theory? For example, I see $F(x)$ and $F[x]$ in my textbook and I've always assumed they were the same thing. But apparently they're not. Is there ever a time they're the same?
I wanted to know the difference, it may be a silly question but it's something I want to make sure I understand.
Answer: Consider $x$ as an element contained in some extension of $F$; then  $F(x)$ is the smallest field that contains both $F$ and $x$. On the contrary $F[x]$ is the smallest ring that contains both $F$ and $x$. Clearly $F[x]\subseteq F(x)$, and in some cases they are equal. You can prove easily (or see it on Morandi's book) that
$$F[x]=\{f(x):\textrm{$f$ is a polynomial with coefficients in $F$}\}$$
$$F(x)=\left\{\frac{f(x)}{g(x)}:\textrm{$f,g$ are polynomials with coefficients in $F$ and $g(x)\neq0$}\right\}$$
Comment: Yes, $\mathbb{Q}[i] = \mathbb{Q}(i)$, @Mark. There's a difference between $R(\alpha)$ and $R[\alpha]$ generally when $R$ is a ring but not a field. For a field $K$, you have $K[\alpha] \neq K(\alpha)$ if and only if $\alpha$ is transcendental over $K$.
Comment: Ah, so to denote the difference. Fields uses square brackets and rings uses round brackets? So in that case, would that mean $\mathbb{Q}(i)$ is the same as $\mathbb{Q}[i]$?
Comment: @DanielFischer So let's say you have a ring R. What's the difference between $R[\alpha]$ and $R(\alpha)$? Is there even a point to consider $R[\alpha]$ since it's not a field? One more question as well, so let's say $K$ is a field and $\alpha$ algebraic. Would that mean $K[\alpha] = K(\alpha)$?. Thanks again!
Comment: @Mark We're often interested in rings that aren't fields, $\mathbb{Z}[i]$ or $\mathbb{Z}[e^{2\pi i/3}]$ for example are quite useful rings, as are polynomial rings. For a field $K$ and algebraic $\alpha$, we always have $K[\alpha] = K(\alpha)$. That's because $K[\alpha]$ is then a finite-dimensional $K$-vector space, and has no zero divisors. Therefore multiplication by any nonzero element $\beta$ is an injective $K$-linear map, hence surjective, and that means $\beta$ has a multiplicative inverse.
Comment: @DanielFischer Woops. I meant to say $R(\alpha)$! Sorry about that. Anyways, your explanation pretty much sums up what I wanted. Thank you once again. :)
Answer: $F[x]$ denotes the ring of (formal!) polynomials over $F$ in the indeterminate $x.$
$F(x)$ denotes its fraction field - the so-called rational "functions" in $x.$
The same notation is used for adjunctions of elements to rings and fields, i.e. if $\,\alpha\,$ is an element of some extension ring $\,E\,$ then $\,F[\alpha]\,$ denotes the smallest subring $\,R\,$ of $\,E\,$ that contains $\,F\,$ and $\,\alpha.\,$ Equivalently, it is the image of $\,F[x]\,$ under the evaluation map $\,x\mapsto \alpha,\,$ i.e. the set of all elements expressible as polynomials in $\,\alpha\,$ with coefficients in $\,F.\,$  If $\,\alpha\,$ is transcendental (= not algebraic) over $\,F,\,$ i.e. $\,\alpha\,$is not a root of any nonzero polynomial $\,f\in F[x],\,$ then there is a ring isomorphism $\,F[\alpha]\cong F[x].\,$ Thus the polynomial ring $\,F[x]\,$ can be viewed as the ring obtained by adjoining to $\,F\,$ any element that is transcendental over $\,F,\,$ e.g. $\,\Bbb Q[x]\cong \Bbb Q[\pi].\,$ Similarly for the case of fields.


Replace subquery with join for the same table

Question: Can the expected result in this case be accomplished without a subquery ? Maybe using a join ?
We have a name say 'jose', Expected result is all rows which has same color as jose. Query should run in both MS-SQL and ORACLE.
query
======
select name,color from tableA where color=(select color from tableA where name='jose')

Expected result
===============
name    color
jose    red
Rap     red

schema
=======

Table and DATA
create table tableA (
name varchar(10),
color varchar(10)
);

insert into tableA values ('jose','red');
insert into tableA values ('Mickey','blue');
insert into tableA values ('Leo','yellow');
insert into tableA values ('Rap','red');
insert into tableA values ('Don','blue');

http://sqlfiddle.com/#!18/5f7e3/2
Answer: You can get this result with a JOIN, by self-joining on the color field, where the name in the second table is jose:
SELECT a1.name, a1.color
FROM tableA a1
JOIN tableA a2 ON a2.color = a1.color AND a2.name = 'jose'

Output
name    color
jose    red
Rap     red

SQL Server demo on SQLFIddle
Oracle demo on SQLFiddle
Answer: If names have only one color, then you would seem to want:
select a.*
from tableA a
where a.color = (select a2.color from tableA a2 where a2.name = 'jose');

You might want to add another condition that a.name <> 'jose' if you don't want to return that row.
Comment: This query uses subquery just like the one in question. I am trying to find out if we can do this without subquery .
Answer: I think the best way is "CTE" :
     with
     cte1 as (
          select 1 as RowToJoin,
                 name,
                 color
          from tableA
     ),
     cte2 as (
          select 1 as RowToJoin,
                 color
                 name
          from tableA
          where name='jose'
     )
     select c1.name, c1.color
     from cte1 c1
     join cte2 c2 on c2.RowToJoin = c1.RowToJoin
     where c1.name <> c2.name

It looks as something hard, but it's simple. Try to read about it.!


If else condition in LINQ to XML query in c#

Question: this is xml let say:

<.Sections>
<.SECTION ID ="4" NAME="GetStudents" CONTROL-TYPE="Button" LINK="WebForm2.aspx">

      <.SECTION ID="5" NAME="SelectStudent" CONTROL-TYPE="Drowpdown" METHOD ="selectList_MethodName">

Observe this xml, I am generating the UI controls base on "CONTROL-TYPE" Attributes. but there are different attributes are there in both sections elements. as LINK and METHOD . I want to query like this , if section's CONTROL-TYPE=="Button" then get value of LINK attribute Else If CONTROL-TYPE=="Drowpdown" then get value of METHOD attribute Else If.
I am trying to write code in c# +ASP.net. how to achieve this? is there way get such data ?
NOTE: please don't go on dot inside tag as <.SECTION>. it is for this forum page understanding.
Answer: Well, the simplest way is either an explicit if/else:
string value;
string controlType = (string) element.Attribute("CONTROL-TYPE");
if (controlType == "Button")
{
    value = (string) element.Attribute("LINK");
}
else if (controlType == "Dropdown")
{
    value = (string) element.Attribute("METHOD");
}
else
{
    // What do you want to happen if it's neither of these?
}

... or use the conditional operator if you're happy with a simple default value for other control types:
string controlType = (string) element.Attribute("CONTROL-TYPE");
string value = controlType == "Button" ? (string) element.Attribute("LINK")
             : controlType == "Dropdown" ? (string) element.Attribute("METHOD")
             : "default value";

EDIT: Within a query expression, there are two reasonable ways to do this. First, you could use the conditional operator and a let clause to fetch the control type just once:
var query =
     from element in elements
     let controlType = (string) element.Attribute("CONTROL-TYPE")
     select new {
         ID = (string) element.Attribute("ID"),
         XYZ = controlType == "Button" ? (string) element.Attribute("LINK")
             : controlType == "Dropdown" ? (string) element.Attribute("METHOD")
            : "default value"
     };

Alternatively - and preferrably, IMO - put this logic into a method, and then call the method from the select clause:
var query =
     from element in elements
     let controlType = (string) element.Attribute("CONTROL-TYPE")
     select new {
         ID = (string) element.Attribute("ID"),
         XYZ = GetXyz(element);
     };

...
private static void GetXyz(XElement element)
{
    ...
}

Comment: wo..wo.. is this i have to write in Select of Linq ? I think it is not support to declaration variables like string u did here ... please tell me where should i have to write this logic ?
let say I ave select as :

//code started here...
from mimic in....something..
select new
{
 ID = mimic.Attribute("ID"),
NAME = mimic.Attribute("NAME"),
CONTROLTYPE = mimic.Attribute("CONTROL-TYPE"),
 //I want to wrte here logic..... for Value as per your code
Comment: @Lalit: It would have helped if you'd given the context beforehand... will edit.


Is window.frameElement (for same-origin iframes) supported across all browsers?

Question: I have googled as much as I can and I'm not sure of the support for the document of an iframe getting the id of itself in the parent window: window.frameElement.id. There are so many browsers that it's hard to test them all and nothing online seems to have any information. I'm specifically wondering about:
Safari
iOS Safari
Windows Phone IE
IE 7, 8, 9, 10, 11
(I tested Firefox and Chrome and they both worked).
EXAMPLE IFRAME CONTENT
<!DOCTYPE HTML>

Answer: I happened to look for the same information.
Here's what I have found.
https://developer.mozilla.org/en-US/docs/Web/API/Window.frameElement
I have tested some browsers in addition to the MDN doc, and confirmed that it is supported by IE7+, Safari, Firefox, Chrome. So pretty much all browsers.
I haven't tested on IE6-, but I guess you don't need to care.
Answer: var frame = window.frameElement;  //Get  element of the window
if (frame) { window.location.href = "/403.shtml"; ...

This code not working for me in cross browser (FF,Chrome,IE)
A prefer this one, working ok and cross browser...
  if (window.self === window.top) window.location.href = "/403.shtml";
//or if (window.self !== window.top) window.location.href = "/403.shtml";


Qual a melhor forma de converter um int array em String no Java?

Question: Qual o melhor método de se converter {1, 2, 3, 4, 5} pra "12345" ? Exemplo:
int[] array = {1, 2, 3, 4, 5};
array.toString(); // Existe alguma função que faça isso?

Eu sei que dá pra fazer com um for loop mas talvez tenha opções melhores.
int[] array = {1, 2, 3, 4, 5};
String s = ""; // Sei que tem StringBuilder também
for (int i : array) {
    s += i;
}

Comment: @LuizAugusto Se não me engano, `Arrays.toString` coloca vírgula entre os elementos, mas a pergunta pede para juntar os números, sem nenhum separador
Comment: E a [resposta abaixo](https://pt.stackoverflow.com/a/444159/112052) é uma opção válida, mas não sei se é "o melhor jeito" (partindo do pressuposto que performance é um critério pra considerar "melhor", então não é, pois [streams são mais lentas que um loop simples](https://pt.stackoverflow.com/q/361945/112052)). Mas quem gosta de uma "pegada mais funcional", com certeza achará melhor :-)
Comment: Em um loop, `StringBuilder` é melhor que concatenar strings com `+`: https://pt.stackoverflow.com/q/71517/112052
Comment: @hkotsubo sim sim, fiz um teste aqui e verifiquei isto, que não iria servir para tal propósito.
Comment: Já tentou `Arrays.toString(array)` do `java.util.Arrays` ?
Answer: Eis um código que pode te ajudar:
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        String resposta = IntStream.of(array).mapToObj(String::valueOf).reduce("", String::concat);
        System.out.println(resposta);
    }
}

Veja aqui funcionando no Ideone.
A ideia dele é primeiro converter o array em um IntStream e depois em um Stream de Strings, usando o String.valueOf(int) para converter int em String. Por fim, o reduce concatena todas as Strings resultantes (usando o método concat em uma só.
Apesar de que para ser sincero, provavelmente a solução usando um for e um StringBuilder será a que tem o melhor desempenho.
Comment: @inosivel [Código menor não é necessariamente melhor](https://pt.stackoverflow.com/a/400495/112052), e usar `replace` é gambiarra (pode até "funcionar" pra esse caso específico, mas e se for um array de string e uma delas tiver um `[` no meio do texto, ele será indevidamente removido, entre outros casos que pode dar problema, como arrays de arrays, por exemplo). Usar streams ou um loop simples é melhor porque vc terá controle total do formato e não depende de detalhes de implementação de `toString` - veja mais em https://pt.stackoverflow.com/q/212754/112052
Comment: Testei teu código em um array de 100 mil unidades e ele foi mais de 100x mais lento que usando um StringBuilder
Pensei em uma forma interessante de fazer o que eu quero, o comentário do Luiz me fez ter essa ideia: `Arrays.toString(array).replaceAll("([\\[\\], ])", "");`
É umas 5x mais rápido que o seu e tem um código menor (mas continua sendo bem mais lento que com StringBuilder então vou continuar usando ele) mas achei interessante esse método pra pequenos arrays, anyway valeu pelo conhecimento amigo
Comment: @hkotsubo Eu sei, vou continuar usando o `StringBuilder` por ser mais legível e rápido, só achei a solução criativa mesmo
Answer: Acho que a melhor forma tanto em legibilidade quanto eficiência é usar StringBuilder mesmo, valeu pela ajuda aí gente.
int[] array = {1, 2, 3, 4, 5};
StringBuilder sb = new StringBuilder();
for (int i : array) sb.append(i);

Answer: Se você estiver usando Java 8, pode usar stream:
    String str = Arrays.stream(intArray).mapToObj(String::valueOf)
        .reduce((a, b) -> a.concat(b)).get();

Se precisar algum char pra concatenar vc pode usar o concat
    a.concat(",").concat(b)

Answer: Só para complementar as outras respostas, a partir do Java 8 é possível usar String.join. Mas como este método deve receber uma ou mais instâncias de CharSequence e int's não são CharSequence's, ainda temos que converter o array de int para um array de String:
int[] array = { 1, 2, 3, 4, 5 };
String s = String.join("", IntStream.of(array).mapToObj(String::valueOf).toArray(String[]::new));
System.out.println(s); // 12345

Se bem que neste caso, eu ainda prefiro a solução que usa um loop e um StringBuilder, que é melhor que a concatenação com + (e ambas, por sua vez, são mais rápidas que streams).

Outra opção (que só funciona se os valores do array são todos números entre 0 e 9) é construir um número com os dígitos do array e no final convertê-lo para String:
int[] array = { 1, 2, 3, 4, 5 };
int n = 0;
for (int i : array) {
    n *= 10;
    n += i;
}
String result = String.format("%0" + array.length + "d", n); // 12345

Usei String.format para colocar os zeros à esquerda, caso os primeiros elementos do array sejam 0 (pois se eu só imprimir o número diretamente, ele é mostrado sem os zeros à esquerda). Eu também uso o tamanho do array (array.length) para que a quantidade de dígitos mostrada seja a mesma quantidade que tem no array (assim, um array como {0, 0, 0, 1} resulta na string 0001).


Is the following inequality correct?

Question: I'm trying to understand whether the following inequality is correct. Let $Y,X$ be random variables and $f(X)$, $n\times 1$-dimensional function of $X$. It is claimed that
$$\begin{aligned}
& a'(A'B^{-1}A)^{-1}A'B^{-1}\mathbb{E}[Yf(X)f(X)']B^{-1}A(A'B^{-1}A)^{-1}a \\
& \geq \inf_x\mathbb{E}[Y|X=x]\|a'(A'B^{-1}A)^{-1}A'B^{-1/2}\|,
\end{aligned}
$$
where $A,B$ are matrices and $a$ is a vector of compatible dimensions (deterministic), $\mathbb{E}[f(X)f(X)']=B$ is positive definite and $A$ is full-column rank.
How to see that this inequality is correct?
Comment: There is some easy cancellation to begin with...
Comment: Are they still there, after the correction of typo?
Answer: Let $$g(x)=\mathbb{E}(Y|X=x)\\
c=\inf_x g(x)\\
h^2(x)=g(x)-c$$
Then, from the right-hand side,
$$||a'(A'B^{-1}A)^{-1}A'B^{-1/2}||=
a'(A'B^{-1}A)^{-1}A'B^{-1}A'(A'B^{-1}A)^{-1}a\\
=a'(A'B^{-1}A)^{-1}A'B^{-1}BB^{-1}A'(A'B^{-1}A)^{-1}a\\
=a'(A'B^{-1}A)^{-1}A'B^{-1}\mathbb{E}(f(X)f'(X))B^{-1}A'(A'B^{-1}A)^{-1}a$$
So the difference between the two sides is
$$a'(A'B^{-1}A)^{-1}A'B^{-1}\mathbb{E}(f(X)h(X)h(X)f'(X))B^{-1}A'(A'B^{-1}A)^{-1}a\\
=\mathbb{E}(||a'(A'B^{-1}A^{-1}A'B^{-1}f(X)h(X)||)\geq0$$

Is the following inequality correct?


Which regression model should I use (in R)?

Question: I am trying to run a regression in R. My variables are as follows:

member_id: the id number for each MP
year: the year (this runs from 1997-2010)
isFemale: 1 for male, 2 for female
party: what party they are in
Leadership: TRUE if they hold a ministerial position in government or opposition, FALSE if not
days_in_house: how many days they have been an MP
n_Edu: number of interjections made about education per member in the given year

I want to use debate participation in education (n_Edu) as my dependent variable, and the independent variables are isFemale, party, Leadership, days_in_house. I want to run this for each year.
    member_id year isFemale                     party Leadership days_in_house n_Edu
 1:       386 1997        1              Conservative      FALSE          6579     0
 2:        37 1997        1                    Labour      FALSE          6579     0
 3:        47 1997        1                    Labour       TRUE          5081     0
 4:       408 1997        1              Conservative       TRUE          6579     4
 5:        15 1997        1          Liberal Democrat      FALSE          5081     0
 6:       191 1997        2   Scottish National Party      FALSE          3618    45
 7:       605 1997        1     Ulster Unionist Party      FALSE          2547     0
 8:       471 1997        1 Democratic Unionist Party      FALSE          6579     0
 9:       111 1997        1              Conservative      FALSE          5088    53
10:       187 1997        1              Conservative      FALSE          6586     0

I am not sure what type of regression I should be running, especially as I want to run it for each year from 1997-2010.
Comment: I would recommend you start by formulating the question of interest. A few key considerations: are you trying to predict your dependent variable using the set of independent variables or are you interested in the causal effect of one of your independent variables? Are you asking "How much...?" or  "Whether?" which would speak to whether any of your variables need to be transformed. Finally, is there a reason you're looking to run a set of cross-sectional regressions or would you benefit from exploiting the time dimension of the panel dataset and want to run one single regression?
Comment: I am looking at the causal effect of gender (isFemale) on the participation rate in the debate per member per year and want to see what affect the other independent variables also have on their participation (if any). I want to be able to see any changes that occur over the time period (1997 - 2010), so I am not sure if this requires me to run cross-sectional regressions or if I can run a single regression?
Answer: It depends on your data structure, but you're in poisson regression world. Here's a link that may help narrow down whether you should use a poisson, negative binomial, or even a zero-inflated model https://stats.idre.ucla.edu/stata/seminars/regression-models-with-count-data/. The basic difference between them are as follows:

Poisson - Used on count data, but assumes the variance equals the mean
Negative binomial - also used on count data, but is less restrictive with respect to the mean & variance
zero-inflated - when your data has a large amount of zero counts (I believe you can do zero-inflated poisson or neg-binom).

With respect to how to code it in r: for poisson you can use the glm function and specify family = poisson; for negative binomial, use the glm.nb function in the MASS package; and for zero-inflated, use the zeroinfl function in pscl package.


Why we use log function for cross entropy?

Question: I'm learning about a binary classifier.
It uses the cross-entropy function as its loss function.
$y_i \log p_i + (1-y_i) \log(1-p_i)$
But why does it use the log function?
How about just use linear form as follows?
$y_ip_i + (1-y_i)(1-p_i)$
Is there any advantage to use log function?
And an other question:
Log function maps (0,1) to (-inf, 0).
So I think it can crush the algorithm if we get 0 for $p_i$ or $1-p_i$ because log value would be -inf and back-prop will be exploded.
Answer: For binary classification one way to encode the probability of an output is $p^y(1-p)^{1-y}$, if y is encoded as 0 or 1. This is the likelihood function and it's meaning is with probability p we output 0 and with probability 1-p if output is 1.
Now you have a sample and you want to find p which best fits your data. One way is to find the maximum likelihood estimator. If your observations are independent your mle is found by maximizing the likelihood over the whole sample. This is the product of individual likelihoods $\pi_{i=1}^n p^{y_i}(1-p)^{y_i-1}$. But this is hard to use. Because of that one transform likelihood with logs. The transformation is monotonous and you get rid of products and obtain sums which are more tractable. Apply logs and get your expression.
Why not use your encoding instead? I think there is no reason why not. The question is which are the properties of your estimator? The first formulation uses likelihood and mle which has some theory behind which includes the fact that your estimator is efficient. The second formulation is not used often, don't know any example of encoding the probability like that which does not exclude your approach.
Answer: I was also looking for an explanation and found one reason I find intuitive here:

It heavily penalizes predications that are confident and wrong.

Check this graph, it shows the range of possible log loss values given a true observation:

The Log Loss increases rapidly as the predicted probability approaches 0(wrong prediction).


Proving the distance between a point and a line formula using vectors

Question: In coordinate geometry, I've often used the following result to obtain the perpendicular distance from a point to a line.

The perpendicular distance of the line $\ell:ax+by+c=0$ from the point $(h,k)$ is given by
  $$\left|\frac{ah+bk+c}{\sqrt{a^2+b^2}}\right|$$

Now I have never seen a proof of this result, but using vectors, I've also solved this same problem for specific situations, so I attempted to prove the result using the following generalised method:

Convert the equation $\ell:ax+by+c=0$ to vector form; which I did, giving
$$\boldsymbol{\mathrm r}(\lambda)=\lambda\,(b\,\boldsymbol{\mathrm i}-a\,\boldsymbol{\mathrm j})-\frac{c}{a}\,\boldsymbol{\mathrm i}$$
substituting $\boldsymbol{\mathrm r}={x\choose y}$ and simplifying easily verifies this to be correct.
Now suppose the position vector of $(h,k)$ is $\boldsymbol{\mathrm p}$, and let $\boldsymbol{\mathrm s}$ be the vector from the point $(h,k)$ to the line $\ell$. Clearly we have $$\boldsymbol{\mathrm s}=\boldsymbol{\mathrm r}(\lambda)-\boldsymbol{\mathrm p}$$
and using this, we obtain a vector-valued function $\boldsymbol{\mathrm s}(\lambda)=\left(\lambda b-\frac{c}{a}-h\right)\boldsymbol{\mathrm i}-(\lambda a+k)\boldsymbol{\mathrm j}$ which for different values of $\lambda$ traces the line $\ell$, starting from the point $(h,k)$.
Now to obtain the perpendicular distance from $(h,k)$, to $\ell$, we want the direction of $\ell$ to be parallel to $\boldsymbol{\mathrm s}(\lambda)$. Thus we solve $$\boldsymbol{\mathrm s}(\lambda)\cdot(b\,\boldsymbol{\mathrm i}-a\,\boldsymbol{\mathrm j})=0$$ for $\lambda$. Say the solution is $\lambda=\lambda_1$. Then the distance is therefore given by $\|\boldsymbol{\mathrm s}(\lambda_1)\|$.

At step 3, I started running into complicated algebra, where I obtained $$\lambda = \frac{cb+hab-a^3-a^2h}{ab^2}$$ and attempts to evaluate $\|\boldsymbol{\mathrm s}(\lambda_1)\|$ seemed to be getting me nowhere.
But I've used this method countless times to find the distance between a point and a line, why is it not working in the general case? I'd appreciate any feedback.
Answer: Consider vector normal to your target line
$(a,b)$ is the normal vector.
Now find a point on your line.  $(p,q)$
the vector from $(h,k)$ to $(p,q)$  = $(p-h,q-k)$
The distance we seek is$\|(p-h,q-k)\|\cos\theta$ where $\theta$ is the angle between $(p-h,q-k)$ and $(p-h,q-k)$
Note that: $|\mathbf u\cdot \mathbf v | = \|\mathbf u|\|\mathbf v\|\cos\theta$
So our formula is:
$\frac {|(a,b)\cdot(p-h,q-h)|}{\|(a,b)\|} = \frac{|(a,b)\cdot(p,q)-(a,b)\cdot(h,k)|}{\|(a,b)\|} = \frac{|c-(a,b)\cdot(h,k)|}{\|(a,b)\|}$
I am not following step 3. above, but it looks like this is the direction you are going.
$r(\lambda) = (-b,a)\lambda + (\frac ca,0)$
is the our line in vector form.
$s(\mu) = (a,b)\mu + (h,k)$
is the line perpendicular to $r(t)$ through $(h,k)$
Find $\lambda, \mu$ for the point of intersection.
The distance between the two lines will be $|\mu|\|(a,b)\|$
$a\mu + h  = -b\lambda+ \frac ca\\
b\mu + k = a\lambda $
$a\mu + b\lambda = - h+\frac ca\\
b\mu  - a\lambda =  -k $
$a^2\mu + ab\lambda = - ha + c\\
b^2\mu  - ab\lambda =  -kb $
$(a^2+b^2)\mu = -ha -kb + c$
$d= \sqrt{a^2+b^2}|\mu| = \frac {|-ha -kb + c|}{\sqrt{a^2+b^2}}$
Comment: Thanks for the reply - I've seen this proof online in fact. But could you point out why my approach goes wrong?
Comment: I don't understand your step 3.  However, I have done an alternate derivation that seems to be coming from the direction you were going.


Follow up question to question involving $\lim_{n\to \infty}\frac{\int_0^1 \left(x^2-x-2\right)^n \, dx}{\int_0^1 \left(4 x^2-2 x-2\right)^n \, dx}$

Question: I tried to answer Q 4482921 by elementary calculus but got stuck :

The first step in my solution is to replace $x$ by $2u$ so that $dx=2du$. The integral becomes $$\lim_{n\to \infty}\frac{\int_0^1 \left(x^2-x-2\right)^n \, dx}{\int_0^1 \left(4 x^2-2 x-2\right)^n \, dx}= \lim_{n\to \infty}\frac{\int_0^\frac{1}{2}\left(4u^2-2u-2\right)^n \ 2du}{\int_0^1 \left(4 x^2-2 x-2\right)^n \, dx}$$$$=2\left(1-\lim_{n\to \infty}\frac{\int_
\frac{1}{2}^1 \left(4x^2-2x-2\right)^n \, dx}{\int_0^1 \left(4 x^2-2 x-2\right)^n \,
dx}\right)$$

Now I need to prove that $\displaystyle\lim_{n\to \infty}\frac{\int_
\frac{1}{2}^1 \left(4x^2-2x-2\right)^n \, dx}{\int_0^1 \left(4 x^2-2 x-2\right)^n\, dx} =0.$ It certainly looks like it in the graph, and I also found that $$\int_{\frac 12}^1 \left(4 x^2-2 x-2\right)^n\, dx= \int_{-1}^{0} \left(4 x^2-2 x-2\right)^n\, dx.$$
Comment: I find it cute that you linked it by the MSE number index
Comment: As $n \to \infty$, the integral is dominated by the maximum that $4x^2-2x-2$ achieves in absolute value on the interval of integration.
Answer: $f(x)=x^2-x-2$ has a minimum at $x=1/2,$ decreases for $x<1/2$ and increases for $x>1/2.$
In particular, $f(x)<0$ on $(0,2).$
So for $1<2x<2,$ $0=f(2)>f(2x)>f(1)=-2.$ So:
$$\left|\int_{1/2}^1 f(2x)^n\,dx \right|\leq 2^{n-1}.$$
On the other hand, when $\frac16<x<\frac13,$ $f(2x)\leq f(1/3)=f(2/3)=-\frac{20}{9}.$ So:
$$\left|\int_{0}^1 f(2x)^n\,dx \right|\geq \frac16\left(\frac{20}9\right)^n.$$
So the absolute value of your quotient is less than: $$3\left(\frac{9}{10}\right)^n,$$ which converges to $0.$
We could have picked any symmetric interval around $\frac{1}{4}$ of length less that $\frac{1}{4},$ $(1/6,1/3)$ was just the simplest.

More generally, if $h(x)$ is a continuous non-negative function on $[a,b]$ which is not zero everywhere, and with all its maximum values taken in $[a,c)$ for some $c\in (a,b),$ then $$\frac{\int_c^b h(x)^n\,dx}{\int_a^b h(x)^n\,dx}\to 0.$$
Essentially, if $M=\sup_{x\in [a,b]} f(x)$ is the maximum, and $M_1=\sup_{x\in [c,b]} f(x)$ satisfies $M_1<M,$ then for some interval $(u,v)$ in $(a,c)$ we have the $h(x)>\frac{M_1+M}{2}$ for $x\in(u,v)$ and this:
$$\int_{c}^b f(x)^n\,dx \leq (b-c)M_1^n.$$
and:
$$\int_{a}^b f(x)^n\,dx \geq (v-u)\left(\frac{M_1+M}2\right)^n.$$
So you quotient is bounded above by $$\frac{b-c}{v-u}\left(\frac{2M_1}{M+M_1}\right)^n$$
We have $0<\frac{2M_1}{M+M_1}<1,$ so this goes to zero.
In your case, $h(x)=2+2x-4x^2,$ $a=0,b=1,c=1/2,$ $M=2\frac12$ at $x=1/4,$ and $M_1=h(1/2)=2.$
Comment: Referring to "On the other hand…": Doesn't the inequality hold only for $x\in (\frac 16, \frac 13)$? How do you apply it to the integral over $[0,1]?$ Yes, I can generalise to an interval centered at $\frac 14$, but $[0,1]$ does not satisfy that criterion.
Comment: The other parts of the integral contribute non-zero values, but only increase the absolute value of the integral. @insipidintegrator This is where it is useful that $x^2-x-2\leq 0$ on $[0,2].$ The additional values outside $(1/6,1/3)$ have the same sign, so can only add to the absolute value.
Comment: Oof. Mind-blowing stuff in here.
Comment: Basically, for non-negative  functions: $$\int_a^b f(x)\,dx\geq \int_u^v f(x)\,dx$$ for $a\leq u\leq v\leq b.$
Answer: For limits as $n \to \infty$, we often don't need exact values of complicated terms, just a general comparison to the size of the result in terms of $n$.
First notice $4x^2 -2x-2 = 2(x-1)(2x+1)$ is negative on the region $0 \leq x < 1$, so $-4x^2+2x+2$ is positive (and both are zero when $x=1$).
To show convergence to zero, we can look at absolute values. When $n$ is odd, the integrand is never positive, and when $n$ is even, the integrand is never negative, so we don't have any "cancellation", and
$$ \left| \int_a^b (4x^2 -2x -2)^n\, dx \right| = \int_a^b |(4x^2-2x-2)^n| \, dx = \int_a^b (-4x^2+2x+2)^n\, dx $$
as long as $0 \leq a < b \leq 1$.
Also completing the square,
$$ -4x^2+2x+2 = -\left(2x-\frac{1}{2}\right)^2 + \frac{9}{4} $$
So if $0 \leq x \leq \frac{1}{2}$, then
$$ \left|2x-\frac{1}{2}\right| \leq \frac{1}{2} $$
$$ -4x^2+2x+2 \geq -\left(\frac{1}{2}\right)^2 + \frac{9}{4} = 2 $$
$$ \int_0^{1/2} (-4x^2+2x+2)^n \, dx \geq \int_0^{1/2} 2^n\, dx = 2^{n-1} $$
And since $(-4x^2+2x+2)^n$ is positive,
$$ \int_0^1 (-4x^2+2x+2)^n\, dx \geq \int_0^{1/2} (-4x^2+2x+2)^n\, dx \geq 2^{n-1} $$
The parabola is always less than or equal to the tangent line at $x=\frac{1}{2}$:
$$ -4x^2+2x+2 = -4\left(x-\frac{1}{2}\right)^2 -2x+3 \leq 3-2x $$
$$ \int_{1/2}^1 (-4x^2+2x+2)^n\, dx \leq \int_{1/2}^1 (3-2x)^n\, dx = \left. -2^n \frac{(\frac{3}{2}-x)^{n+1}}{n+1} \right|_{x=1/2}^{x=1} = -2^n \frac{2^{-n-1}-1}{n+1} $$
$$\int_{1/2}^1 (-4x^2+2x+2)^n\, dx \leq \frac{2^n - \frac{1}{2}}{n+1} < \frac{2^n}{n+1} $$
Finally,
$$ \left| \frac{\int_{1/2}^1 (4x^2-2x-2)^n\, dx}{\int_0^1 (4x^2-2x-2)^n\, dx} \right| = \frac{\int_{1/2}^1 (-4x^2+2x+2)^n\, dx}{\int_0^1 (-4x^2+2x+2)^n\, dx} < \frac{\frac{2^n}{n+1}}{2^{n-1}} = \frac{2}{n+1} $$
So the limit as $n \to \infty$ approaches zero.
Comment: how do your two obtained expressions help me to find anything about $\int_0^1(-4x^2+2x+2)^n dx$?
Comment: They help find the limit of the quotient as $n \to \infty$.
Comment: The first major result has limits of integration as 0 and 1/2. The second has 1/2 to 1. But  the inequalities have opposite signs, so I cant conclude an integral with limits 0 and 1.
Comment: The absolute value of $\int_0^1$ is more than the absolute value of either piece, so bigger than $2^{n-1}$. The opposite inequality directions are for the division step: we can conclude $A/B \leq C/D$ if we know $A \leq C$ and $B \geq D$ (all positive).
Comment: So I get the ratio less than equal to $\frac{(3/2)^n}{n+1}$. Does this converge to 0?
Comment: Oh yeah, it doesn't. My bounds aren't tight enough, it turns out.
Comment: I've fixed this answer, I think.


Elementos inseridos via .html() e ação das teclas com jQuery

Question: A idéia do código é a de pesquisar produtos e inserir o link do produto quando o usuário selecionar o link do registro como um produto vinculado. Ao clicar no input[type='radio'], um novo campo é inserido abaixo do campo da URL através do .html() do jQuery.
Inseri um retorno de log no console para saber se o código estava reconhecendo o evento .keyup() do campo, mas não há respostas.

$(document).ready(function(){

  $("input.tipoURL").on('click',function() {

    var value = $(this).val();

    if(value=='prod') {

      $('#prURL').val('');
      $('#return').html("<input type='text' name='listaProd' id='listaProd' placeholder='Pesquise pelo produto'/>

");

    } else if(value='link') {

      $("#prURL").val('');
      $("#return").html('');

    }

  });

  $('#listaProd').keyup(function(e){

    e.preventDefault();
    var value = $(this).val();
    var contaChar = value.length;

    window.alert('Acessou');

    if(contaChar<=3) {
      $('#returnProd').html('');
    }

    if(contaChar>3) {
      $("#returnProd").load("lista.php?prod=" + value,function(data){
        console.log(data);
      });
    }

  });

 });

<input type='text' name='prURL' id='prURL'/>

<input id='tipoURLlink' type='radio' name='tipoURL' value='link' id='tipoURL' class='tipoURL' checked/> Link

<input id='tipoURLprod' type='radio' name='tipoURL' value='prod' class="tipoURL"/> Produto

Answer: Como você está inserindo um elemento no DOM de forma dinâmica, e a associação do evento keyup foi feita antes do elemento existir, o mesmo não é executado.
Altere a linha:
$('#listaProd').keyup(function(e){

Por:
$(document).on('keyup', '#listaProd', function(e){

Desta forma, você passa a interceptar qualquer evento keyup dentro do documento que contenha o id #listaProd.

$(document).ready(function(){

  $("input.tipoURL").on('click',function() {

    var value = $(this).val();

    if(value=='prod') {

      $('#prURL').val('');
      $('#return').html("<input type='text' name='listaProd' id='listaProd' placeholder='Pesquise pelo produto'/>

");

    } else if(value='link') {

      $("#prURL").val('');
      $("#return").html('');

    }

  });

  $(document).on('keyup', '#listaProd', function(e){

    e.preventDefault();
    var value = $(this).val();
    var contaChar = value.length;

    window.alert('Acessou');

    if(contaChar<=3) {
      $('#returnProd').html('');
    }

    if(contaChar>3) {
      $("#returnProd").load("lista.php?prod=" + value,function(data){
        console.log(data);
      });
    }

  });

 });

<input type='text' name='prURL' id='prURL'/>

<input id='tipoURLlink' type='radio' name='tipoURL' value='link' id='tipoURL' class='tipoURL' checked/> Link

<input id='tipoURLprod' type='radio' name='tipoURL' value='prod' class="tipoURL"/> Produto

Comment: é uma boa prática generalizar o uso de $(document).on('keyup'),...... ou somente para casos específicos de manipulação de conteúdo gerado via DOM ? Grato.


Is there any drawback of using Internal Impala table vs External Impala table?

Question: We know of following advantage of using internal tables;

Internal table provides merge functionality (update single column)
Query optimization and query cache

Are there any drawbacks of using Internal Tables?
Answer: Most apps uses internal tables to get benefit of impala. Most importantly, you/hive are the owner of the table and not someone else.
I have seen people uses external table is when they want to use less expensive staging area or reading from some external file not a part of warehouse. But for target data/final data, we should use internal table which are managed/owned by hive/impala.
If you have very good test case for using non managed tables, you can go for it, but i would strongly recommend to use internal.


Como realizar um Left Join com LINQ C# usando meu SQL?

Question: Exemplo que funciona no SQL:
select * from Doacoes
inner join Projetos on Projetos.IdProjeto = Doacoes.IdProjeto
left join Pedidos on Doacoes.IdDoacao = Pedidos.IdDoacao
left join Recompensas on Pedidos.IdRecompensa = Recompensas.IdRecompensa
where Doacoes.IdUsuario = 2017

Realizei a reescrita desta forma, mas não funciona:
from d in banco.Doacoes
join p in banco.Projetos on d.IdProjeto equals p.IdProjeto
join pedi in banco.Pedidos on d.IdDoacao equals pedi.IdDoacao into pedi
join recompensa in banco.Recompensas  on recompensa.IdRecompensa equals
pedi.IdRecompensa into pedi

Comment: Se não me engano é a mesma coisa, `left join pedi in...`. 3 anos que não uso Linq mas acho que é isso msm!
Answer: Para ter o left join no Entity Framework você terá que fazer o seguinte
from d in banco.Doacoes
join p in banco.Projetos on d.IdProjeto equals p.IdProjeto
join pedi in banco.Pedidos on d.IdDoacao equals pedi.IdDoacao into pediLeft
from pedi in pediLeft.DefaultIfEmpety()
join recompensa in banco.Recompensas on recompensa.IdRecompensa equals pedi.IdRecompensa into recoLeft
from recompensa in recoLeft.DefaultIfEmpety()

De uma olhadinha nessa pergunta Entity Framework Left Join também.


An example of a sequence of differentiable functions defined on $[0,1]$.

Question: Help me to find an example of a sequence of differentiable functions defined on $[0,1]$ that converge uniformly to a function $f$ on $[0,1]$ such that there exists $x \in (0,1)$ such that $f$ is not differentiable at $x$.
Answer: Any continuous function is a uniform limit of polynomials, so pick your favourite non-differentiable continuous function, and that would work!
In fact, if $f$ is such a function, say $f(x) := |x- 0.5|$, then take the sequence to be the sequence of Bernstein polynomials
$$
B_n(f)(x) := \sum_{k=1}^n {n\choose k} f\left(\frac{k}{n}\right) x^k (1-x)^{n-k}
$$
Then $B_n(f) \to f$ uniformly.
Edit: A simpler example: Take $f(x) = |x-0.5|$ and consider
$$
f_n(x) = \sqrt{\frac{1}{n^2} + f(x)^2}
$$
Then check that $f_n$ is differentiable and
$$
f(x) \leq f_n(x) \leq f(x) + 1/n \quad\forall x\in [0,1]
$$
and so $f_n \to f$ uniformly.
Comment: Perhaps, but it solves the problem efficiently while also indicating how to find such a sequence given a specific function. All desirable qualities in a solution, IMHO.
Comment: I do agree that it's a correct answer that uses a neat result. The original question appears to be at a rather elementary level of real analysis, however. As such, I seriously doubt that this answer is at all useful to the OP.
Comment: @PrahladVaidyanathan Is it possible to do it without bernstein polynomials ? i am not introduced to it
Comment: @JamesMatthews: Have posted a simpler example :)
Answer: Consider the $C^1$-functions
$$f_n(x):=\sqrt{{1\over n^2}+x^2}-{1\over n}\qquad(n\geq1)\ .$$
One has $f_n(0)=0$ for all $n$, and
$$f_n(x)={x^2\over \sqrt{{1\over n^2}+x^2}+{1\over n}}\to |x|\qquad(n\to\infty)$$
for all $x\ne0$. It follows that $\lim f_n(x)=|x|$ for all $x\in{\mathbb R}$, which is not differentiable at $0$.


Python - FileNotFoundError: [Errno 2] No such file or directory

Question: titles = [line.rstrip() for line in open('./nlp_class/all_book_titles.txt')]

# copy tokenizer from sentiment example
stopwords = set(w.rstrip() for w in open('./nlp_class/stopwords.txt'))

I tried to run the python file 'books.py' but it gave this error:
Traceback (most recent call last):
  File "books.py", line 14, in <module>
    titles = [line.rstrip() for line in open('./nlp_class/all_book_titles.txt')]
FileNotFoundError: [Errno 2] No such file or directory: './nlp_class/all_book_titles.txt'

The full directory is: C:\Python36\python_bible\nlp_class
The 'books.py' file location: C:\Python36\python_bible\books.py
The full code is here: https://jsfiddle.net/4rd2knbu/
Comment: Does the file `C:\Python36\python_bible\nlp_class\all_book_titles.txt` exist?
Comment: yes both files exist
Comment: Have you tried giving the absolute, rather than relative, path: C:/Python36/python_bible/nlp_class/all_book_titles.txt
Comment: JsFiddle doesn't run Python code ;)
Answer: I suspect the issue is that you're using the UNIX path separator / on a Windows system instead of using the Windows path separator \. You can write OS-independent code using os.path.join (which will automatically use the correct separator):
import os

titles_file = os.path.join("nlp_class", "all_book_titles.txt")
titles = [line.rstrip() for line in open(titles_file)]

# copy tokenizer from sentiment example
stopwords_file = os.path.join("nlp_class", "stopwords.txt")
stopwords = set(w.rstrip() for w in open(stopwords_file))


Adding a permanent PREROUTING rule in iptables using firewall-cmd

Question: I'm trying to add a new rule in the PREROUTING chain in iptables (NAT) using firewall-cmd on RHEL 7:
$ firewall-cmd --permanent --direct --add-rule ipv4 nat PREROUTING 0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8161
Then I check the iptables via $ iptables -t nat -L:
...
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
PREROUTING_direct  all  --  anywhere             anywhere
PREROUTING_ZONES_SOURCE  all  --  anywhere             anywhere
PREROUTING_ZONES  all  --  anywhere             anywhere
...
Chain PREROUTING_direct (1 references)
target     prot opt source               destination
REDIRECT   tcp  --  anywhere             anywhere             tcp dpt:http redir ports 8161
...

However, if I run an equivalent iptables command as follows:
...
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
PREROUTING_direct  all  --  anywhere             anywhere
PREROUTING_ZONES_SOURCE  all  --  anywhere             anywhere
PREROUTING_ZONES  all  --  anywhere             anywhere
REDIRECT   tcp  --  anywhere             anywhere             tcp dpt:http redir ports 8161
...
Chain PREROUTING_direct (1 references)
target     prot opt source               destination
REDIRECT   tcp  --  anywhere             anywhere             tcp dpt:http redir ports 8161

I get this additional rule in the Chain PREROUTING and this allows prerouting to work even if the firewall is disabled (i.e., disabling firewall daemon and running the iptables command).
So, my question is two-fold:

Is there a firewall-cmd command that does exactly the same as the iptables command above?
Can this rule be added permanently via firewall-cmd and stay there even after firewall daemon is disabled?
Answer: You are using firewall-cmd with --direct option which means it accepts an iptables command. So, you can just the same options with iptables -t nat to have the same effect with one exception. Using firewall-cmd this way will add NAT rule to PREROUTING_direct chain while using iptables directly with add the rule to PREROUTING chain.
In the output of iptables -t nat -L, you added the rule twice: once to each chain.
As for the second part of question, firewalld service will remove all defined chains when stopped. So, rules added to PREROUTING_direct will not be available any more. Short answer is No.
Answer:
I get this additional rule in the Chain PREROUTING and this allows prerouting to work even if the firewall is disabled.

So I am not completely sure that is true.
If the PREROUTING is no longer working when you stop firewalld (and I am not clear why you would do that), then I would assume that is because firewalld is removing its entire policy (e.g. iptables -F/iptables -X). In which case, the fact you added another version of the same rule manually would make little difference.
iptables -F would still remove it.
Your (first) command should be giving you a permanent pre-routing rule as you wanted, so long as you do not stop firewalld. I would tend to think that should be sufficient, but I may very well be missing something about your needs.
Just to be clear: there is no practical difference between having your prerouting rule in the PREROUTING_DIRECT chain or the PREROUTING chain.
Both approaches work the same, have the same effect, and absent other changes to your firewall policy, should be doing what you need.
The only difference is that firewalld is essentially doing a little admin behind the scenes for you, and placing your actual rule in a user-defined chain rather than a system defined one.
tl;dr: I would just keep firewalld running, and use its commands to create and manage your rules. While the firewall-cmd vs 'raw' iptables commands have slightly different visual effects, they have the same effect on the network traffic.
Comment: You're right - the sentence was a bit unclear. What I meant there was actually running the iptables command *after* disabling the firewall. This would add the rule correctly.


Finding the converges of a sequence

Question: Problem 69, from Calculus by Larson, 9e.

$$a_n = \left(1+\frac{k}{n} \right)^n$$

I know that is $e^k$, but that is not a fixed number, is this legal?
Doesn't it have to converge to a specific number?
Comment: well, we assumed (i supposed) that $k$ is fixed, so $e^k$ is fixed number
Comment: It would also have to be the limit and n approaches infinity. Think of k as a constant. Similar to the constant of integration (+C) this k is just a number.
Answer: $e^k$ is a fixed number, as $k$ is here an arbitrary constant.
As you see you are having $a_n$ so there is only a dependence from $n$

Finding the converges of a sequence


Reading WMI Classes from non-defaul namespace

Question: i have a simple Problem. I cant read a specific Instance of an WMI class.
ManagementScope scope = new ManagementScope(@"\\.\root\OpenHardwareMonitor", null);
scope.Connect();
ManagementPath printersPath = new ManagementPath("Sensor");
ObjectGetOptions options = new ObjectGetOptions(null, TimeSpan.MaxValue, true);

ManagementClass printersManager = new ManagementClass(scope, printersPath, options);
foreach (ManagementObject printer in printersManager.GetInstances())
{
    Console.WriteLine(printer["Name"]);
}

ManagementPath path = new ManagementPath(scope.Path + ":Sensor.Name='CPU'");

ManagementObject disk = new ManagementObject();
disk.Path = path;
disk.Get();

Here i get an exception, but the upper list works and 'CPU' is shown.
The Exeption points to the ';' of Get(). Details: (using German VS12)
System.Management.ManagementException wurde nicht behandelt.
  HResult=-2146233087
  Message=Ungültiger Objektpfad <--- invalid objektpath
  Source=System.Management
  StackTrace:
       bei System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
       bei System.Management.ManagementObject.Get()
       bei Hello_openHWM.Program.getCPUTemp() in c:\Users\XXX\Documents\Visual Studio 2012\Projects\Hello openHWM\Hello openHWM\Program.cs:Zeile 46.
       bei Hello_openHWM.Program.Main(String[] args) in c:\Users\XXX\Documents\Visual Studio 2012\Projects\Hello openHWM\Hello openHWM\Program.cs:Zeile 18.
       bei System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       bei System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       bei Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       bei System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       bei System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       bei System.Threading.ThreadHelper.ThreadStart()
  InnerException:

What am i doing wrong? I am new to C#
Comment: Can you show exception details?
Comment: And show exactly _where_ you get the exception.
Comment: sure. i edited it in starting post
Answer: It seems which you are passing the wrong WMI object path to the WMI, as workaround you can use a WQL sentence to retrieve the proper data.
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;

namespace GetWMI_Info
{
    class Program
    {

        static void Main(string[] args)
        {
            try
            {
                ManagementScope Scope;
                Scope = new ManagementScope(String.Format("\\\\{0}\\root\\OpenHardwareMonitor", "."), null);

                Scope.Connect();
                ObjectQuery Query = new ObjectQuery("SELECT * FROM Sensor Where Name LIKE 'CPU%'");
                ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

                foreach (ManagementObject WmiObject in Searcher.Get())
                {
                    Console.WriteLine("{0,-35} {1,-40}","Identifier",WmiObject["Identifier"]);// String
                    Console.WriteLine("{0,-35} {1,-40}","Index",WmiObject["Index"]);// Sint32
                    Console.WriteLine("{0,-35} {1,-40}","InstanceId",WmiObject["InstanceId"]);// String
                    Console.WriteLine("{0,-35} {1,-40}","Max",WmiObject["Max"]);// Real32
                    Console.WriteLine("{0,-35} {1,-40}","Min",WmiObject["Min"]);// Real32
                    Console.WriteLine("{0,-35} {1,-40}","Name",WmiObject["Name"]);// String
                    Console.WriteLine("{0,-35} {1,-40}","Parent",WmiObject["Parent"]);// String
                    Console.WriteLine("{0,-35} {1,-40}","ProcessId",WmiObject["ProcessId"]);// String
                    Console.WriteLine("{0,-35} {1,-40}","SensorType",WmiObject["SensorType"]);// String
                    Console.WriteLine("{0,-35} {1,-40}","Value",WmiObject["Value"]);// Real32

                }
            }
            catch (Exception e)
            {
                Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace));
            }
            Console.WriteLine("Press Enter to exit");
            Console.Read();
        }
    }
}

Comment: does the % after CPU mean wildcard? because there are instances with names like 'CPU #1'.
Comment: Yes it's a wildcard, you can modify the WQL sentence as you want.


mockResolvedValue is not a function on partial mock with Jest/Typescript

Question: I am trying to partially mock a module, and set the return value for the mocked method as needed in certain tests.
Jest is throwing this error:
mockedEDSM.getSystemValue.mockResolvedValue is not a function
TypeError: mockedEDSM.getSystemValue.mockResolvedValue is not a function

My mock:
jest.mock('../src/models/EDSM', () => ({
  __esModule: true,
  ...jest.requireActual<typeof import('../src/models/EDSM')>('../src/models/EDSM'),
  getSystemValue: jest.fn(),
}));
const mockedEDSM = jest.mocked(EDSM);

Within tests:
it('should test', () => {
  mockedEDSM.getSystemValue.mockResolvedValue(edsmData);
});

Typescript is throwing no warnings in the IDE, I'm only getting errors from Jest when running the tests.
Answer: Ah of course, found the answer right after posting this!
No need to call jest.mock at the top of the test file, the only thing needed is to spyOn the method within each test (or in a before/after hook):
const getSystemValueMock =
  jest.spyOn(EDSM, 'getSystemValue')
  .mockResolvedValue(edsmData);


HTTP 500 (Internal Server Error) when using google api php client on a remote server

Question: I followed THIS TUTORIAL to upload a file on Google Drive with php, directly from a REMOTE SERVER: so I create new API Project from Google API Console, enable Drive API and Drive SDK services, request OAuth Client ID and Client Secret, and write them in a script, then upload it together with Google APIs Client Library for PHP folder to http://www.MYSERVER.com/script1.php, to retrieve Auth code:
<?php

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';

$drive = new Google_Client();

$drive->setClientId('XXX'); // HERE I WRITE MY Client ID

$drive->setClientSecret('XXX'); // HERE I WRITE MY Client Secret

$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');

$drive->setScopes(array('https://www.googleapis.com/auth/drive'));

$gdrive = new Google_DriveService($drive);

$url = $drive->createAuthUrl();
$authorizationCode = trim(fgets(STDIN));

$token = $drive->authenticate($authorizationCode);

?>

When I visit http://www.MYSERVER.com/script1.php it run perfectly, so I allow authorization and get the Auth code that I can write in a second script. Then I upload it to http://www.MYSERVER.com/script2.php, who looks like:
<?php

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';

$drive = new Google_Client();

$drive->setClientId('X');  // HERE I WRITE MY Client ID
$drive->setClientSecret('X');  // HERE I WRITE MY Client Secret
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));

$gdrive = new Google_DriveService($drive);

$_GET['code']= 'X/XXX'; // HERE I WRITE AUTH CODE RETRIEVED AFTER RUNNING REMOTE script.php

file_put_contents('token.json', $drive->authenticate());

$drive->setAccessToken(file_get_contents('token.json'));

$doc = new Google_DriveFile();

$doc->setTitle('Test Drive');
$doc->setDescription('Document');
$doc->setMimeType('text/plain');

$content = file_get_contents('drive.txt');

$output = $gdrive->files->insert($doc, array(
      'data' => $content,
      'mimeType' => 'text/plain',
    ));

print_r($output);

?>

Well, now I can upload in the same folder of MYSERVER a token.json empty file (writable) and a simple drive.txt (file to upload in my Drive), but when I finally visit http://www.MYSERVER.com/script2.php browser gives everytime a HTTP 500 (Internal Server Error) and obv no file is uploaded in my Google Drive: there are errors in the steps, or some issue with the scripts? Please help me to resolve this!
EDIT:
MYSERVER error log is full of:
PHP Fatal error:  Uncaught exception 'Google_AuthException' with message 'Error fetching OAuth2 access token, message: 'invalid_grant'' in /var/www/vhosts/.../gdrive/google-api-php-client/src/auth/Google_OAuth2.php:113
Stack trace:
#0 /var/www/vhosts/.../gdrive/google-api-php-client/src/Google_Client.php(131): Google_OAuth2->authenticate(Array, NULL)
#1 /var/www/vhosts/.../gdrive/sample2.php(23): Google_Client->authenticate()
#2 {main}
thrown in /var/www/vhosts/.../gdrive/google-api-php-client/src/auth/Google_OAuth2.php on line 113

Comment: Check your server logs for what the actual error is.
Comment: your code seems good for now, check your error log for errors, also double check file permissions, it would trigger an error if the script does not have a permission to write files ( which seems for now the only possible problem)
Comment: that are access logs. check the error logs.
Comment: @John : Those* :p and thank you for the good laugh ! +1
Comment: Huxley, my man, those inputs are from the ACCESS log, it is fairly useless for us now, we need ERROR logs which can be found in error_log
Comment: Huh sorry, @SAFAD, I have (re)edited question :=)
Answer: it seems that you cannot get new access token because your old one has not expired yet, that is what's this code is telling you :
'Google_AuthException' with message 'Error fetching OAuth2 access token, message: 'invalid_grant'
You must get the access token ONCE, save it somewhere and use it until it expires, you can not get new access token each time you try to query something
to revoke your first access token go to Google API Console and you will find it under Client ID for installed applications
Best Regards
Comment: okay, It is a little bit late and this was a hard day, I did not read the error properly, but now I did, please see the updated answer as we are going to approach the error in a different way
Comment: Unluckly I had already checked it: token.json has 666 permission and script2.php has 766 (or 777), but I get same error..
Comment: and what about the directory permissions ? is the directory writable ?
Comment: Sure, www.MYSERVER.com/gdrive directory has 777 permission :(
Comment: your log, other than the uncaught exception, is there anything before it ? there should be something about file permissions or something..
Comment: No, I can see only the above error logs, apart a useless `File does not exist: /var/www/vhosts/.../httpdocs/favicon.ico`
Comment: Thank you SAFAD, I have simply re-visited the URL of sample.php, got a new OAuth Code, written it again in the sample2.php script and now it works (Only the first time)! So, if I would like to run AGAIN sample2.php after a few minutes, whats the right way?
Comment: You save my life @SAFAD. It works for me too. Thanks a lot.


How to log incoming POST requests

Question: We are seeing a lot of POST requests by bots to /register pages or pages with forms. This is likely an attempt to make an SQL injection.
What's the best way to log the full POST request and see the payload data?
Cheers
Answer: You may use HTTP Request Logger module.
Comment: Thanks - Any Drupal 7 ideas? This module is Drupal 8 & above.
Answer: If you are Nginx, below answer is the easiest way to log POST requests including data being carried.
https://stackoverflow.com/questions/4939382/logging-post-data-from-request-body

How to log incoming POST requests


How to change glyphicon icon class on click event?

Question: I have list of submenu at the sidebar with an glyphicon icon. My one li is clicked the icon should be changed. At the moment when I click on one li all the icon are being changed.
This is the code I am working on. I am not sure how to fix this issue.
HTML

            Sales

...

            Report

...

ts.
export class SidebarComponent implements OnInit {
    sign = 'up';

    changeIcon(): void {
        if (this.sign == 'up') {
            this.sign = 'right';
        } else {
            this.sign = 'up';
        }
    }
}

Comment: Have you tried with `ngClass`? ``
Comment: @veben i have not tried ngClass.. how to use it here
Answer: here is a working
example
of what you need, if you have any question regarding the code don't hesitate to ask.
Comment: your code is ok but my glyphicon is at right side and when I click your code make it appear at left side.
Comment: i think you should add a "arrow" class to the class name in the ts file:el.nativeElement.className = "glyphicon glyphicon-menu-up arrow";
Comment: I have a question why there is if and else if with same code
Comment: i don't fully understand your question, but i think you are asking why i used if and else if instead of if else, coz i assumed that you have more than two menu, but if you have just two you can edit to be if else.
Comment: if (el.nativeElement.id== numb) {
            this.ToggleIconClass(el);
          }
          else if ((el.nativeElement.id== numb) ){
          this.ToggleIconClass(el);}
        } Are they same condition ?
Comment: Yes they are, sorry for the bug you can delete  the else  statement


Gradle: Declaring dependency in top level and sub module- which is used?

Question: When different versions of dependencies are declared in the top-level build.gradle and sub-module build.gradle, which one takes precedence?
For example if in my top level build.gradle I had junit:junit:4.8.2 but in a sub-module had junit:junit:4.10 ?
Also, what does declaring a dependency in the top level build.gradle do? Should all dependencies just be declared in sub-modules?
Answer: Having
// root build.gradle
subprojects {
    dependencies {
        compile "junit:junit:4.10"
    }
}

and
// submodule build.gradle
dependencies {
    compile "junit:junit:4.8.2"
}

is essentially the same as just having
// submodule build.gradle
dependencies {
    compile "junit:junit:4.8.2"
    compile "junit:junit:4.10"
}

This means you have two version of junit declared in your submodule. Now Gradle conflict resolution kicks in here. The default resolution for
dependency conflicts is to choose the newer version. So junit 4.10 will be picked. To change this behaviour you can configure the resolution strategy.


Enviar Botão Adicionar ao Calendário com PHPMailer

Question: Tenho esse script.

    Add to Calendar
    05/30/2017 16:00
    05/30/2017 18:00
    America/Caracas
    Summary of the event
    Description of the event
    Location of the event
    MM/DD/YYYY
    apjeYlqFLzfsSVnNdmRH28418

Segundo o tutorial dessa pagina
Gostaria de enviar o botão "Adicionar Ao Calendário" usando o PHPMailer
Só que não consegui adicionar o javascript na mensagem
Mesmo setando a linha
$mail->IsHTML(true);

Answer: Quando você manda um email, automaticamente o Cliente de Email, bloqueia qualquer script que venha a ser incluído no corpo do e-mail.
Ou seja não vai ter como você adicionar o Widget do addevent no corpo do email.
Sugiro você dar uma olhada na API da própria addevent e checar se existe a possibilidade de você utilizar os serviços deles, ai você apenas iria criar um link simples no corpo do email, que redirecionaria para esta página que será incumbida de dar continuidade ao registro dos eventos.


Why cannot i download nodemon?

Question: I am trying to download nodemon and am quite unsure why it is not downloading. I have got the following error?
npm install -g nodemon

npm ERR! code EACCES
npm ERR! syscall mkdir
npm ERR! path /usr/local/lib/node_modules/nodemon
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/nodemon'
npm ERR!  [Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/nodemon'] {
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'mkdir',
npm ERR!   path: '/usr/local/lib/node_modules/nodemon'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/ryandevasia/.npm/_logs/2021-12-04T05_47_29_366Z-debug.log

What must be done to download the module?
Answer: The EACCES error means that npm does not have permissions to install global packages. To do this, you'll need to run the command as root (which has permission for the npm global directory) with sudo. So you can run sudo npm install -g nodemon with an administrator account and it will work, after you enter your password.
Comment: I happen to have the same problem with downloading sqlite3 with npm would sudo work with that
Comment: It should work with globally installing anything. But if it's a library that a project depends on, you should install it locally. Global stuff is for CLIs and other tools (like nodemon).
Answer: Try installing with sudo:
sudo npm install -g nodemon

Usually it's better to install nodemon as a dev dependency with
npm i -d nodemon

That way you can build it into your scripts and it helps with collaboration:
"start" : "nodemon index.js"

Comment: You may want to install nodemon globally if you are working on multiple js files in one npm project or js files outside of an npm project.
Comment: I've always found working on a project with multiple people it was complicated trying to replicate an environment so building it as a dependency and adding as a script works better.

Why cannot i download nodemon?


Force existing users to complete profile after adding required fields

Question: I inherited a Drupal (D7) site with existing users. Now I want to add new fields to the user profile, but they will be required.
New users will have to fill out these fields when registering. Existing users will have to fill out these fields when trying to save their profile.
But what I would want is for existing users to be redirected to their profile page after logging in. Of course, I would also like to display a message on that page that they need to complete their profile with this new information.
Is this possible in Drupal?
Answer: I fixed this with the Rules Module.
First, I set the necessary fields in the user profile as required. That fixes it for new users that want to register.
Then, a little more complex, I used the Rules module for the existing user, with the following setup:

Event: user has logged in
Actions:

page redirect (to user/[account:uid]/edit)
show a message on the site (to clarify why the user was sent here)

Conditions:

One OR group with the following conditions:
Data value is empty (with site:current-user:field-lastname)
Data value is empty (with site:current-user:field-firstname)
etc.

This works perfectly. The only minor point is that when I add a required field, I also have to add a condition to the OR group manually.
Answer: You can do it of course. But for that you have to create your own module with the hook_user_login. You can also give a look at the documentation that has a simple example to redirect user to his profile page to fill data.
Comment: Or use Rules Module to implement `hook_user_login()`
Answer: Peter,
there are two modules for such thing:

complete_profile
pfff

But.. I want to try your rules solution because the modules above don't work with hybridauth :(.
If you don't use hybridauth you'd better try complete_profile. It doesn't allow user to go to another pages if required fields are empty.
Comment: I had solved it with the Rules Module, but a while ago, I switched to the Complete Profile module. It makes it easier (when I changed fields on my user entity, I would have to change my rule).


Drupal Views for 2 Title Styles

Question: Mock:
Site: http://www.mastersfunds.com.php5-23.dfw1-2.websitetestlink.com/funds-and-performance/equity-fund
Brief: The mock has the title with 2 font styles. The first part is in blue text and the fund/ticker is in a smaller, light gray font.
Is there a way to use VIEWS to display the TICKER font/html directly after the Title as displayed in the mockup? What VIEWS settings would I use?
Comment: This should be fairly easy to do, but right now, it looks like it's a QuickTab. Do you want it to be a View instead?
Comment: Also, is the 'ticker' a CCK field, or will you be adding that manually?
Comment: Well right now the TITLE for the QUICK-TAB can only take 1 style. I want to show a custom HTML snippet AFTER the quick-tab title so the ticker can be a smaller/gray style instead of the style of the h2 title.
Comment: This is only my 3rd or 4th Drupal site and I'm not too familiar with CCK. The ticker is no where yet, I noticed in VIEWs there's an option to add a field AFTER whatever the view is. And that field accepts html.
Answer: I think as a relatively new Drupal developer, you could benefit tremendously from getting to know CCK. This will allow you to have flexibility with how fields are laid out and ensure that page layouts remain consistent.
The way you've approached the task, I can think of two ways to get that ticker to show: using jQuery and using a theme function. If you know about template.php and theme overrides, I'd recommend that route. Otherwise, this should be doable with jQuery:
Using jQuery:
Place this in a js file:
$(function() {
    $('#block-quicktabs-fundsperformancetabs h2').append('
MSILX, ETC
');
});

And in your stylesheet
.ticker {
    text-transform: uppercase;
    color: #CCC;
    font-size: 11px;
}

Be sure to include your js file in your theme's info file.
scripts[] = js/custom.js

This has the downside of being 'in the code' instead of editable by the client, but that's where CCK would come in.
Answer: Views is a tools to query and display data (most of the time nodes). While views is pretty flexible, its main and well documented usages are blocks and pages with data from the database. We don't have that much information, but it doesn't seems like you need to query your database to build a list of items to be displayed. You are rather looking for a way to display the fund/ticker information right after the title of the page.
IMHO, the proper way to do it is to have a hook_preprocess_HOOK implementation for the block.tpl.php template to retrieve the tickers information and store in the $variables array received as argument. Then in this template, display the information right after the title. The tricky part would be retrieving the tickers since you won't have that much information about the block context while in the hook_preprocess_HOOK implementation.
In your custom module .module file or in your theme's template.php
function MODULE_preprocess_block(&$variables) {
  $tickers = get_ticker_from_some_context();
  // Use a custom theme hook to format the tickers
  $variables['tickers'] = theme('tickers', $tickers);
}

In your block.tpl.php
<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
<?php if ($block->subject): ?>
  <h2<?php print $title_attributes; ?>><?php print $block->subject ?>

  <?php if !empty($tickers):?>$tickers<?php endif;?>
<?php endif;?>
  <?php print render($title_suffix); ?>

  <div class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>

Drupal Views for 2 Title Styles


Common method order for Rails models

Question: I'd like to keep my code tidy and follow the best practices amongst rails developers which leads me to this question. Let's say for instance I have the following method types for my model

Model Associations
Validations
Scopes
Callbacks
Other Custom Methods

What is the usual order that the above appear in? Please feel free to add any others I might've left out.
Bonus: Should you group variables alongside their associated method types or should all variables be grouped at the beginning of the model? Let's say I had a variable to store a regular expression. Is it best to keep it close to the validation(s) or at the top of the model similar to where you would keep globals?
Example:
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, uniqueness: true, length: {within: 5..50}, format: { with: VALID_EMAIL_REGEX }

Comment: Related reading:
https://github.com/bbatsov/rails-style-guide#models and
http://rails-bestpractices.com/posts/75-keep-code-struture-in-models-consistent
Comment: Not sure if it's best practices but what you describe is pretty much what I do.  If you move your email regex until after the validation I think you'll find it won't work.
Comment: Yeah my bad. I meant either close by or at the very top.
Comment: This is not just opinion based, there are bugs that arise because ordering matters, the problem is that associations define callbacks, just `as accept_nested_attributes` does, and the order of callbacks depends on definition. See [this issue](https://github.com/rails/rails/issues/16823) for more info.
Answer: It doesn't matter what convention you follow as long as you keep it consistent and easier for other developers to understand.
Commonly followed ordering would be
1. associations
2. scopes
3. class methods
4. validations
5. callbacks
6. instance methods

Some people also move class methods below callbacks. Again, its up to you. But keep it consistent
Comment: Just to mention that this is currently the order in the styling guide (by rubocop) if you want to update your answer.
https://github.com/rubocop/rails-style-guide#macro-style-methods
Answer: I follow this order:

associations
scopes
validations
callbacks
class methods
instance methods

Again its really up to you and the important part is to BE CONSISTENT.
I put all variables in the beginning, you could put them anywhere but I think it advantageous to keep them together.

Common method order for Rails models


Need To Update One Entity Through Another

Question: I've been trying every angle I can, but I keep running into Revision ID errors when I try to update a referenced or related entity of another entity. I believe this might be on the right track? I'm not sure why these are occurring. I just need a simple field to be updated when the related entity is updated.
It also throws this error:
DatabaseTransactionNoActiveException
Is there any documentation on how to update one entity when another is updated? I just need to be pointed to the right track on this one.
Comment: Hello, and welcome to Drupal Answers. May you show your code? Without seeing any code, it is not possible to say what is wrong in the code.
Comment: I think that's my question, I have a custom module already set up and ready to code, I'm just not sure where to start with this. I get this error (It's an undefined property error) when trying to use either [Rules](http://drupal.org/project/rules) or with this [Entity Reference Sync](http://drupal.org/project/ref_field) module. I prefer code but being fairly new to Drupal it's hasn't been easy to find documentation on certain things :/ Oddly enough I also get a Revision ID error when I run the update.php file.
Answer: Okay figured it out. I needed to patch the Redhen module I'm using which was causing a Revision ID error. Im using the Relation, Rules Redhen modules together (and of course the Entity API). Here is the export of the Rule that did it:
<code>{ "rules_update_employment_status" : {
"LABEL" : "Update Employment Status",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules", "relation" ],
"ON" : [ "relation_update" ],
"IF" : [
  { "entity_is_of_type" : { "entity" : [ "relation:endpoints:0" ], "type" : "redhen_contact" } },
  { "entity_has_field" : {
      "entity" : [ "relation:endpoints:0" ],
      "field" : "field_employment_status"
    }
  }
],
"DO" : [
  { "relation_rules_fetch_endpoint" : {
      "USING" : {
        "relation" : [ "relation" ],
        "entity_type" : "redhen_contact",
        "number" : "1"
      },
      "PROVIDE" : { "endpoint_fetched" : { "endpoint_fetched" : "Fetched Endpoint" } }
    }
  },
  { "data_set" : {
      "data" : [ "relation:endpoints:0:field-employment-status" ],
      "value" : "20"
    }
  },
  { "drupal_message" : { "message" : "[endpoint-fetched:full-name]\u0027s Employment Availability has been changed to [endpoint-fetched:field-employment-status]." } }
]
  }
}
</code>
This let me access whatever fields on the endpoint that I wanted then change them if I needed to.


Complex power function $z^a$ for $a=\frac{3}{2}$

Question: I've been having a little trouble here figuring this out. How would one sketch the image of the sector $0 < \theta < \pi/6$, where $\theta$ is the polar angle of the complex number $z$, under the complex power function $w=z^a$ when $a=\frac{3}{2}$? Also, what would happen if $a=i$? It seems the only thing I've been able to get around so far is the case where $a$ is an integer. I would appreciate some guidance here.
Comment: Replace the $z$ with $r\exp(i\theta)$, separate out real and imaginary parts, and you now have parametric equations for a family of curves...
Comment: Putting under the rug (as some interventions here seem to do) the key fact that there is no way to define continuously $z^{3/2}$ on the whole complex plane leaves me uneasy. We all know that $r\exp(i\theta)=r\exp(i(\theta+2\pi))$ and that applying the seemingly obvious operation $z\to z^{3/2}$ to the LHS and to the RHS does not give the same result, don't we? The same objection (only possibly worse) applies to $z^i$.
Comment: @Didier: I guess we could make a branch cut at the ray that is $\pi/6$ radians in angle measure from the positive real axis to make the function continuous?
Answer: Proceeding from @J. M.'s comment:
For $a=3/2$ $w=r^{3/2} e^{\frac{3}{2}i \theta}$ or $w=r^{3/2} \left( {1+ \frac{3i \theta}{2} -\frac{9 {\theta}^2}{8}-\frac{27 i {\theta}^3}{48} + \frac{81 {\theta}^4}{384}+\ldots} \right)$
observe the curve plot at Wolfram Alpha
For $a=i$: $w=r^i e^{-\theta}$
See the Curve
Comment: For which $\theta$? See my comment to the question.


Sort List Of Class using Id property?

Question: I have a class called Questions. This Questions has properties QuestionID and QuestionAnswer. My list of Questions has QuestionID like 2,3,4,15,12,24,22,,,, etc
I need to sort this List of Questions Object based on QuestionID and store in another Questions object.
Comment: How is the list organized? Is it an array of a `List`? Can you supply the actual declaration of `Questions`? From your question it's not clear whether `Questions` represents one single question or that list of questions.
Answer: There is a framework called LINQ designed for this exact sort of task. For example, in C#:
var sortedList = questionList.OrderBy(q => q.QuestionID).ToList();

Comment: Can you explain here how apply desc order?
Comment: @wilo087 Use `OrderByDescending` instead of `OrderBy`.

Sort List Of Class using Id property?


Higlight table row based on current time

Question: Hi i want to highlight the row that's next based on current time
so if "a" is at 7 and it is now 7:10 i want "b" to be highlighted.
And if "f" is at 1800 and it is 18:10 i want to highlight nothing till 00:00 then i want to highlight a again.
Thank you so much.

Answer: I believe the example below does what you need, it runs a function every 3 seconds to check whether the cells with the class .time are in the past or not.
Make sure you change the setInterval timer to something more sensible, it sounds like you wouldn't need to run it every seconds but perhaps every minute would provide more than enough sensitivity?
The highlighting is then all done using CSS, namely the classes .past and .future. The next session is highlighted using the + selector, which finds the first incidence of a class that immediately follows the preceding class, i.e. .past + .future applies styles to the first element with a class .future that is a sibling and immediately following an element with class .past.
Styles are applied to the parent tr using the jquery selector .closest("tr").

// Create table dynamically
setupTable();

// Set the function to run every 3 seconds
checkTime();
v = setInterval(checkTime, 3000);

// Check time function
function checkTime() {

  // Get current time
  const d = new Date();
  h = d.getHours();
  m = d.getMinutes();

  // Print the latest time
  $("#time-now").text(twoDigits(h)+":"+twoDigits(m)+"." + twoDigits(d.getSeconds()));

  // Cycle through each time cell
  $(".time").each(function() {

    // Get the time from the cell
    cellTimes = $(this).text().split(":");
    cellH = parseInt(cellTimes[0]);
    cellM = parseInt(cellTimes[1]);

    // Check if it is in the past
    if (cellH < h || (cellH == h && cellM < m)) {

      // Add past classes, remove future classes
      $(this).closest("tr").addClass("past").removeClass("future");

    } else {

      // Add future class
      $(this).closest("tr").addClass("future");

    }

  });

}

// Standardise times
function twoDigits(inNumber) {

  return inNumber.toLocaleString('en-US', {
    minimumIntegerDigits: 2,
    useGrouping: false
  })

}

// Setup table
function setupTable() {
  d = new Date();
  let hour = d.getHours();

  min = d.getMinutes() - 2;
  while (min < d.getMinutes() + 2) {

    $("#times").append("
" + twoDigits(hour) + ":" + twoDigits(min) + "
");

    min = min + 1;

  }

}
.past {
  color: red;
}

.past+.future {
  background: blue;
  color: white;
}

.future {
  color: green;
}

    Time

Comment: Tahnk you so much
Comment: No worries! Glad it helped


Deny deletion after SFTP upload

Question: I'd like to prevent users from deleting files they have uploaded to my sftp server.  I know I could set up a solution of my own using inotify/dnotify (or pam hook) and lsof which triggers a script to do something such as chattr +i $filename after a file is uploaded and closed. But I wonder if there is something already available as a feature or a solution already vetted and available of which I'm not aware.
The current setup is that I'm using openssh sftp and users are jailed upon connecting.
Answer: If you add your sftp-server umask option -u with parameter 0222, new uploaded files will be created with above mentioned umask, which means they will not have write access for their files, so they will not be able to delete the files.
The line in your sshd_config will look something like this:
Subsystem sftp internal-sftp -u 0222

Comment: Hmm. Chmod should be possible to disable using `-P` option to sftp-server. But if user is able to delete the file, then there is something wrong ...
Comment: Very nice.  I didn't see this in the man page for sshd_config because it's in the man page for sftp-server / internal-sftp.  Because I'm using a `Match Group ...` block for users of a certain group to make sure they're jailed, I think It will look like this, no?
`Match Group chrooted` ...other lines ... `ForceCommand internal-sftp -u 0222`
Comment: using `ForceCommand internal-sftp -u 0222` in the match block indeed created the file as `-r--r--r--` but I was able to delete the file.  I was also able to chmod the file to other perms.
Comment: if a user has mode 0444 on a file, deletion is still possible.
Comment: The mode of the file is not relevant to the deletion of the file. The deletion is authorized or not accordig to the write bit on the containing directory. A shell will probably give a warning or ask for confirmation when deleting a read-only file, but it is just a warning.
Answer: Look at lsyncd(http://code.google.com/p/lsyncd/). It will provide inotify=>action part for your solution. It will look like this:
cat /etc/lsyncd.conf
settings {
    logfile    = "/var/log/lsyncd.log",
    statusFile = "/var/run/lsyncd.status",
    nodaemon   = false,
    insist     = true,
}

-- config action
my_config = {
    delay = 10,
    maxProcesses = 1,
    onCreate  = "chattr +i -R /path/to/dir/*",
}

sync { my_config,
    source="/path/to/dir/",
}
-- EOF

you can change onCreate action for better logic, maybe run a script which will find uploaded files and set chattr +i.
Comment: Glad that my solution helped you:)
Comment: you saw that I'm using openssh sftp, correct?  It's not an option for me to switch to vsftpd at this time.
Comment: Em...actually it's doesn't matter what daemon you use
Comment: I've removed word vsftpd for more clarity
Comment: Your example worked, and I was able to install it as an official debian package.  It's also available from the epel repository.  I did have to make some changes though.  /etc/lsyncd.conf didn't work.  When I opened the systemd unit startup script for lsyncd I saw that it expected its config file to be at `/etc/lsyncd/lsyncd.conf.lua` ...After tweaking that, things worked well!
Comment: Working example with lsyncd:

    sftp> put foo
    Uploading foo to /upload/foo
    foo
    sftp> rm foo
    Removing /upload/foo
    Couldn't delete file: Permission denied

Deny deletion after SFTP upload