browser crashes while displaying 6000 Records in angularjs

Question: I am trying to display the large set of records  with ng-repeat, but the browser crashes.How could I display large dataset without using infinite scroll.
Comment: there is no reason to show `6000` records at a time as user is not going to view `6000` record at time, I'd say that either do pagination or use `infinite scroll`..
Comment: try to paginate the result
Comment: Agree with comments here that displaying 6000 things at once is likely not going to be a good user experience for anyone, so you should strongly think about paginating the results.
Comment: Agree with ur comments. But i have different table structure in a single Page and single scope variable binded all table's Value.
Answer: Like the others suggest, 6000 rows begs to be paged, but technically angular can handle that. I created a codepen with angular generating 10k rows are using ng-repeat to display a table, to show its technically possible. I suggest you use track-by in your ng-repeat as well as ng-cloak to optimize the rendering of that much data.

The reason your browser is crashing is likely due to the way the data is being created (possibly adding each row to the cope at a time and causing many render cycles), or due to the complexity of each rows display. So optimizations could allow you to display that much data without the browser crashing, but its still not a good idea (or a good user experience).
Answer: 6000 records is a problem that begs for paging in some form. Loading 6000 records in one go is not a good solution and especially not considering you are using Angular. You should use an Angular construct such as a dataTable which supports paging.
http://ng-table.com/#/


É possível fazer com que um elemento html se expanda para cima?

Question: Ex: Eu tenho um parágrafo dentro de uma div, e eu quero que sempre que o texto quebre uma linha, ele expanda para cima, ao invés de para baixo (padrão).
Vejam o exemplo:

#content {
      width: 200px;
      height: 200px;
      background: yellow;
}

#texto {
    font-size: 16px;
    width: 180px;
    float: left;
    margin-left: 10px;
    margin-top: 95px;
}

          Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore

Notem que o texto está próximo ao inferior da div, e se eu adicionar mais texto ali, ele irá sair do espaço. Por isso que eu gostaria de saber uma solução (Não overflow hidden) que alocasse o texto corretamente ali, independente do tamanho, pois isso seria um título vindo do banco de dados, e assim seria uma string de length variável.
Obs: Mantendo o margin-top o máximo possível, deixando tipo uns 10px somente de distância do inferior.
Obrigado a todos e bom dia!
Comment: Não. O margin-top é para estar ali mesmo, mas se caso precise expandir o texto, que seja para cima, pois para baixo irá sumir ou perder a formatação.
Comment: Conforme o tamanho  do texto  você precisa modificar o margin-top pra caber na div é isso?
Comment: Sim, era isso, mas o Gumball já respondeu. Obrigado, Marconi.
Answer: Tem que ter uma combinação de position:relative com position:absolute.
Deixei uma margem inferior de 5px. Daí é a gosto seu.

#content {
  width: 200px;
  height: 200px;
  background: yellow;
  position: relative;
}

#texto {
  font-size: 16px;
  width: 180px;
  display: block;
  margin: auto;
  bottom: 5px;
  left: 0;
  right: 0;
  position: absolute;
}

    Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore. Lorem ipsum dolor sit amet.


Calculate percentage of time

Question: I currently need to find the percentage of a song (for my program), I have tried doing it the normal way of (current position)/(total length of song), however since seconds go up to 60 and not 100 this does not work. How would I do this with seconds? Both the current position and length of song are in seconds.
To be more clear, how would I work out the percentage of the song, knowing that I am currently 122.277seconds the way through a song that is total of 177320seconds.
Thanks
Answer: You can do this in the usual way, as long as both current position and total length of the song are in the same units (e.g. seconds or minutes or hours, etc). In your example it would be
$$
\frac{122.277}{177320} \approx 0.0689 \%
$$
(You must have a really long song, $177320$ seconds is about 50 hours, you sure you got the right units?)
Comment: My program must be giving me the wrong information then, hmm. That may explain why I am getting the wrong results. The song is only ~3mins
Comment: @guest123 could you be getting the result in *milliseconds*, i.e. song is $$177320 \textrm{msec} = 177.320 \textrm{sec} = 2 \textrm{min} 57.32 \textrm{sec}?$$ The answer above then is rescaled by 1000 to become $$\frac{122.277}{177.32} = 68.9\%$$
Comment: Think it is, thanks for that. Some reason it looks as if I am getting the current position in seconds and the total length in milliseconds. Strange, the API only documented that it was in seconds, what ever your suggestion works with the songs I tried. Thanks for that tip! Glad to know it wasn't my maths and that it was a program error instead.
Comment: @guest123 familiar problem. Now you have to watch what happens when they upgrade the library you are using fixing the bug -- your estimates would be off by a factor of 1000 :-)
Comment: Yep, the fun of documentations being wrong. Also this is using the library inside the Spotify application which updates quite frequently. What fun this will be when I find out something goes wrong!
Answer: Like gt6989b said, if you're just working in seconds there is no problem and you can just use the convensional way. This is the easy way.
But let's say you are currently at $1'20"$ from a $3'35"$ song you can either calculate it back to seconds or calculate it in minutes, but recalibrate the second part to an accaptable comma value.
$$20 seconds = (20 \times \frac{5}{3})minutes = 0.33 minutes$$
so $1'20" = 1.33$ minutes
$$35 seconds = (35 \times \frac{5}{3})minutes = 0.58 minutes$$
so $3'35" = 3.58$ minutes
The percentage calculated with minutes $=\frac{1.33}{3.58}=0.371$

Calculate percentage of time


Brezis' exercise 4.19

Question: I'm having trouble with problem 4.19 of Brezis' book in functional analysis (Functional Analysis, Sobolev Spaces and Partial Differential Equations). It asks for a sequence $f_n\geq 0$ in $L^1(0,1)$ and a function $f\in L^1(0,1)$ such that

$f_n \to f$ weakly $\sigma(L^1,L^\infty)$;
$||f_n||_1 \to ||f||_1$;
$||f_n-f||_1 \not \to 0$.

What sequence $f_n$ work? I know that i cannot choose $f=0$ because statement 2 would contradicts 3.
Answer: Consider $r_n \colon \mathbb{R} \to \mathbb{R}$ given by $r_0(x) = (-1)^{\lfloor x\rfloor}$ and $r_n(x) = r_0(2^n\cdot x)$. Let $g_n = r_n\lvert_{(0,1)}$. Then show that $g_n \to 0$ weakly, and use these functions to construct the desired sequence $(f_n)$.

Accepting that $g_n \to 0$ weakly for the moment, one sees that for every $f\in L^1(0,1)$ with $f(x) \geqslant 1$ for all $x$, by setting $f_n = f + g_n$ we have a sequence $f_n \geqslant 0$ in $L^1(0,1)$ with $f_n \to f$ weakly, and $\lVert f_n - f\rVert_1 = \lVert g_n\rVert_1 = 1$ for all $n$. For $n \geqslant 1$, we also have
$$\lVert f_n\rVert_1 = \int_0^1 f_n(x)\,dx = \int_0^1 f(x)\,dx + \int_0^1 g_n(x)\,dx = \int_0^1 f(x)\,dx = \lVert f\rVert_1.$$
So it remains to see that $g_n \to 0$ weakly. First we show that
$$\int_0^1 g_n(x)h(x)\,dx \to 0\tag{1}$$
for all $h \in C([0,1])$. Since $[0,1]$ is compact, every $h\in C([0,1])$ is uniformly continuous. Given $\varepsilon > 0$, we can therefore find a $\delta > 0$ such that $\lvert x-y\rvert \leqslant \delta \implies \lvert h(x) - h(y)\rvert \leqslant \varepsilon$. Then let $n \geqslant 1$ such that $2^{-n} \leqslant \delta$. For $0 < k < 2^n$ we have
\begin{align}
\biggl\lvert\int_{2^{-n}(k-1)}^{2^{-n}(k+1)} g_n(x)h(x)\,dx\bigr\rvert &= \biggl\lvert\int_{2^{-n}(k-1)}^{2^{-n}(k+1)}g_n(x)\bigl(h(x) - h(2^{-n}k)\bigr)\,dx\bigr\rvert\\
&\leqslant \int_{2^{-n}(k-1)}^{2^{-n}(k+1)} \lvert g_n(x)\rvert\cdot\lvert h(x) - h(2^{-n}k)\rvert\,dx\\
&\leqslant 2^{1-n}\varepsilon.
\end{align}
Summing over all odd $k$ between $0$ and $2^n$, we obtain
$$\biggl\lvert \int_0^1 g_n(x)h(x)\,dx\biggr\rvert \leqslant \varepsilon.$$
Thus $(1)$ is proved.
Next we take an arbitrary $h \in L^\infty(0,1)$. Given $\varepsilon > 0$, by Luzin's theorem there is a $h_\varepsilon \in C([0,1])$ with $\lVert h_\varepsilon\rVert_\infty \leqslant \lVert h\rVert_\infty$ such that $\lambda(\{ x : h_\varepsilon(x) \neq h(x)\}) < \varepsilon$. Then we have
\begin{align}
\biggl\lvert \int_0^1 g_n(x)h(x)\,dx\biggr\rvert
&\leqslant \biggl\lvert \int_0^1 g_n(x)h_\varepsilon(x)\,dx\biggr\rvert + \biggl\lvert \int_0^1 g_n(x)\bigl(h(x) - h_\varepsilon(x)\bigr)\,dx\biggr\rvert\\
&\leqslant \biggl\lvert \int_0^1 g_n(x)h_\varepsilon(x)\,dx\biggr\rvert + \biggl\lvert \int_{\{ x : h_\varepsilon(x) \neq h(x)\}} g_n(x)\bigl(h(x) - h_\varepsilon(x)\bigr)\,dx\biggr\rvert\\
&\leqslant \biggl\lvert \int_0^1 g_n(x)h_\varepsilon(x)\,dx\biggr\rvert + \int_{\{ x : h_\varepsilon(x) \neq h(x)\}}\lvert h(x) - h_\varepsilon(x)\rvert\,dx\\
&\leqslant \biggl\lvert \int_0^1 g_n(x)h_\varepsilon(x)\,dx\biggr\rvert + 2\lVert h\rVert_\infty \varepsilon,
\end{align}
and hence
$$\limsup_{n\to\infty}\: \biggl\lvert \int_0^1 g_n(x)h(x)\,dx\biggr\rvert \leqslant 2\lVert h\rVert_\infty \varepsilon.$$
Since that holds for all $\varepsilon > 0$, we conclude
$$\lim_{n\to\infty} \int_0^1 g_n(x) h(x)\,dx = 0,$$
as desired.
Comment: I suppose that's a typo; $g_n \to 0$ weakly, not $f_n$. Can you see that $\int_0^1 g_n(x)h(x)\,dx \to 0$ for every $h\in C([0,1])$?
Comment: Now, if the space of continuous functions were dense in $L^\infty$, it would be trivial to conclude. Since it isn't, we need a little more machinery. I suggest Luzin's theorem.
Comment: Thanks! I can see that if i take $f_n(x) = g_n(x) +1$ and $f(x)=1$ then $||f_n||_1 = 1  = ||f||_1 and ||f_n - f||_1 = 1$. So it satisfies 2) and 3). Intuitively i believe $f_n \to 0 $ weakly but i don't know how to prove it.
Comment: I have to take $h \in L^\infty(0,1)$ and show that $\int_{0}^1 f_n h dx \to \int h dx$.
At first, we can suppose $h\geq 0$.

Since for each $\epsilon>0$ there is a simple function $\phi\geq 0$ such that $\phi(x)\leq h(x)\leq \phi(x)+\epsilon$, we can suppose $h = \chi_E$ for some measurable subset $E\subset \mathbb (0,1)$.

So i must show that $m(E) = \lim \int_E f_n dx$, but i don't know how.
Comment: Yes, for continuous functions i agree that it's true.
Comment: Now i see it. Thank you very much!

Brezis' exercise 4.19


dropdownlist not selecting the correct index

Question: I have a database bound dropdown list that gets its values from a DB.
When I call the ddl.SelectedItem either .Text or .Value the index is incorrect.
Let's say the values in the DB tables are like so:
Column1 | Column2

Dublin1 | Value1
Dublin2 | Value1
Dublin3 | Value1
London1 | Value2
London2 | Value2
London3 | Value2

SQL select query:
SELECT [Column1],[Column2] FROM [Table] ORDER BY [Column1]

The DDL:
<asp:DropDownList runat="server" ID="ddl"
 DataSourceID="SQLDataSource" DataTextField="Column1"
 DataValueField="Column2"></asp:DropDownList>

Binding on ASPX only:
<asp:SqlDataSource ID="SQLDataSource" runat="server"
      ConnectionString="<%$ConnectionStrings:DatabaseConnectionString %>"
      SelectCommand="SELECT [Column1],[Column2],FROM [Table] ORDER BY [Column1]">
</asp:SqlDataSource>

So when I get the Selected Item from the dropwdownlist whether I pick Dublin2 or Dublin3, it always comes back with Dublin1, same with London values.
The ddl populates correctly for both item.text and item.value.
Is there something I need to set regarding the bounding?
Comment: Could you add the server side code with the `ddl.SelectedItem`?
Comment: Are the TextItems and ValueItems unique?
Comment: well, this seems pretty odd, we can help you if you provide more server side code :)
Comment: `SELECT [Column1],[Column2] FROM [Table] ORDER BY [Column1]` Is this gives correct value or you get duplicate?
Comment: U have to clear the selected items
Comment: Its like dddl.items.clear();     Try this........
Comment: Updated code above. I am not binding in code behind at all currently. The binding is from the aspx page.
Comment: Where do I clear them?
Comment: My Column2 values are not all unique. Column1 values are. Apparently that can cause an issue: http://forums.asp.net/t/1218292.aspx/1
Answer: Are you checking for IsPostBack inside Page_Load .
if (!IsPostBack)
{
    BindDropDownListddl();
}

Also set AutoPostBack to true for your drop down list.
<asp:DropDownList runat="server" ID="ddl"
 DataSourceID="SQLDataSource" DataTextField="Column1"
 DataValueField="Column2" AutoPostBack="true" ></asp:DropDownList>

Answer: I think that the values in the dropdown must be unique and the Column2 has repeated values. You should modify the databind to use Column1 on both text and value:
<asp:DropDownList runat="server" ID="ddl"
 DataSourceID="SQLDataSource" DataTextField="Column1"
 DataValueField="Column1"></asp:DropDownList>

Then on code behind access you need a copy of a table and access it like this to get the value:
Dictionary<string, string> table = //Get the table here with Column1 as keys
table[ddl.SelectedItem.Value]


dblog not working, page shows a 500 Internal server error

Question: My problem starts in a contact form with an upload box, it does everything right and sends the email, except that, on upload it shows:

Warning: strtr() [function.strtr]: The second argument is not an array in syslog_watchdog() (line 105 of syslog/syslog.module)

So I found this post to resolve my problem above, but it just showed me another problem, a problem with dblog, the page shows me a 500 error, I can't access it.
I couldn't find any help to solve this matter so if anyone knows some way to figure out what is causing this, I would appreciate it.
Comment: Welcome Nuno. Please elaborate in what you changed code-wise or what changes you did more specifically, instead of posting an article that people need to read in addition to your question.
Comment: Hello, i used a theme named Surreal, in terms of code i didn't change nothing but CSS, so i can't elaborate unfortunately.
Answer: This sounds like the incorrect watchdog data was saved to the database. Truncate the 'watchdog' table that contains your dblog messages in your database and you should be good.


Find all natural numbers $n$ such that $3^n+81$ is a perfect square.

Question: Find all natural numbers $n$ such that $3^n+81$ is a perfect square.
My solution:
$3^n=a^2-81 \Rightarrow 3^n=(a-9)(a+9)$
$gcd(a-9,a+9) \mid 18$
because $a+9>a-9$ then $a-9$ can be $1,3,9$that only $a=9$ is the answer so we have only one solution.I just wanted to verify my answer is it right?
Comment: You state that $a-9$ can be $1$, $3$, or $9$.  These options lead to $a=10$, $a=12$, and $a=18$.  None of these is $a=9$.  Of these options, only $a=18$ works (not $a=9$).  Note that $9$ and $27$ are the *only* powers of $3$ which differ by $18$ (which is needed for the product to work).
Comment: What about $n=5$?
Comment: @HagenvonEitzen for $a=9$ we get $n=5$.
Comment: @MichaelBurr but then we can go up and have more solutions for $a-9$.I mean answers like $27,81,/dots$
Comment: we can only get perfect square if 3 is raised to the power $4k+1$ or $4k+2$ we get $k=1$ for $4k+1$ now check for $4k+2$ if it does not give any solution then $n=5$ is the only one. here $k$ is whole number.
Answer: You get $3^n = (a-9)(a+9)$ in the question.  But the only factors of $3^n$ are other powers of $3$, so you need $a-9$ and $a+9$ to both be powers of $3$. The only powers of three differing by $18$ are $9$ and $27$.  So $a = 18$, and the only solution is $18^2  = 3^5 + 81$.


Cannot upload file to Spring Boot REST using Axios and FormData

Question: I try to upload file from page using axios and can't get it on my controller.
In fromt-end I use Vue.js with axios, and at the back end Spring MVC Controller. It seems that my controller can`t convert FormData() to MultipartFile in spring. I read a lot of questions but have no answer. here is my code:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

Uploading files with Vue.js

Single file uploading

                        <input type="file" ref="file" id="customFile"
                               v-on:change="handleFileUpload($event)"
                               class="custom-file-input"
                               enctype="multipart/form-data">
                        {{chosenFile}}

                <button v-on:click="submitFile()" class="btn btn-primary">Submit</button>

Multiple files uploading

and controller file:
package com.yurets_y.webdevelopment_uploading_file_with_vue.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@CrossOrigin("*")
@Controller
public class UploadController {

    @Value("${upload.path}")
    private String uploadPath;

    @ResponseBody
    @PostMapping(value="/single-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> uploadSingle(
            @RequestParam(name="file", required = false) MultipartFile file
    ) {
        System.out.println("uploaded");
        System.out.println(file);

        return ResponseEntity.ok().build();

    }

}

I will be very grateful for the advice.
P.S.
when I use  @RequestParam(name="file", required=true) MultipartFile file I get error POST http://localhost:8080/single-file 400 (Bad Request), It looks like spring cannot get MultipartFile file from FormData. At back end I don't get any errors, only MultipartFile file = null
Answer: After two days, that I spent to solve my promlem I fount a couple of working projects, compare all files and found, that my problem was in dependencies,
I used dependency:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

And when I change dependency:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

Now it's working exactly how I need.


How can I get remaining args after pulling out parsed items using getopts?

Question: I want to parse some arguments to a bash script using getopts but want to be able to access the remaining args that are not included in the option list. So for example, if I have a call:
% script -a -b param -c param -d other arguments here

I would have:
while getopts "ab:c:d" opt ; do
.
done

What is the easiest way to get "other arguments here", which should be unprocessed by getopts?
Answer: you need to shift when you parse an arg, or put
shift $((OPTIND -1)) after you have finished parsing, then deal in the usual way e.g.
while getopts "ab:c:d" opt ; do
.
done
shift $(expr $OPTIND - 1 )

while test $# -gt 0; do
  echo $1
  shift
done

Comment: It's worth explaining, that $OPTIND is the index of the next option to be considered, after each getopts is run.  Hence is $* contains 3 parameters, following the first valid call it's 2, and the second it's 3.  Should the a call be invalid, it'll drop out with the earlier value.  So if parameter 1 isn't valid, OPTIND will be 1 (hence the above example will `shift $(expr 1 - 1)` which is safe.
Answer: At the end of the parsing, once you have shifted the variable $@ contains the end of the line :
while getopts "ab:c:d" opt ; do
.
done
shift $((OPTIND-1))
OTHERARGS=$@


Máscara para hora com iMask

Question: Estou usando esse plugin Jquery para formatar máscaras mas não estou conseguindo fazer o mesmo funcionar, mesmo seguindo religiosamente o exemplo existente, tentei isso, alterando um formato existente para o meu caso:

$(document).ready(function() {
    $('#dHora').iMask({
          type      : 'fixed'
        , mask      : '00:00'
        , stripMask : true
    })
});

Mas a máscara não é aplicada.
Comment: Tente alterar para **99:99** (0 não é coringa para nada)
Comment: Olá @Luis Henrique, tinha alterado tanto que nem tinha percebido essa gritante falha minha, obrigado pela ajuda.
Comment: @LuizHenrique formule uma resposta :) mesmo que simples pode ser útil, eu acho
Comment: Já viste esta pergunta -> http://pt.stackoverflow.com/q/71094/129 ?
Comment: Mas porque não usa o time do html5?
Answer: Basta alterar os coringas definidos para a máscara:
00:00

Deve ser substituido por:
99:99

Quando você usou 0 ele não é substituido por nada por não se tratar de um coringa para o plugin que roda por trás.
Os coringas disponíveis para serem usados como máscara conforme documentação, são:

9 = Numeric
a = Alpha
x = AlphaNumeric

Máscara para hora com iMask


How to embed views in a particular custom block template

Question: I have created a views block in D8 and thinking to embed it within a particular custom block template I created to override (e.g block--myblock.html.twig), I wonder how to do this ?
Answer: Ok, I have found a way to do so from another post, tested and it works ! So basically..
1) Create a new variable in mytheme.theme file located in your default theme folder.
<code>function mytheme_preprocess_block(&$variables) {

  $variables['view1'] = views_embed_view('view_name', 'block_news');

}
</code>
'block_news' is your views block's machine name actually.
2) And then use this twig in your block template.
<code> {{ view1 }}
</code>


Slow response when querying unicode (non ascii) characters in sybase

Question: Query 1: Select * from table where fieldname = 'abc'
Query 2: Select * from table where fieldname = 'XY�'

My query 1 executes in 150mS
My query 2 executes  in 5000mS

Both return zero results (abc and XY� do not exist in database).
Once I run query 2 and then rerun my query 1, query 1 starts taking longer time if it is run in same session (around 2000ms instead of earlier 150ms)
My fieldname is indexed (non-clustered index).
I am using Adaptive Server Enterprise/12.5.4
I tried to do a show plan for both. Both show same results.
My worries:

Why queries with non ascii characters should take more time ? Is that something to do with indexes?
Running query 2 should not impact my query 1 response time. Any ways to fix this?

Thanks
Comment: What does the table look like please, with indexes? And how does `Select fieldname  from table where fieldname = 'whatever'` perform?
Answer: I found issue to my problem. TIBCO EMS does some changes to unicode chars(non ascii) which causes query plan in sybase to change to some non optimized query plan. When using prepared statements in Java query plan is cached ,as a result all future queries become slow.


How do I simplify(expand) this Boolean expression?

Question: Expression - (A OR B OR C OR D) AND (!B AND !D)
I know that with distributive property, it holds that (a OR b) AND (c OR d) = (a AND c) OR (a AND d) OR (b AND c) or (b AND d) but I'm not sure how it will work if the second group has an AND
Steps in the answer would help.
Comment: Yes by `!B`, I mean `NOT B`. I just went through De morgan's law. So
`(A OR B OR C OR D) AND (NOT B AND NOT D) = (A OR B OR C OR D) AND NOT (B OR D)`?
Answer: OK, so you have:
$(A \lor B \lor C \lor D) \land (\neg B \land \neg D)$
Now, notice that this is a conjunction (an 'AND' statement) whose right conjunct is a conjunction itself. In a case like that, you can actually drop the parentheses, and thus get:
$(A \lor B \lor C \lor D) \land \neg B \land \neg D$
This is what is called a generalized conjunction; a conjunction that can conjunct together any number of terms. In this case, you have $3$ terms
And by the way, note that the left conjunct is already a generalized disjunction (of $4$ terms), so this is really nothing unusual.
Now, any logical equivalence principle you would normally apply to a 'normal' conjunction with $2$ conjuncts, you can still apply to any $2$ conjuncts of a generalized conjunction.
For example, one very useful simplification principle is:
Reduction
$\neg P \land (P \lor Q) \Leftrightarrow \neg P \land Q$
To understand this: note that $\neg P$ is definitely true ... so how can $P \lor Q$ be true as well? Clearly it must be that $Q$ is true. So, the left side implies the right side, and going from right to left is trivial, since $Q$ implies $P \lor Q$.  But, going from left to right, which is how we typically use Reduction, because is simplifies things, we say that in the presence of $\neg P$, the term $P \lor Q$ 'reduces' to just $Q$
OK, so we can apply Reduction to your statement twice:  The $\neg B$ will reduce the $A \lor B \lor C \lor D$ term to $A \lor C \lor D$, and the $\neg D$ term will further reduce that to $A \lor C$. Hence, we end up with:
$(A\lor C) \land \neg B \land \neg D$
If you want this more formally, you can state the Association principle, which states that $P \land (Q \land R) \Leftrightarrow (P \land Q) \land R$, and thus makes clear that you could write $P \land Q \land R$ without any ambiguity, as a justification for dropping the parentheses at the start. As such, it formally looks like:
$$(A \lor B \lor C \lor D) \land (\neg B \land \neg D)$$
$$\overset{\text{Association}}{\Leftrightarrow}$$
$$(A \lor B \lor C \lor D) \land \neg B \land \neg D$$
$$\overset{\text{Reduction x 2}}{\Leftrightarrow}$$
$$(A\lor C) \land \neg B \land \neg D$$


Configuring Vertx WebClient SSL context

Question: I am using some library for security functions, it allows me to create custom java.security.Provider, KeyManagerFactory, TrustManagerFactory with a specific TLS cipher suits, algorithms, keys and trust storage formats. Normally Netty allows me to configure sslContext like below, to kick things working. Is there a way to configure Netty used by Vertx library layer?
val nettyProvider = SslProvider.JDK
val (keyManagerFactory, trustManagerFactory) = loadKeyCertStuff()
val customJcaProvider: java.security.Provider = CustomTlsProvider()

return SslContextBuilder.forClient()
    .sslProvider(nettyProvider)
    .keyManager(keyManagerFactory.keyManagers[0])
    .trustManager(trustManagerFactory.trustManagers[0])
    .sslContextProvider(customJcaProvider)
    .ciphers(listOf("TLS_CIPHER_2012"))
    .build()

Looks like this configuration option is not taken into account in the API of Vertx library, it allows to set custom KeyManagerFactory and  TrustManagerFactory, but no way to set java.security.Provider.
Answer: It is possible since Vert.x 4.3.4, PR #4468
In a few words, you need to create an SslContextFactory. Here's what it looks like for TCP client:
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(
  null,
  tmFactory.getTrustManagers(),
  null
);

client = vertx.createNetClient(new NetClientOptions().setSsl(true)
  .setSslEngineOptions(new JdkSSLEngineOptions() {
    @Override
    public SslContextFactory sslContextFactory() {
      return new SslContextFactory() {
        @Override
        public SslContext create() {
          return new JdkSslContext(
            sslContext,
            true,
            null,
            IdentityCipherSuiteFilter.INSTANCE,
            ApplicationProtocolConfig.DISABLED,
            io.netty.handler.ssl.ClientAuth.NONE,
            null,
            false);
        }
      };
    }
  }));

Configuring Vertx WebClient SSL context


premake5 how to set outdir based on platform + configuration?

Question: I'd like to set the outdir/targetdir for each combination of platform + configuration.
function SetLibTargetDir(platforms, configs)
for i2,c in ipairs(configs) do
        for i,p in ipairs(platforms) do
            filter ("configurations:" .. c, "platforms:" .. p)
                targetdir("bin/" .. p .. "/" .. c)
                libdirs ("bin/" .. p .. "/" .. c)
                libdirs ("bin_prebuilt/" .. p .. "/" .. c)--manually generated libs/dlls that premake5 can't handle

    end
end
end

SetLibTargetDir({"Win32", "Win64"}, {"Debug", "Release", "Final"})

I tried using this code, while it gets the config right(debug/release/final). It places everything in Win64, so the 32 bit files & 64 files all end up in the same directory.
What am I doing wrong here? I'd like each combination of platform + configuration to have its own output dir and library paths.
Thanks
Answer: Stumbled across the answer:
https://github.com/premake/premake-core/wiki/Tokens
"%{cfg.buildcfg}" get the config
"%{cfg.platform}" gets the platform
So this code works:
targetdir("bin/" .. "%{cfg.platform}" .. "/" .. "%{cfg.buildcfg}")
libdirs("bin/" .. "%{cfg.platform}" .. "/" .. "%{cfg.buildcfg}")
libdirs("bin_prebuilt/" .. "%{cfg.platform}" .. "/" .. "%{cfg.buildcfg}")


Why is the Mean Square Between (MSB) used in 1-way ANOVA instead of total variance?

Question: I'm having a hard time parsing the logic behind the formulas in the 1-way ANOVA. I'll first establish what I understand so far which will lead into my question.

The objective of a 1-way ANOVA is to test the null hypothesis that the population means for all conditions are the same:
$$H_0: \mu_1 = \mu_2 = ... = \mu_k$$
In other words, we are interested in seeing if all the samples are coming from the same population with mean, $\mu$, and variance, $\sigma^2$.
One of the key assumptions of the 1-way ANOVA is the "homogeneity of variance" which states that the variance within each of the populations ($\sigma^2$) is the same. Thus, we can use the pooled variance of all the samples, $S_p$, as an estimator for $\sigma^2$. I believe this pooled variance is more commonly known as the Mean Square Within (MSW):
$$S_p = MSW = \frac{\sum_{j=1}^{k}\sum_{i = 1}^{n_j}(Y_{ij}-\bar{Y_j})^2}{N - k} = \frac{\sum_{j=1}^{k}(n_j - 1)s_j}{N-k} = \frac{SSW}{N-k}$$

Ok great, now we have an estimate for the population variance. It would then make sense logically to see how the sample means themselves vary relative to the population variance. If the sample means are all close to each other ("closeness" is of course defined by the estimated population variance), then the null hypothesis is probably true.
But how do we calculate this variance between the sample means? Well here are 2 potential ways:
1.) The "grand variance", S: $$S = \frac{\sum_{j=1}^{k}\sum_{i = 1}^{n_j}(Y_{ij}-\bar{Y})^2}{N - 1} = \frac{TSS}{N-1}$$
where $TSS$ is the Total Sum of Squares.
2.) Using the Mean Square Between (MSB): $$MSB = \frac{\sum_{j=1}^{k}n_j(\bar{Y_j} - \bar{Y})^2}{k - 1} = \frac{SSB}{k-1}$$
where $SSB$ is the Sum of Squares Between.

My question: How come the MSB is the preferred way of calculating this "variance between sample means"? Is it an estimator for a certain statistic? Is it because of the useful relationship:
$$SST = SSW + SSB$$
Comment: Three things to consider: (1) SSB + SSW = SST. So, if you used MSB and MST to make the variance ratio, you would be comparing the part with the whole, not the two _independent_ estimates of variance with each other. (2) Whether nor not $H_0$ is true, MSW is an unbiased estimator of the common variance $\sigma^2.$ Only if $H_0$ is true, is MSB an unbiased estimator or $\sigma^2,$ otherwise it tends to be too large.
(3) MSB/MSW has an F-distribution, and MSB/MST does not.
Comment: @BruceET If the null hypothesis is true, are MSB, MSW, and MST all unbiased estimators of $\sigma^2$? And if not, only MSW is?
Comment: Right. However, MST is not usually used to estimate $\sigma^2.$
Answer: Suppose we have a one-way ANOVA with three levels of the
factor, five replications per cell, and common group
variance $\sigma^2 = 3^2 = 9.$
To begin, suppose $H_0: \mu_1 = \mu_2 = \mu_3 = 55.$
Then each of the group sample means $\bar X_i,$ for $i = 1,2,3,$
has $Var(\bar X_i) = \sigma^2/n = 9/5,$ so the variance of the three group sample means multiplied by the number $5$ of replications is MSB. Also, the mean of the sample variances (in a balanced design) is MSW.
Consider the following ANOVA, in which data are simulated
so that $H_0$ is true. I think the formulas in your question are correct, but it may be more intuitive to look at
computations in a simple ANOVA: [Using R.]
set.seed(310)
x1 = rnorm(5, 55, 3)
x2 = rnorm(5, 55, 3)
x3 = rnorm(5, 55, 3)
x = c(x1, x2, x3)
g = as.factor(rep(1:3, each=5))
aov.out = anova(lm(x ~ g));  aov.out

Analysis of Variance Table

Response: x
          Df  Sum Sq Mean Sq F value Pr(>F)
g          2  34.289 17.1445  1.8128 0.2052
Residuals 12 113.492  9.4577

MSB and MSW can be 'captured' from the table as follows:
msb = aov.out[1,3];  msb
[1] 17.14446
msw = aov.out[2,3];  msw
[1] 9.45767

As stated above MSW is the average of the three group
variances:
mean(c(var(x1), var(x2), var(x3)))
[1] 9.45767

Also, MSB is the number of replications times the variance
of the three group means.
5*var(c(mean(x1), mean(x2), mean(x3)))
[1] 17.14446

Both MSB and MSW are estimates of $\sigma^2 = 9.$
Of course, with so little data, the estimates are not
very good. However, it is not difficult to 'wrap' this
one example in a 'for' loop and take averages of many
similar ANOVAs to show better estimates. [This method
of simulation is not fast, elegant, or efficient, but
it should be easy to follow.]
set.seed(310)
m = 10^5;  msb = msw = numeric(m)
for(i in 1:m) {
 x1 = rnorm(5, 55, 3)
 x2 = rnorm(5, 55, 3)
 x3 = rnorm(5, 55, 3)
 x = c(x1, x2, x3)
 g = as.factor(rep(1:3, each=5))
 aov.out = anova(lm(x ~ g));  aov.out
 msb[i] = aov.out[1,3];  msb
 msw[i] = aov.out[2,3];  msw
 }
mean(msb);  mean(msw)
[1] 9.058666 # aprx 9
[1] 8.989481 # aprx 9

Now look at a similar ANOVA in which $H_0$ is false
because $\mu_1 = 50, \mu_2 = 55, \mu_3 = 60.$
set.seed(2022)
x1 = rnorm(5, 50, 3)  # different
x2 = rnorm(5, 55, 3)  #  group
x3 = rnorm(5, 60, 3)  #   population means
x = c(x1, x2, x3)
g = as.factor(rep(1:3, each=5))
aov.out = anova(lm(x ~ g));  aov.out
    Analysis of Variance Table

Response: x
           Df Sum Sq Mean Sq F value    Pr(>F)
 g          2 343.56 171.780  16.065 0.0004042 ***
 Residuals 12 128.31  10.692
 ---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

msb = aov.out[1,3];  msb
[1] 171.7795
msw = aov.out[2,3];  msw
[1] 10.69249

Now, MSB is much larger. Its expected value is $\sigma^2 + n\theta = 134,$ where $\theta = \frac{1}{3-1}\sum_i (\mu_i - \bar\mu)^2,$ and $\bar\mu = \frac 13 \sum_i \mu_i.$
9 + 5*var(c(50,55,60))
[1] 134

Again here, we have too little data for good estimates of MSB and MSW,
but we can come close, using a simulation.
set.seed(2022)
m = 10^5;  msb = msw = numeric(m)
for(i in 1:m) {
 x1 = rnorm(5, 50, 3)
 x2 = rnorm(5, 55, 3)
 x3 = rnorm(5, 60, 3)
 x = c(x1, x2, x3)
 g = as.factor(rep(1:3, each=5))
 aov.out = anova(lm(x ~ g))
 msb[i] = aov.out[1,3]
 msw[i] = aov.out[2,3]
 }
mean(msb);  mean(msw)
[1] 134.2149
[1] 8.992701


Is this considered a Random sample?

Question: The Department has an online system whereby students can voluntary sign up to take part in lab studies to earn credits towards their coursework. Students have to check this online system frequently to see if they are interested in participating in any of the listed studies. Also they visit that online system to register to participate in the studies if they need additional credit.
As a researcher, I when I log into that online system database, I contact all the students  who have expressed interest to invite them to my lab. Out of 400 students, only 50 students show up for the study.
Is this regarded as a random sample?
Thanks
Answer: This is opportunity or convenience sampling and is not random.
You might see wikipedia on sampling

Is this considered a Random sample?


Deserialize multiple JSON records in C#

Question: I have the following string of Json records:
{
   "records":[
      {
         "PK":"1_1_8",
         "ID":"8",
         "DeviceID":"1",
         "RootID":"1",
         "CustName":"test1",
         "CustSurname":"test2",
         "Address":"Nisou 1",
         "City":"",
         "ZipCode":"",
         "PhoneNumber":"45646",
         "HomePhoneNumber":"",
         "Email":"",
         "Notes":"",
         "Owner":"1",
         "LanguageID":"1",
         "LanguagePK":"",
         "DeletedFlag":"false",
         "created":"2017-10-25 10:15:00",
         "modified":"2017-10-25 09:35:43"
      },
      {
         "PK":"1_1_33",
         "ID":"33",
         "DeviceID":"1",
         "RootID":"1",
         "CustName":"",
         "CustSurname":"",
         "Address":"",
         "City":"",
         "ZipCode":"",
         "PhoneNumber":"",
         "HomePhoneNumber":"",
         "Email":"",
         "Notes":"",
         "Owner":null,
         "LanguageID":"0",
         "LanguagePK":"",
         "DeletedFlag":"true",
         "created":"2017-10-25 10:13:54",
         "modified":"2017-10-25 10:13:54"
      },
      {
         "PK":"1_1_16",
         "ID":"16",
         "DeviceID":"1",
         "RootID":"1",
         "CustName":"Theodosis",
         "CustSurname":"",
         "Address":"Dali",
         "City":"Nicosia",
         "ZipCode":"2540",
         "PhoneNumber":"45645",
         "HomePhoneNumber":"99123456",
         "Email":"email@example.com",
         "Notes":"",
         "Owner":"",
         "LanguageID":"1",
         "LanguagePK":"",
         "DeletedFlag":"false",
         "created":"2017-10-25 09:36:22",
         "modified":"2017-10-25 09:36:22"
      }
   ]
}

I am using Xamarin PCL in C# trying to parse this string into a list of objects.
I have a Customer class:
public class Customer
{
    [PrimaryKey]
    public string PK { get; set; }
    public int DeviceID { get; set; }
    public int ID { get; set; }

    public string RootID{ get; set; }

    public string CustName { get; set; }
    public string CustSurname { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string ZipCode { get; set; }
    public string PhoneNumber { get; set; }
    public string HomePhoneNumber { get; set; }
    public string Email { get; set; }
    public string Notes { get; set; }
    public bool Owner { get; set; }

    public int LanguageID { get; set; }
    public string LanguagePK { get; set; }

    public bool DeletedFlag { get; set; }
    public DateTime created { get; set; }
    public DateTime modified { get; set; }
}

I also tried out having a container class with a list of Customer objects.
public class DataContainer
{
    public List<Customer> customers { get; set; }
}

I have seen quite a few of examples online on how to parse this into a list or any workable type but nothing seems to be working for me.
I have tried the following (JsonResults holds the string of Json records):
var observation = JsonConvert.DeserializeObject<DataContainer>(JsonResults);

From other posts, I am not able to access JavaScriptSerializer class from my code, perhaps because of the Xamarin PCL Framework I am using.
Any ideas would be very welcome, as I said I do not mind the format I parse the string into, as long as it's workable.
Thank you.
Comment: Yous Json starts with an object containing a property `records`. Have you tried renaming (or annotating) `customers` to `records`?
Comment: if you observe that your json is having key as "records" but in your DataContainer you have property as customers
Comment: Working example: https://dotnetfiddle.net/Widget/d8MJWT
Comment: `JavaScriptSerializer` is obsolete, Everyone uses Json.NET. If you have a problem, it doesn't mean that Json.NET is broken, it means the code is wrong. Post the *error message*. Most likely it complains that your string doesn't match your class (it doesn't). Json has a `records` property whil your class has a `customers` property
Comment: Also you need a JsonConverter for `Owner` or change it to a `int?`.
Answer: The JSON string you provided is a JSON object, which contains a single property called records. records property is a List<Customer>. You can not deserialize the given string directly into DataContainer class that you provided because the property names do not match.
In the Class that your provided it is called customers
public class DataContainer {
    public List<Customer> customers { get; set; } //records
}

Or please have a look at the attribute for a bit of advanced mapping
[JsonProperty]

JSON you provided is of the form:
{"records":[{Customer},{Customer},{Customer}]}

But Owner property is "1", null or "". Therefore I would suggest redefining Owner as int? (nullable)
Comment: It's *NOT* a list of objects. It's *one* object that contains a property named `records`, which has a list of other objects
Comment: The original answer was wrong. There's no list of objects
Comment: @PanagiotisKanavos, Yeah i read the comments and thanked you for the heads up :)
Answer: You would have to make the following changes to your code to make this work.
First and most importantly, you don't have a property customers, you have records, so either rename it
public class DataContainer {
    public List<Customer> records { get; set; }
}

or add a JsonProperty attribute
[JsonProperty(PropertyName = "records")]

Secondly, your Owner is a bool in C# and a nullable int (int?) in Json. So either change it in your C# class
public int?  Owner { get; set; }

or write a converter to do that (e.g. like here)
[JsonConverter(typeof(NullableIntToBooleanConverter))]
public bool Owner { get; set; }

Here is a working .NetFiddle
Comment: @CodeCaster Fair enough - find a duplicate and I'll chip in a close-vote.
Answer: Your string shows one object with a property named records that contains a list of other objects. Your code is trying to deserialize this into an object that doesn't have such a property.
Furthermore, the string contains objects with a property Owner that may be missing or have a numeric value. It's definitely not a bool.
You'll have to change Owner to :
public int?  Owner { get; set; }

To deserialize the string, you need an object with a records property:
public class DataContainer
{
    public Customer[] records { get; set; }
}

var data=JsonConvert.DeserializeObject<DataContainer>(json);
Debug.Assert(data.records.Length == 3);

Deserialize multiple JSON records in C#


How do I get rid of  tag in manually created block?

Question: I'm trying to remove a
 tag from a manually created block. This block only contains an image and nothing else. I have kpr() function outputting block variables but am not seeing where, or how the unnecessary
 tag is being generated.
Would the modification occur in theme_preprocess_block function? It seems it's not possible to get rid of within the block template file.
Another thing is that my tried was getting turning on themes info, clicking the element in hopes of finding some override function, but themer_info only shows me block info instead of some function info.
Any help would be greatly appreciated, thank you.
Answer: It's in fact because of the text input format. Going to admin/config/content/formats and removing the checkbox for
Convert line breaks into HTML (i.e.
 and
)

for the input format you're using should do the trick (re-save the block, of course). Also, if you use WYSIWYG editor, it could do some formatting for you and put the image in
 tag.


(WPF) How to keep GUI code from being a mess

Question: I have a GUI that is going to do a lot of disparate tasks. I currently have these separated in  a tab UI. The functionality that does all of the heavy lifting is split into separate classes, but what is left still looks like a mess. How do you organize the GUI functions in code so that everything is coherent? I'm working with WPF specifically, but general answers are also appreciated.
Answer: You should have a look at the Model-View-ViewModel design pattern, which is perfect for writing clean GUI code, clearly separated from business logic.
Answer: In addition to Thomas answer - MVVM if for GUI-non GUI separation. You should also separate GUI modules, and Prism will help in that.


Using grep to find uncommented literal integers

Question: What Patterns Do I Want to Match?
I want to find literal constant integers (e.g. 4, 8, 15), but not if they are within a comment (e.g. !4) or part of a variable name (e.g. myvar4).  The language of the file that I'm grepping is Fortran, so the comment symbol is "!".  Here is a file named "MWE.f":
j = j + 1      ! <-- match this
!j = j + 1     ! <-- do NOT match this
j1 = j1 + j2   ! <-- do NOT match this

What Have I Tried?
The command egrep ^[^\!]*[0-9] MWE.f matches the first line as intended, but it also matches the third line.  So, I tried adding word boundaries with egrep ^[^\!]*<[0-9]> MWE.f, but this command throws the following error:
-bash: [0-9]: No such file or directory

I assume this means that "<" is being interpreted as "pipe input from the file to the right", so I tried escaping the boundary characters with egrep ^[^\!]*\<[0-9]\> MWE.f.  Unfortunately, this command does not match any of the lines.
Thanks in advance for your help!
Appendix: Why Am I Doing This?
To avoid numerical problems in the code, I want to specify the type of each literal constant.  To keep it simple, I've used integers in this example.  Once I get integers figured out, I'm going to extend this to floating point types.  Then I should be able to find any single precision (4 byte) reals and change them to double precision (8 byte) reals.
Comment: Would you want to match the integer literal `1_a`, for example?
Comment: aside from the actual question, it is pointless to clutter the code by specifying  type for small integer literals.  You only need to worry about numbers > 2^31 , and products that could lead to such  large numbers.  If you do this wholesale take care with how you handle literals that appear as function arguments
Comment: @agentp  I was only using small numbers to keep the example simple.  In practice, I'm applying this to real numbers.  I was able to use a parameterized type and the IMPORT keyword to get it to work with function arguments.
Comment: @francescalus  No, I want to ignore anything with a trailing _a (or similar).  I'm assuming that anything like that has already been identified and changed to the appropriate type.
Answer: It looks to me like your issue is simply a lack of quotes around your pattern:
grep -E '^[^!]*\<[0-9]+\>' file

works fine for me, matching the first of your three lines. You can also remove the backslash escaping the !, as there is no longer any risk that it will be interpreted by the shell as a history expansion. I also added a + so that multi-digit constants are matched.
As a general rule, quote your string literals with single quotes to avoid them being interpreted by the shell.
By the way, grep -E is specified by POSIX and should be used instead of egrep, which is deprecated.


First-order Taylor expansion for a function of two variables

Question: If $u:\mathbb R^2\to \mathbb R$ and $u$ has continuous partial derivatives prove that
(a) $u(x+h,y+k)-u(x,y)=\dfrac{\partial u}{\partial x }h +\dfrac{\partial u}{\partial y }k +\epsilon_1$
(b) $v(x+h,y+k)-v(x,y)=\dfrac{\partial v}{\partial x }h +\dfrac{\partial v}{\partial y }k +\epsilon_2$
where $\dfrac{\epsilon_1}{h+ik}\to 0$ and  $\dfrac{\epsilon_2}{h+ik}\to 0$.
My try:
$u(x+h,y+k)-u(x,y)=\dfrac{u(x+h,y+k)-u(x+h,y)}{k}k+\dfrac{u(x+h,y)-u(x,y)}{h}h=\dfrac{\partial}{\partial y} u(x+h,y)k+\dfrac{\partial}{\partial x} u(x,y)h$
Similarly the other case will follow.
What I am having trouble is that how I should incorporate $\epsilon _1$ here and give the requisite conditions that $\dfrac{\epsilon_1}{h+ik}\to 0$.
Comment: did you want to write $k$ instead of the second $h$ on the r.h.s in (a), (b) ?
Comment: Your try is not accurate enough. There is no equality between the the middle term and the right term. You should revise the definition of the derivative of a function of two variables.
Comment: yes you got it right@uniquesolution
Comment: please do provide an answer which ever way you think is possible @uniquesolution
Comment: The appearance of (b) is bizarre. It's just the same formula with $v$ instead of $u$. What is the point of it?
Answer: You applied the mean value theorem incorrectly. It says
$$
 {u(x+h,y+k)-u(x+h,y)} =  u_y(x+h,y+\theta_1 k)k $$
and
$$
 {u(x+h,y)-u(x,y)}  =  u_x(x+\theta_2 h,y)h
$$
where $\theta_1,\theta_2\in (0,1)$. The continuity of partial derivatives yields
$$u_y(x+h,y+\theta_1 k) = u_y(x  ,y  ) + \eta_1(h,k)   $$
and
$$u_x(x+\theta_2 h ,y) = u_y(x  ,y  ) + \eta_2(h)   $$
where $\eta_1(h,k)$ and $\eta_2(h)$ tend to zero as $(h,k)\to (0,0)$. Hence, the quantity
$$\epsilon_1 = \eta_1(h,k) k+ \eta_2(h) h$$ has the desired property.


PostgreSQL UNIQUE for JOINed table

Question: Given the following example:
CREATE TABLE bom (
    id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name varchar(255) NOT NULL
);

CREATE TABLE bom_item (
    id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    bom_id_fk INT REFERENCES bom(id) NOT NULL,
    pcb_identifier varchar(50) NOT NULL
)

Is it possible to place an UNIQUE constraint on bom_item.pcb_identifier for a certain bom_id_fk besides making them both PRIMARY KEY?.
The logic behind that is, that a pcb_identifier may only exist once in a certain BOM
Answer: In Postgres, you would typically use a partial unique index for this:
create unique index on bom_item(pcb_identifier) where(bom_id_fk = ?)

The question mark should be replaced with the value of bom_id_fk for which you want to enforce uniqueness of pcb_identifier.
Answer: Yes, you want a unique constraint with two keys:
CREATE TABLE bom_item (
    id SERIAL PRIMARY KEY,
    bom_id_fk INTEGER REFERENCES bom(id) NOT NULL,
    pcb_identifier varchar(50) NOT NULL,
    CONSTRAINT unq_pcb_identifier_bom_id_fk UNIQUE (pcb_identifier, bom_id_fk)
);

This will guarantee that at most one pcb_identifier per bom_id_fk.  Note that either key individually can be in the table multiple times.  It is the pair that is unique.
By the way, Postgres recommends replacing serial is int generated always as identity.
Comment: Thanks for the hint concerning the `serial`. I changed my setup (and the question) accordingly

PostgreSQL UNIQUE for JOINed table


How to compile a java file using the command line?

Question: I want to test if Java is working fine on my machine, for that I wrote this part of code.
this is the code :
public class Test {

    public static void main(String args[]){
        System.out.println("This is a Test class");
    }
}

The Test.java file is in the directory C:\Users\HP\Desktop\JAVA Code,
I execute this java compile command to compile the java class : javac Test.java , I got the error below :
C:\Users\HP\Desktop\JAVA Code>javac Test.java
Test.java:1: error: error while writing Test: Test.class (Le fichier spÚcifiÚ est introuvable)
public class Test {
       ^
1 error

Comment: do you have a package statement? is this a correct file "Test.java" ?
Comment: Can you do `echo xx >Test.class` and `del Test.class` ? Any errors when you do that?
Comment: Try `dir Test.java` and check whether it exists.
Comment: Translation comment: *Le fichier spécifiér est introuvable* means *The specified file is not found*
Comment: @Stultuske I don't hava a package statement, it is a correct file, note that I tried to execute this code in eclipse, it works, but in command line, it does not work
Comment: @RobertKock I tried it, Test.java exists
Answer: Thank you for your responses, finnaly I solved the error
This is the solution : I'm using windows 10, so when I compile the JAVA file, windows denied this process because of authorities, I added the javac.exe to the authorized apps list in windows, and it works.
How to add apps to the authorized app on windows 10
Comment: You should click on the "tick" on the left to accept your own answer. It can be useful to anyone experiencing the same thing. I tried but couldn't reproduce the same error message, so it's good to know what caused it.
Answer: There might be an issue with the blank space between JAVA and Code in your working directory. This sort of conventions (a directory name with blank spaces) might make ridiculous and time-consuming troubles. Please try  C:\Users\HP\Desktop\JAVA%20Code  as your path to Test.java file.
In case of using Mac, you could use ~/Desktop/JAVA\ Code.
Hope it works out.
Comment: I changed the name of directory to javaCode, but it doesn't work.
Comment: can you execute java -version  and javac -version  commands to ensure that your compiler version is set exactly as jdk version ?
Comment: I solved the problem, you can check the answer, thank you akarimin


What determines which mode you're in?

Question: I've learned all about modes, but there's something that confuses me.
The G major scale contains the exact same notes as the A Dorian scale. So what determines which of those two scales you are playing?
I know if you played a low G or a low A, then we'd hear that as the root and the matter would be settled. But without holding on the root, it seem like the mode is very much up in the air
Comment: @user1079505: I couldn't see how that question is related.
Comment: @user1079505 - it's vaguely related.
Comment: The question is different, but I think the answer with most votes answers your question... anyway, Aaron found a better matching question.
Answer: How can one distinguish G major from A dorian?
Every mode has a tonal center, a point of greatest stability within the overall sound of the mode. So a piece in G major will tend to move toward G as a pitch goal; whereas, a piece in A dorian will gravitate toward A.
If one in looking at a written score, a good starting point in determining the mode is to look at the key signature and then at the final sound of the piece. Since a tonal center is the "at rest" note for the mode, it's reasonable to expect the piece to end on that pitch. So a piece in G major will have one sharp and end on G (or a G major chord), and a piece in A dorian will also have one sharp but end on A (or an A minor chord).
In general, how can one mode be distinguished from another?
A mode is a collection of notes which have a certain set of relationships to each other. Scales are the abstract representation of modes: the set of notes, ordered. The steps of each modal scale has a unique set of intervals. Major, for example, is represented by a scale whose intervals are WWHWWWH. Dorian, by contrast, is represented by a scale whose intervals are WHWWWHW.
When a piece is written "in a mode", it will emphasize the unique relationships within that mode. For example, major emphasizes the half step between the seventh and eighth notes. Dorian, to distinguish itself from major, can emphasize the whole step between those same two scale degrees. The major third between the first and third notes of the major scale can be contrasted with the corresponding minor third in the dorian scale.
By ear
Distinguishing a mode by ear relies on being able to identify the tonal center (not the note name, but the pitch that sounds like the "target" pitch) and the characteristic sound of that mode.
By score analysis
Distinguishing a mode analytically also relies on being able to identify the tonal center and noticing the predominant pitches used in the piece. A piece that has C as a tonal center, and mostly uses "white keys", but emphasizes F#, could be reasonably determined to be in C lydian.
Answer:
The G major scale contains the exact same notes as the A Dorian scale. So what determines which of those two scales you are playing?

mode = set of notes + tonic
The sense of mode is somewhat subjective and depends on where the music makes the listener feel the tonal center to be. Rhythms and sense of pulse and meter, affect that as well as pitches! Meter means, where the "one" beat is and which notes are strong vs. weak - which can be subjective as well. It is entirely possible for a player to "use" the scale of a mode, but FAIL to produce the feeling of that mode. It's not what notes you play, it's how and when you play them. Playing notes from a scale randomly will not create the right modal feeling (except by accident). Using only the white keys of the piano, you can create many different modal feelings. The fact that the keys are white doesn't guarantee anything.

without holding on the root, it seem like the mode is very much up in the air

Exactly. You have to practice it. Here is a longer answer.
Why do modes sound so different, although they are basically the same as a mode of another scale?
(This whole question is yet another dupe, it's being continuously re-asked over and over again by different people using slightly different wordings, so why not have it all out there, just in case someone found one of the answers with THAT particular wording that the person happens to be using.)
Answer: Tonal music is called tonal, as it relies on one particular note as its 'home' note - its tonic - hence tonal.
The majority of tonal music is somewhat like a journey. Our journeys tend to take us from 'home', visiting wherever, and eventually, arriving back at square one - home again. We may well make several journeys during that period, but each will end finally back at home.
Using that analogy, any piece of tonal music will, of necessity, have a 'home'. That's when modal music becomes recognisable. Of the 7 modes produced by use of the notes available from one 'parent' key (thus, its scale notes), each will have its own tonic, or home. Each will use that note to return to, as a temporary rest place, throughout, and finally feel finished on that same note.
Thus, the other notes involved will have particular relationships with that tonic. In Ionian mode, there is always a leading note, one semitone below the tonic, which when heard often begs that the tonic will follow, and if it doesn't (as sometimes happens), resolution is denied, producing a feeling that the journey's not over yet.
Using those same 7 notes, but in Dorian mode, there's no leading note as such, so that feeling cannot be invoked. There's also the factor that the 3rd of any mode will be either m3 or M3, giving a minor or major feel to the piece, whenever that particular note is heard. One of the reasons Aeolian is considered, along with Dorian in jazz, as the prominant minor mode.
To establish a mode in a piece, then, the tonic needs to be a prominant note, the leading note will be used to herald its arrival (or not, if there isn't one!), the 3rd of the mode will underline whether it's a minor or major mode, and the triads involved (all the same in all modes from the same parent) will be used in such a way that the tonic triad becomes sensed as the home triad.All that, and more, is why the Locrian mode is probably least used, as it finds it hard to fulfill any, or many, of those criteria...

What determines which mode you're in?


Valuation ring and localizations

Question: Theorem. Let $D$ be an integral domain with identity. The following conditions are equivalent.
(1) $D_P$ is a valuation ring for each proper prime $P$ in $D$.
(2) $D_M$ is a valuation ring for each maximal ideal $M$ in $D$.
How do I prove this? I tried working with the definitions, but it didn't turn out to be helpful. Help.
Answer: Let's take as definition of a valuation ring $V$ with field of fractions $K$ that for each $u \in K$, either $u \in V$ or $u^{-1} \in V$.

Fact: Let $V$ be a valuation ring with field of fractions $K$.  Let $R$ be a ring $V \subseteq R \subseteq K$.  Then $R$ is a valuation ring.

Proof of fact is immediate.
(1) -> (2) is obvious since maximal ideals are prime.
(2) -> (1) Let $\mathfrak{p}$ be a prime ideal.  It is contained in some maximal ideal $\mathfrak{m}$.  We have naturally that $D \subseteq D_\mathfrak{m} \subseteq D_\mathfrak{p} \subseteq K$. So $D_\mathfrak{p}$ is a valuation ring by the above fact and the assumption that $D_\mathfrak{m}$ is a valuation ring.

Valuation ring and localizations


I find composing for transposing instruments hard

Question: So I have gotten into writing orchestral works and I have a bit of a problem. You see, I can transpose, but I am not used to adjusting the notation of the transposition.
So if I transpose from C to Bb, I typically just change the key signature to Bb, transpose, and then leave it at that. I don't typically adjust it so that Bb is in the position C is in on most instruments. That looks to me like I would be going forwards with both and than backwards with the notation.
I was thinking that until I get an intuition for the different transpositions and what instruments require it, I should write a chart on a piece of paper where the first column is the concert pitch column for reference and then I transpose the individual notes of the chromatic scale to these keys:

Bb for Bb clarinet, euphonium, tuba, saxophone(sopranissimo, soprano, tenor, bass, and subcontrabass) and brass band)
Eb for Eb clarinet, saxophone(sopranino, alto, contrabass)
F for French horn, English horn, and Basset horn(essentially an F clarinet)
G for alto flute
A for A clarinet
Ab for piccolo clarinet(if I ever write for it)

But how would I get an intuition for it? I mean after years of transposing piano music and after researching transposing instruments, I still have trouble writing for clarinet and especially French horn or alto flute.
Comment: I find this confusing. If a piece is in C, you would write in D for Bb trumpet, and in A for Eb sax, surely?
Comment: You "can transpose" but you are "not used to adjusting the notation of the transposition"? What does that mean? There's nothing to learn about notating a Bb clarinet part except writing every tone a note higher. It's annoying at first, especially when dealing with several different transpositions simultaneously, but it's nothing that doesn't come to you by itself with more practice.
Answer: So write in concert pitch.  Getting out "reverse-transposed" sheet music should be a standard feature of whatever notation software you use, and there rarely is a reason for playing from hand-written scores these days since transcribing has become reasonably simple nowadays.
Comment: Very much THIS.  Or hire a grad student :-)
Answer: Your description suggests that you're doing it backwards!  A piece in C will need to be written in D for a Bb instrument, in A for an Eb instrument.  Has your work been performed?
You can compose using a 'Score in C' or a 'Transposed Score'.   There is a growing tendency to use 'Score in C' right through the process, though transposed Parts will be supplied for the individual players.  (This is distinct from the modern tendency to eschew key signatures altogether, which can apply to both transposed and non-transposed scores.)
The advantage of a transposed score is that it helps the composer see how the music lies in each instrument's range.  Inexperienced composers often make far too much use of the extremes, rather than writing in the comfortable mid-range where the instrument can do its best without struggling technically.
As you're probably composing into a computer notation program, you can have the best of both worlds.  It will know the transpositions for all the instruments you're likely to need.  Add a 'Trumpet in Bb' to the score, you'll get a stave with the correct transposition built in.   And you'll have the choice of switching between Transposed and Untransposed score views.  Don't just create generic staves and label them 'Trumpet' etc.  USE the facilities of the program!
Comment: You don't have to PLAY every instrument.  But a good composer develops a rapport with them, knowing how they sound in the various registers.  Almost as good as actually playing it!
Comment: Yes. This is one of the few things where a graphical computer score editor really makes sense. Though I daresay the transposed view doesn't add all that much if you can't play the instrument yourself – knowing the _ranges_ isn't enough to write something that actually lies naturally on the instrument. And for the range alone, the concert pitch view would also be sufficient.


Outlook 2010 - how to remove "You forwarded this message on" line in email with VBA

Question: Does anyone know if there is a property associated with the grey message that appears under the Sender's name in a forwarded email? On Exchange it is "You forwarded this message on mm/dd/yyyy hh:mm AM" next to a small blue icon with an "i" in it.
I have not been able to identify the property in the Object Reference.
i would like to turn this off after forwarding an email in a VBA routine.
Thank you.
Answer: PR_LAST_VERB_EXECUTED (DASL name "http://schemas.microsoft.com/mapi/proptag/0x10810003") determines the action kind (forward/reply/reply all) and PR_LAST_VERB_EXECUTION_TIME (DASL name "http://schemas.microsoft.com/mapi/proptag/0x10820040") determines the time. You can delete these properties using MailItem.PropertyAccessor.DeleteProperty.
Take a look at the properties in OutlookSpy (I am its author - click IMessage button).
Answer: The Outlook object model doesn't provide any properties for that.
But you can try to read the MAPI property PR_LAST_VERB_EXECUTED (0x10810003) to detect the last action made with the Outlook item. I suppose the information text is based on that property value.


How to redirect my sub-domain to localhost:5000 in Https with Nginx?

Question: I've a problem with my nginx :
I have to redirect all the http and https traffic when my users search "hermes.my-domain.com" to the 5000 port, on my nginx serveur, where my app is.
"hermes" is the name of my sub-domain.
So I do that :
server {

listen    80;
server_name    hermes.my-domain.com;

return 301 https://hermes.my-domain.com$request_uri;
}

server {

listen    443;
ssl_certificate           /etc/certs/ssl/bundle.crt;
ssl_certificate_key       /etc/certs/ssl/server.key;

    location / {
        proxy_pass http://localhost:5000;
        proxy_redirect off;
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Ssl on;
    }
}

Every time I fall on a 502 error.
I don't understand what's happen...
if someone know the problem please ?
Thank you very much !
This is my result from error.log :
My apologies, this is my result from error.log :
    2021/11/24 09:09:44 [error] 19384#19384: *332 connect() failed (111: Connection refused) while connecting to upstream, client: 10.10.1.158, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:5000/", host: "hermes.my-domain.com"

2021/11/24 09:09:44 [error] 19384#19384: *332 connect() failed (111: Connection refused) while connecting to upstream, client: 10.10.1.158, server: , request: "GET / HTTP/1.1", upstream: "http://[::1]:5000/", host: "hermes.my-domain.com"

2021/11/24 09:09:44 [error] 19384#19384: *332 no live upstreams while connecting to upstream, client: 10.10.1.158, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://localhost/favicon.ico", host: "hermes.my-domain.com", referrer: "https://hermes.my-domain.com/"

Thank you for your help all !
Comment: If that is an exact copy-paste, note that you currently have `location /{` and probably mean to have `location / {`. Often `nginx` will put something in `error.log` - maybe you could post if there is something there.
Comment: Thank you for your reply.  I put a space between "/{" in my vhost file, but it's the same result. And I add a log output, and this is the result :
10.10.1.158 - - [23/Nov/2021:17:16:17 +0100] "GET / HTTP/1.1" 502 568 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36".
Comment: normally use `listen 443 ssl;` or `listen 443 ssl http2;` never read about ssl on
Comment: The output above is from `access.log`. Please edit the question and add contents of `error.log` when the error occurs.
Comment: `connection refused` indicates that nothing is listening on port 5000. Make sure your service is running and listening on the correct port and interface. You can do that by running `ss -tnlp |grep :5000`.
Comment: Oh okay, so if I understand well, it's not my Vhost the problem, but rather my web app is not correctly working on my 5000 port ?
Comment: It's a possibility. We can't say for sure without seeing the output of said command.
Comment: The result is nothing, I do some test on other port what I know active, and I have a result, but for ss -tnlp |grep :5000, I have nothing. So I think you're right ! And the problem is more on my web app. Thank you so puch for your answer and help
Answer: Your application server is not listening on Port 5000.
connection refused indicates that nothing is listening on that port on that interface.
An empty output of ss -tnlp |grep :5000 confirms that nothing is listening on that port.
If your application server is indeed running, check it's configuration for the correct port. If it is not running, start it.


A Question on Schlicht Functions

Question: Denote the class of Schlicht functions (injective, holomorphic on the unit disk, with $f(0)=0$ and $f'(0)=1$) by $\mathcal{S}$.  And let $\gamma :[0,\infty )\rightarrow \mathbb{C}$ be a simple curve (continuous and injective) and such that $\gamma (0)=0$ and $\lim _{t\to \infty}\gamma (t)=\infty$.
I have to show that, for each such $\gamma$, there is a unique $t>0$ so that $\mathbb{C} \backslash \gamma \left( [t,\infty )\right)$ is the image of some $f\in \mathcal{S}$.
Here's my idea so far:
For each $t$, via the Riemann Maping Theorem, I can construct a bijective, holomorphic function $f_t:\mathbb{C} \backslash \gamma \left( [t,\infty )\right) \rightarrow \mathbb{D}$ ($\mathbb{D}$ is the unit disk) such that $f_t(0)=0$.  Furthermore, such an $f_t$ is unique up to a choice of the argument of $f_t'(0)$.  If I could somehow show that there must be some $t>0$ such that $\left| f_t'(0)\right| =1$ I would be done, but I am stuck as how to do this.
Anyone have any ideas?  In the same direction or not, all suggestions are welcome.
Answer: Here is a simple idea, unfortunately not finished (unlike I thought a minute ago; I'm posting it anyway:) It shows that there is at most one such $t$, but not existence (for existence I give only an unfinished idea).
Let $F_t:\mathbb{C}-\gamma([t,\infty))\to\mathbb{D}$ be the holomorphic bijection such that $F_t(0)=0$ and $F_t'(0)>0$. If $t_1<t_2$ then $F_{12}=F_{t_2}\circ F_{t_1}^{-1}:\mathbb{D}\to\mathbb{D}$ is injective but not bijective and $F_{12}(0)=0$, so by Schwarz lemma $F_{12}'(0)<1$, i.e. $F_{t_1}'(0)>F_{t_2}'(0)$. So there is at most one such $t$ that $F_t'(0)=1$.
For existence: If $t$ and $a>1$ are such that $\gamma(t')>a$ for all $t'>t$ (i.e. if $t$ is big enough) then $z\mapsto F_t(z/a)$ maps $\mathbb{D}$ injectively to $\mathbb{D}$, so $F_t'(0)\leq1/a<1$ (again by Schwarz lemma).
If $F_t'(0)>1$ for some (small) $t$ and if $F_t'(0)$ is a continuous function of $t$ then we're done.

A Question on Schlicht Functions


Measure alignment in LilyPond

Question: In LilyPond, why is the first (yellow marked) measure not aligned with the other measures? What is the way to fix it?
Comment: It's a setting in the notation program you're using.   Tell us WHICH program and we can give specific help.
Comment: Frescobaldi Version 3.1.3
Answer: In LilyPond, to get rid of indentation at the start of the piece of music you just need to include indent = 0 in the layout block.

The reason the indentation is there, is to leave some space for the instrument name.
It also makes the first line of the piece stand out (somewhat like indenting paragraphs in a body of text).  This is especially useful when there are multiple piece over several pages.
Comment: The convention of an indented first stave often extends to scores where there ISN'T an instrument name there.

Measure alignment in LilyPond


Which wiki markup parser does Wikipedia use?

Question: None of these parsers are used by Wikipedia; None of them handle the wiki code correctly.
Does anyone know what parser Wikipedia uses?
Comment: Wikipedia is run by MediaWiki software, and I'm pretty sure the parser is built-in.
Answer: Wikipedia runs on the Mediawiki engine, originally written precisely to use for Wikipedia.
They implement their own parser. A more thorough description of the parser is available in the manual.
Comment: Do you know how to use [their own parser](http://svn.wikimedia.org/doc/Parser_8php_source.html) in a simple example?
Comment: @Peter: I've never worked with the MediaWiki source, but judging by the manual, you'll want to instantiate the class and call either the [parse](http://svn.wikimedia.org/doc/classParser.html#a0e3f2edd4bd47376953dfad4dcfc9c74) method. If it's just parsing to HTML, you might be able to use the [internalParse](http://svn.wikimedia.org/doc/classParser.html#a6b7ac0b498eb30e00dfcfb5722cfab9f) method instead.
Comment: The page die when I try to instantiate the class. Neither `$wiki =& new Parser();` or `$wiki = new Parser();` works.
Comment: @Peter: I expect the parser has some amount of dependencies which you may or may need to provide somehow (e.g. include other files). Again, I have never touched or used this code, so I can't say for sure; if nothing else, you should be able to figure it out by turning on error messages and dealing with any problems one at a time.
Comment: @Peter: You may also find the following blog post helpful to understand the parser better: http://musialek.org/?p=94
Answer: Wikipedia uses MediaWiki, which has its own parser.
Comment: I am looking for just the parser, not the whole engine.


If $f(\theta) = sin(\theta) = 0.1$, then find $f(\theta +\pi) = sin(\theta + \pi)$

Question: I know the answer is $- 0.1$, but I'm not sure how to show my work analytically. My reasoning is that a $\pi$ shift changes the $0.1$ into a negative number, just like in the unit circle. How do you analytically find the answer?
Answer: Simply you may use the formula: $$\sin(a+b)=\sin(a)\cos(b)+ \cos(a)\sin(b) $$
Answer: You can do it by using the summation formula for sines
$$\sin (x + y) = \sin (x)\cos (y) + \sin (y)\cos (x)$$
just set $y = \pi $ and you get
$$\eqalign{
  & \sin (x + \pi ) = \sin (x)\cos (\pi ) + \sin (\pi )\cos (x)  \cr
  & \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, = \sin (x)\left( { - 1} \right) + 0\cos (x) =  - \sin (x) \cr} $$


Como descobrir o tamanho de um arquivo por plsql?

Question: Olá, estou com dúvidas sobre como achar o tamanho do arquivo na linguagem PL/SQL.
Já procurei em vários lugares e achei essa solução como padrão:
declare
  vExists     BOOLEAN;
  vFileLength NUMBER;
  vBlocksize  NUMBER;
begin
  UTL_FILE.FGETATTR('directory_location',
                    'file.extension',
                    vExists,
                    vFileLength,
                    vBlocksize);
  dbms_output.put_line('vFileLength :' || vFileLength);
  dbms_output.put_line('vBlocksize :' || vBlocksize);
  dbms_output.put_line('MB :' || (vFileLength / 1000000));
end;

Mas ele me retorna null em todos os casos.
Alguém teria outra maneira de descobrir o tamanho de um arquivo em pl?
Obrigado desde já! :)
Comment: É uma boa pergunta, também gostaria de saber.
Comment: O que o Exists retornou ?
Comment: Basicamente é isso mesmo como está usando, vou postar a function que uso e não tenho problemas, talvez seu arquivo não está sendo encontrado.
Answer: Parece que a função está correta, o problema pode estar relacionado ao caminho dos diretórios do arquivo, segue a função que uso para retornar o tamanho em bytes.
SELECT flength('diretorio_teste','teste.txt') size_in_bytes FROM dual;

-- Function
CREATE OR REPLACE FUNCTION flength(location_in IN VARCHAR2,
                                   file_in IN VARCHAR2)
RETURN PLS_INTEGER
IS
    TYPE fgetattr_t IS RECORD (fexists BOOLEAN,
                               file_length PLS_INTEGER,
                               block_size PLS_INTEGER);
    fgetattr_rec fgetattr_t;
BEGIN
    UTL_FILE.fgetattr(location => location_in,
                      filename => file_in,
                      fexists  => fgetattr_rec.fexists,
    file_length => fgetattr_rec.file_length,
    block_size => fgetattr_rec.block_size);

    RETURN fgetattr_rec.file_length;
END flength;
/


Is this function analytic in every point?

Question: Given the function $\ f(x) =  \frac{e^{2x} -1-2x}{x}  $ , I am asked to determine if there are any non-analytic points, so I managed to find the series for this function, $\sum_{n=1}^∞ \frac{2^{n+1}}{(n+1)!}x^n $ , from what I know every point is analytic
Comment: How is f defined at 0?
Answer: The function $f$ has an isolated singularity at $x_0=0$, this means that there exists an open disk $D(x_0,r)$ for which $f$ is analytic on the punctured disk $D(x_0,r)\backslash \{x_0\}$. What happens is that the singularity is removable
$$
\lim_{x\to 0} f(x) = 0
$$
So, the function is not analytical everywhere
Answer: Yes, I am aware that f(x) is not defined on x=0. Yet, I have the example of $ g(x)= \frac{sen(x)}{x} $  being analytical everywhere despite not being defined on x=0, at least according to "Differential equations and boundary value probelms" by Nagle, on page 441, 4th edition, calling such point a removable singularity, so I am a little confused


basic violin note question

Question: I am beginner to learn violin and I need to understand the basic note.
Below's two lines of notes from suzuki violin book1
I'd like to understand:

Am I right that 3 # means A major?
What is the C in the start of second line? why the C is not in the first line?
Why use 1 #, 2 # or 3# to mark different major, is this the exactly same as piano/keyboard notes?

Thanks
Answer:
Yes, 3 sharps is the key signature for A Major
The second line changes Time Signature. The "C" is an abbreviation for 4/4 time, also known as Common time, now having 4 counts in the measure and 4 counts in a whole note. The first line has the time signature written out as 3/4 time, with 3 counts in each measure.
Key signatures are independent of instruments and are the same in all cases, so yes, the same as the keyboard notes.
Having no sharps puts you in A minor/ C major (all letter notes/white keys), and the key moves up a 5th every time a sharp is added.

When the first sharp is added you have moved up to G major. The second sharp moves you to D major, and the third sharp puts you in A major.
The Suzuki books have Piano accompaniment for the exercises. The key signature is added to the exercise even though you aren't playing anything specific to A major so it matches what the piano is playing.
Comment: yes, thank you for the full explanation.  I didn't go into it because someone starting with book 1 of suzuki probably doesn't need the history at this point. Using "Common Time" as a mnemonic for the C being 4/4 is useful, even if it isn't exactly what it means.  I also tell my students that they will get in "treble" if they don't remember what the other name of the G clef is...  https://en.wikipedia.org/wiki/Time_signature
Comment: Many people assume "the letter C" stands for "Common time," but actually it originated before the modern concept of "time signatures" and "bar lines" even existed in western music. It was originally just a broken circle (to distinguish it from a complete circle) and the modern "cut time" symbol was a just a broken circle with a vertical line across it. See https://en.wikipedia.org/wiki/Mensural_notation#Mensurations for the original (and complicated) system of dividing notes into 2 or 3 equal parts, as compared with the modern system of only dividing into 2 (half notes, quarters, 8ths, etc).
Comment: @AlphonsoBalvenie The name for the other clef is fairly bass-ic, really.
Comment: @Alphonso Balvenie, sorry I just couldn't find how to mark your answer the correct one like stackoverflow. It's my first post in music channel.

basic violin note question


How to create a Webform pre-build option list via a query to an external database?

Question: I'm trying in Webform (version 4.9) to create a pre-build option list with data from an external database. A pre-build option list is an available list you get when creating a "select options" field in Webform (like list of countries, state, ...).
I didn't find an existing module that allows me to add such pre-build list to Webform.
So, first I added my external database information to the setting.php file.
To test it, I build a simple php page containing this:
db_set_active('external_db');
$query = db_query("SELECT id, name FROM TABLE")->fetchAllKeyed();
db_set_active();
Print_r($query);

And, it's working (= I got a correct result of my request).
So then I added this to my .module file:
function webform_pre_build_list_db_webform_select_options_info() {
    $items = array();
    $items['modeles_db'] = array(
        'title' => t('Modeles_db'),
        'options callback' => 'webform_pre_build_list_db'
    );

   return $items;
}

function webform_pre_build_list_db() {

db_set_active('external_db');

return db_query('SELECT id, name FROM table')->fetchAllKeyed();

db_set_active('default');

}

And, it's not working (= my list is empty).
If I try with a request to the Drupal DB, then, it's working. For example:
function webform_pre_build_list_db() {
return db_query('SELECT cid, recipients FROM contact')->fetchAllKeyed();
}

Is working well, I got recipients form drupal table "contact" in my list...
What am I missing?
Any help will be appreciated!
Comment: first of all you are using `db_set_active('default');`  after `return` statement, next - read about [db_set_active](https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_set_active/7) probably you need to clear cache
Comment: What's a "Webform prebuild list"? Also, would it be an option to use an (existing) contributed module instead of writing your own module? If you want to answer these questions, then please do so via an EDIT of your question.
Comment: @Pierre.Vriens, I have edited my post.
Comment: @Neok, Yes to go back to default Drupal DataBase, but I change to "external_db" before return. I already tried clearing cache. Thanks!
Comment: OK, now the question is way more clear. I hope my extra edits are OK (also). If not please rework as you like ...
Comment: @Pierre.Vriens, edits sound good for me :), now let's hope for an answer ;) thank you!
Comment: @Fumble try to debug with `Xdebug`, or `var_dump` atleast inside webform_pre_build_list_db
Answer: I changed this:
function webform_pre_build_list_db() {
db_set_active('external_db');
return db_query('SELECT id, name FROM table')->fetchAllKeyed();
db_set_active('default');
}

to this
function webform_pre_build_list_db() {
  db_set_active('external_db');
  $options = db_query('SELECT id, name FROM table')->fetchAllKeyed();
  db_set_active('default');
  return $options;
}

And it's working!
(Explanation: return immediately ends the execution of a function, in this case before db_set_active() could be called.)
Thanks to Nevets


how to perform aggregation and expression from given string (formula)?

Question: I want to do aggregation operation by identifying "sum(a)" as in the below string and need to perform some logical operation to get sum, avg, count or percentage(i have separate method to do that so don't worry about that).
expression like below,
 = '"sum(a)" * 10 + "count(b)"'

Here a and b is key word. Based on the key word i will perform the operation. But i need to identify operation name and key word in the above string.
Then, I need to execute the expression without using eval function for following expression. like below,
"10 * 10 + 22"
Note: I am trying to use Function constructor, but i am facing performance issue.(Use string to call function without eval())
Comment: @LaxmikantDange probably written down in the rest of the homework assignment?
Comment: Souldn't the whole expression be a string? Shouldn't it be `'sum(a) * 10 + count(a)'`
Comment: where are count and sum?
Comment: @Andreas It is maybe more than simply a `for`loop. You have to parse the expression
Comment: What you need to do is to build a *parser*. You can use regular expressions to **validate** the lines, but you will need write the rest of the code yourself. Regular expressions do not cater for this.
Comment: `without using eval` also I assume without `new Function` too?.. If it's without `new Function` also, you will need to parse.  There are lots of JS parsers out there, an example one would be peg.js.  https://pegjs.org/
Comment: @C.Champagne yes expression be a string. i have modified my post. I hope it now clear
Answer:

function sum(values){
  return values.reduce(function(s, n){
  return s + n;
}, 0)
}

function count(values){
  return values.length
}

alert( sum([2,3,4]) * 10 + count([2,3,4]) )
Comment: My bad.! Kind of mixed that with the sum ;)
Answer: You can use Array.proptotype.reduce:

const values = [2,3,4];
const sum = values.reduce((sum, current) => sum + current, 0);
console.log(sum * 10 + values.length);


SQL Server: Adding a column increases table size more than expected

Question: To migrate to a new schema, I am doing two things to a table:

Changing a VARCHAR column to NVARCHAR
Adding a BIGINT column

To test how this affects size, I generated 180,000 rows. The VARCHAR column I am changing is set to null on every row.
Here are the results of sp_spaceused (all sizes in KB):
<code>          rows     reserved     data   index_size  unused
          ----     --------     ----   ----------  ------
before    180000     110976     43168       67288     520
after     180000     120320     52536       67296     488
</code>
So the data grew by more than 9MB. I would have expected it to grow by only 1.4 MB, because I added an 8-byte numeric column.
If I just create the table and generate the data, the size looks more like what I would expect:
<code>          rows     reserved     data   index_size  unused
          ----     --------     ----   ----------  ------
        180000       117760    46184        71352     224
</code>
So is there something about adding a column that causes sp_spaceused to report more data in use than was actually added?
Comment: Did you rebuild your clustered index afterward?  You probably got all sorts of page splits by requiring an extra eight bytes on each row.  Check the number of pages used, I'll bet it increased quite a bit.
Comment: What is the table definition? How did you generate the rows?
Comment: Wouldn't changing `VARCHAR` to `NVARCHAR` double the string lengths? This might cause a some forwarded records as well.
Comment: @mustaccio they say all the values are null so this would be zero length. Forwarded records only apply to heaps.
Answer: No one really explained why this happened.  Dave Gugg gave you a great hint.
SQL stores rows in pages.  (That are about 8K, but not exactly)  And a row must fit into one page (not really, given long varchars can be stored on a separate page using a pointer - but yours are all null, so lets ignore that for now.)
The pages are allocated in clusters.
When you inserted the rows you had a nice fresh set of pages and clusters and the rows were all neat.
As you make any change, but particularly something like adding a column, SQL must update every row.
Updating any row requires changing one or more pages - because the changed row may no longer fit on the same page.  In fact, because of the way rollback works, I think that sometimes SQL actually likes to move changed rows to a new page.
So, your tightly arranged rows got distributed and took many more pages and clusters.  Over time with many changes, this averages out.  Not every update adds pages - but adding a column is making each row larger and less likely to fit with its prior neighbors.
We cannot be more specific because you did not provide the schema.  If you had, we'd have a sense of expected rows per page before and after your change.
Comment: Great explanation. Thanks.
Answer: As you all expected, the problem was fragmentation. After generating the data and migrating to the new schema with the additional column, I checked fragmentation using sys.dm_db_index_physical_stats. The avg_fragmentation_in_percent for the clustered index was 98.8%. Rebuilding reduced it to 0.4%, and sp_spaceused show the data size dropping from 52MB to 29MB.
Thanks for all the great help.


Firebase chat - need suggestion

Question: I am developing a project where a chatting feature is required. For the chatting module, I am using firebase chat.
Please check my requirement
1.Ten to fifteen people chat together on a "chat group". Users can chat "one-to-one" or "group chat". This type of chat group will be created approx 1000 per day.
2.There is a live event section on our project. On that day 15,000 to 20,000 users can join a single group chat and chat together. Approx 10 live events happen in a month.
3.There is a file upload option on the chat module. Approx 20GB/day of data can be stored on "storage".
My question is
a)which kind of database is good for this kind of situation - "Cloud Firestore" or "Realtime Database"?
b)please suggest to me about the pricing? what will be the approx pricing for this type of chat module?
Comment: For deciding what database to use: did you see (and try) this already: https://firebase.google.com/docs/database/rtdb-vs-firestore ? For determining the cost, did you see the pricing calculator at the bottom of this page already: https://firebase.google.com/pricing?
Answer: I have done messaging to my App and I got it working with Realtime Database
Realtime Database has .on future. that mean when a new value enter  the database the other user will be notified. You don't have to trigger the question to the database again and that is what Realtime mean.
Comment: While I'd also go with Realtime Database for this solution, the realtime listeners aren't the reason. Firestore has an `onSnapshot` method, which results in the exactly same behavior. https://firebase.google.com/docs/firestore/query-data/listen
Comment: I know, but realtime has faster response and it can handle more then `Firestore`. I would use both. for realtime I would only save the messages content and for `Firestore` i would save data that are complex. That is what I did anyway.
Comment: I'd clarify that bit about speed in your answer, as it now reads as if Firestore requires polling which it doesn't.

Firebase chat - need suggestion


Array retornando erro "Can't use function return value in write context in"

Question: Estou criando um array mas esta me retornando o erro:

Fatal error: Can't use function return value in write context in C:\xampp\htdocs\cadastro_insert.php on line 54:

Aonde estou errando???
$array = array(1, 2, 3, 4, 5, 6); --> tambem tentei:  $genero = array(6);
$x = 0;

if ($genero01 != "") {
$x++;
$array($x) = $genero01;
}

if ($genero02 != "") {
$x++;
$array($x) = $genero02;
}

...
Comment: Substitua `$array($x)` por `$array[$x]`
Comment: Deu certo roberto. Obrigado
Answer: Motivo
Conforme já dito, o erro estava ao chamar o array, onde está usando parênteses ao invés de colchetes:
$array($x) = $genero01;

$array($x) = $genero02;

Corrigindo
if ($genero01 != "") {
  $x++;
  $array[$x] = $genero01;
}

if ($genero02 != "") {
  $x++;
  $array[$x] = $genero02;
}


Should I create a class or add a property

Question: I am currently designing a software to track and manage an individual's finance using C#/WPF and the MVVM pattern. This is a personal project I am doing on my own, that I have started out of interest in gaining more knowledge with these technologies and to put in my portfolio, so having no time/money/etc constraints, I am trying to take the best decisions design-wise.
In the model part of my software, I currently have classes like Expense and Income that inherit a public interface ITransaction. I also have classes like BankAccount, CreditCard and Loan that inherit a public interface IAccount. Expense and Income don't have any difference between them, they have the same properties like Name, Description, etc. Same goes for BankAccount, CreditCard and Loan: they all have the same properties. Since these are in the model part of MVVM, to my knowledge, they shouldn't have methods since they shouldn't have any logic implemented directly in them (other than properties validation that can be done in the properties themselves).
A question I am having early on (I actually am just starting this project), is whether I should change that design since, while they model something concrete of the real life, they have no difference at all between them (Expense is just a copy paste of Income, etc). Should I be changing my design to have, for example, a TransactionType property in a Transaction class in order to distinguish between an income and an expense instead of having the class type do that difference?
What are the advantages and disadvantages of each method in the long run?
Comment: @Choub890 can i give a piece of advice: develop for what you need now, do it in a way so you can extend it later if you need it and you should be fine
Comment: I agree with @GrantWinney also.  I don't think you can go too far wrong either way, but using separate classes is safer, gives you more flexibility.
Comment: Yeah, i agree with @GrantWinney, keep your code clean so if you will need to change it later you just copy paste it and you are done.
Comment: @GrantWinney Let's say that I keep things the way they are and the Expense and Income class never change (so they basically stay a copy paste of each other, but only differing in the treatment I do with them in the ViewModel). Wouldn't that be considered a bad design later on in the project?
Answer: If you're torn between the two, you could start off with the simpler option - a single class with a property indicating the transaction type.
public class Transaction
{
    public string AccountNumber { get; set; }

    public decimal Amount { get; set; }

    public TransactionType TransType { get; set; }
}

public enum TransactionType
{
    Income,
    Expense
}

If you decide later that the two concepts are diverging, and you need separate functionality for one or the other, you could always create separate classes that extend Transaction, which should hopefully prevent some refactoring headaches:
public class Credit : Transaction
{
    public Credit()
    {
        TransType = TransactionType.Income;
    }

    public void SomeOtherMethodYouRealizedYouNeed()
    {
        // Do something
    }
}

public class Expense : Transaction
{
    public Expense()
    {
        TransType = TransactionType.Expense;
    }

    public int SomeNewProperty { get; set; }
}

Just my two cents...
Comment: I prefer the inheritance model from the beginning. It almost always has to be refactored to this later. I wouldn't even consider to have the `SomeType` property anymore now. Having both the inheritance and the `Type` property at the same time is redundant anyway so why bother at all? It only makes things more complicated.
Answer: In the end, I will keep my design the way it is there, which is with and Expense and Income class inheriting the ITransaction interface (same goes for BankAccount, Loan and CreditCard with the IAccount interface) because, as pointed out by comments, it would be the easiest to refactor if even comes a day where I need different behaviors from those classes. This could be as simple as different property validation logic (which could be the case even though they Expense and Income just have properties and no methods).
Also, a class is something that should be modeled from an object or a concept of real life that your software uses. I think, for that reason, that Expense, Income and BankAccount, Loan and CreditCard should be classes even if for the moment there is no difference in logic between them, because those are concepts or "objects" that my software has to model.