Does disabling unused languages [Python ASP.net CGI Perl] in PLESK8 Speed Up PHP5 on Apache server?

Question: Fellow Folks,
Inspecting om my PLESK 8.2 on APACHE2 with PHP 5.2.3 I saw this. Being a person who loves peed, would I gain anything by disabling all the stuff except PHP? which is the only thing I use really? I'll do anything to speed up my site. Advise in regards to the buttons in this picture is appreciated greatly.
Answer: No - disabling the other language's won't make PHP any faster, as the other options won't be using CPU time unless they're actively being used.
In theory, you might save some memory due to Apache modules not being loaded, but this is pretty marginal.
That said, if you're not going to use them it makes sense to disable them anyway.


cannot install $ npm i mini-css-extract-plugin. What could be the problem?

Question: This is the ERROR. I use visual studio code with gitBash.
$ npm i mini-css-extract-plugin
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: firstname.lastname@example.com
npm ERR! Found: firstname.lastname@example.com
npm ERR! node_modules/webpack
npm ERR!   dev webpack@"^4.39.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer webpack@"^5.0.0" from firstname.lastname@example.com
npm ERR! node_modules/mini-css-extract-plugin
npm ERR!   mini-css-extract-plugin@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\Smith\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Smith\AppData\Local\npm-cache\_logs\2021-08-19T13_12_04_740Z-debug.log

This is my package JSON file. What could be wrong here?
How to match versions?
{
"name": "lesson-54-intro-webpack",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack-dev-server",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.5.5",
"@babel/preset-env": "^7.5.5",
"autoprefixer": "^9.6.1",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.6",
"babel-polyfill": "^6.26.0",
"css-loader": "^3.1.0",
"file-loader": "^4.1.0",
"html-webpack-plugin": "^3.2.0",
"postcss-loader": "^3.0.0",
"precss": "^4.0.0",
"style-loader": "^0.23.1",
"webpack": "^4.39.1",
"webpack-cli": "^3.3.6",
"webpack-dev-server": "^3.7.2"
},
"dependencies": {
"axios": "^0.19.0"
}
}
Comment: those are literally the same thing.  `npm i` is just an alias for `npm install`.
Answer:
See the edit below.

As the error says the webpack version not matched try either:

upgrade lesson-54-intro-webpack package
downgrade mini-css-extract-plugin

Edit: based on your package.json content
You need to upgrade your webpack version to version 5
Comment: I put a green checkmark. Does this mean that the problem is solved?
Comment: https://drive.google.com/file/d/1QXod8eNzXyBdS7G48IOYBhR6N-wUG0Hb/view?usp=sharing
This is my package JSON file.
What could be wrong here?
Comment: Please add it to you question
Comment: I'm sorry. I'm new here. How you add code without details. I can't add.
This message is displayed:  " It looks like your post is mostly code; please add some more details "
Comment: It's OK, welcome aboard, as I can see you've already added the package json
Comment: Thanks. Yes, I added. But it is not correct to output. Not readable. If done through ```console ```, then this message is displayed: " It looks like your post is mostly code; please add some more details "
Comment: This is syntax highlighting read [StackOverflow - syntax highlighting](https://stackoverflow.com/editing-help#syntax-highlighting) and set the language to `json` rather than `console`, it may help
Comment: Elaborate the question so you won't get this error
Comment: Thank you very much! Can you please tell me,  is it mandatory to use miniCssExtractPlugin or not?
Comment: What do you need to do? Is this part of some tutorial?
Comment: Yes, I am doing a small project based on the tutorial. I wanted to know if it's worth using miniCssExtractPlugin in the future?
Comment: I don't know this plugin, if my answer helped you don't forget to mark it as solved
Comment: yes of course I will not forget. Now I will try to update webpack.
Comment: Hey! Yes. Thanks
Comment: Yes, have a great day


Put off loading my theme banners to speed up Drupal

Question: I'm currently using the Marinelli theme for a project.  It loads ALL the top banner pictures before showing the page.  Very slow.  Results in a big download size for the home page.  Is there a way to get Drupal or the theme to put off loading all but the first banner pics when it displays the page.  See my screen capture of pingdom.com
Dave
Comment: If you can tell us how you'd do this in a non-Drupal site, we can help you implement it in Drupal.
Answer: I think you're looking for a technique called "lazy-loading" to implement on your pages. Lazy loading means that the images are only loaded upon viewing them.
You can use the Lazyloader module as a start to implement it, however how it will exactly work for your site is completely dependent on your Drupal theme and module(s) configuration. One useful example (and starting point) is this blogpost, which explains how to implement the layloader module in combination with a slideshow.
Comment: Thanks, I think this is the answer unless someone else has other solutions...


Can an own goal be scored in field hockey?

Question: In sports like football, a goal is scored whenever the ball is in play and somehow ends up in the goal, regardless of how it happened, unless it relied on a breach of rules by the team who scored.
But in field hockey, I often see the ball go into the goal, even after a player touches it inside the shooting circle, yet a goal is not given and the scores do not change.
Is it possible for a defender to score an own goal at all?
Answer: In field hockey, a goal can only be scored if the ball is played by an attacker inside the circle, then crosses the goal-line under the crossbar without leaving the circle in between.
This applies even if a defender has touched the ball prior to the attacker, or touches the ball between the attacker and the goal. If the attacker would not have scored without the defender's action, the latter is sometimes informally called an own goal. However, the last attacker to touch the ball inside the circle is typically given credit, due to the rule requiring the attacker's touch.
If the ball is not played by an attacker inside the circle, a goal simply cannot be scored. Should only a defender touch it instead, no goal is given, and play restarts with a (long) corner as with any other instance of the ball leaving play over the back-line.
The FIH previously included a mandatory experimental rule which provided for scoring own goals - a defender's touch inside the circle also counted for scoring a goal if the ball entered the goal. However it was widely disliked and did not serve to improve the game as hoped, so the rule was reverted to its previous form.
Comment: does the player, or the ball have to be in the circle ? i just saw spain score via a defender, but the ball was outside the circle, if the ball is pushed, does it depend of where the push starts, or ends ?
Comment: There are several points that need explanation for answering that. You could ask a separate question (preferably by including a video and saying which of the goals you refer to).


The role of G in The Sound of Silence in A minor

Question: So the chord sequence for The Sound of Silence in Am (the key I play in because I lost my capo) is roughly
Am G Am C F C F C F C Am C G Am G etc.
My question is why the G before Am, "within the sound," which has a lot of suspense and does not sound bright at all, sounds very different from the G after the Am, which is bright and cheery. It's G Am G, but the two G's sound very different. I took music theory a decade and a half ago and I've long since forgotten pretty much all of it, but I got the sense that the "chord of suspense" should be E or E7, which is nowhere in this piece.
Answer: We hear the first G chord as ♭VII of A minor.   The second one follows a string of C major chords and feels like V of C major.   Yes, it's interesting what a big difference the context makes.
Answer: Laurence answered this.  I'd just add that the "chord of suspense" is not E or E7 because this piece is modal, in A Aeolian, not in A minor.
Comment: Isn't A Aeolian the same as A natural minor, one of the more commoly found minors?
Comment: @Tim - Good question.  I'd say the border between the two is gradual.  My rough guide is that if G major is used as a dominant (as it is in _Sound of Silence),_ then it's more aeolian, and if e minor is the dominant, it's more natural minor.  But I don't think we can really draw a hard and fast line here.
Comment: Seems to me that Em isn't really dominant in key Am. Seems that G is often used as its 'dominant'.
Comment: It's not common to use Em as a dominant, but it does happen.  In any case, there's not much to distinguish between A Aeolian and A natural minor.
Comment: And in the same vein, there's only one note differece between G and Em!
Comment: Indeed, Tim.  Our catagorizations don't encompass the complexity of the real.  Thank goodness.


Determine if sequence with factorial is convergent

Question: I was requested to determine if $$a_n=\frac{2^n}{n!}$$ is convergent or not. Please notice that I was not requested to present a formal proof that the sequence is convergent, but only to determine if it was, so "intuitive" approaches ar valid as long as I can justify them.
What I did was the following.
$i)$ Notice that  $$a_n=\frac{2^n}{n!}=\frac{2*2*2*...*2}{1*2*3*...*n}=\frac{2}{1}*\frac{2}{2}*\frac{2}{3}*...*\frac{2}{n}$$.
$ii$) From $i$ it follows that
$$lim_{n\to\infty}a_n=lim_{n\to\infty}(\frac{2}{1}*\frac{2}{2}*\frac{2}{3}*...*\frac{2}{n})$$
$$= lim_{n\to\infty}(\frac{2}{1})*lim_{n\to\infty}(\frac{2}{2})*lim_{n\to\infty}(\frac{2}{3})*...*lim_{n\to\infty}(\frac{2}{n})$$
Notice that we can be sure the limit of each of the terms of the sequence represented by $...$ exists when $n\to\infty$ because they are all constants of the form $\frac{2}{b}$ with $b\in\mathbb{N}$.
$iii$) Solving $ii$ we get $$2*1*2/3*...*0=0$$
Because $lim_{n\to\infty}a_n=0$ the sequence converges.
Answer: Yes, the limit is $0$, but you argument is not correct. To see why, consider the sequence$$1,\left(1+\frac12\right)\times\left(1+\frac12\right),\left(1+\frac13\right)\times\left(1+\frac13\right)\times\left(1+\frac13\right),\ldots$$In other words, consider the sequence$$\left(\left(1+\frac1n\right)^n\right)_{n\in\mathbb N}.$$Its limit is $e$, right?! But, from your argument, you should deduce that the limit is $1$, since $\lim_{n\to\infty}1+\frac1n=1$.
However, as I wrote, the limit is indeed $0$. If $n>2$, then $\frac 2n\leqslant\frac23$. Therefore$$n>2\implies\frac21\times\frac22\times\frac23\times\cdots\times\frac2n\leqslant2\times\left(\frac23\right)^{n-2}.$$
Answer: Hint:
For $n\ge 6$ $$0\le 2^n\le (n-1)!$$
Now use Squeeze theorem.


Euler - Operator Splitting for $y'+y=3e^2t$, $y(0)=1$

Question: $y'+y=3e^2t$, $y(0)=1$
How can we solve this equation with operator splitting methods in matlab by using forward Euler method?
Comment: What do you want to split? The solution of the part linear in `y` is the integrating factor `exp(t)`, so set y(t)=u(t)*exp(t)` as usual.
Answer: $${ y }^{ \prime  }+y=3{ e }^{ 2t }\\ \\ { y }^{ \prime  }+y=0\\ { y }^{ \prime  }=-y\\ \int { \frac { dy }{ y }  } =-\int { dt } \\ \ln { y } =-t+C\\ y=C{ e }^{ -t }\\ y=C\left( t \right) { e }^{ -t }\\ { y }^{ \prime  }={ C }^{ \prime  }\left( t \right) { e }^{ -t }-C\left( t \right) { e }^{ -t }\\ { C }^{ \prime  }\left( t \right) { e }^{ -t }-C\left( t \right) { e }^{ -t }+C\left( t \right) { e }^{ -t }=3{ e }^{ 2t }\\ { C }^{ \prime  }\left( t \right) { e }^{ -t }=3{ e }^{ 2t }\\ { C }^{ \prime  }\left( t \right) =3{ e }^{ 3t }\\ C\left( t \right) =\int { 3{ e }^{ 3t } } dt={ e }^{ 3t }+{ C }_{ 1 }\\ y={ e }^{ -t }\left( { e }^{ 3t }+{ C }_{ 1 } \right) $$
and consider the condition that $y\left( 0 \right) =1$ $$y\left( 0 \right) =1+C=1\\ C=0$$ so the final answer is

$$y={ e }^{ 2t } $$
Comment: thank you so much :) but  how this solution write in matlab by using forward euler?
Comment: you are welcome, @ElifHacısalihoğlu,but unfortunately i don't what "operator splitting methods in matlab by using forward euler method" is


iPhone SDK - what is this control? Is it custom?

Question: What is this control? Or is it something that has been custom made? I see it in the Twitter and several other applications. I'm referring to the two triangles, and if you've ever used them, they refresh the view below them, usually going through a list of content items.
(I'm not referring to the navigation controller with a back button)
Answer: They are UISegmentedControls with custom images and the style set to UISegmentedControlStyleBar.
Answer: Its right there in Apple's NavBar sample code. You have the entire source code for the project. Search for NavBar within the Documentation and API reference item under the Help menu of Xcode 4.


Alterar a propriedade CSS Display para TODOS os elementos de uma página e deixar Block apenas para alguns?

Question: Estou tentando fazer a impressão de uma bootstrap-modal que é chamada dentro de um Form com includeporém quero imprimir SOMENTE a modal, tem como fazer isso usando somente CSS? Vejam:
Modal:

CONTEUDO DA MODAL...

Arquivo CSS:
@media print {
*{
 display:none;
}
/* MODAL PROTOCOLO */
#modal-protocolo{
 display: block;
}
}

O que posso usar aqui para selecionar todos os elementos da página?

*{
 display:none;
}

Do jeito que está na hora da impressão fica tudo branco...
Comment: Seu problema é que quando vc da display:none no pai vc obrigatoriamente tb está dando display:none no filho, não há como vc dar display:none no pai e manter o filho com block, pois tudo dentro do pai tb vai estar como none.... E mesmo colocando `*:not(#modal-protocolo)` {display:none} não vai adiantar
Comment: Muito obrigado pelo esclarecimento meu amigo, consegui resolver utilizando um plugin Jquery, com CSS puro tava dando muito trabalho... Vou colocar a resposta
Comment: Gabriel eu consegui uma solução pra vc só com CSS caso interesse...
Answer: Tenho uma solução para vc apenas com CSS. É um tipo de hake, mas basta vc colocar um box-shadow gigante no seu modal na hora da impressão, dessa forma ele vai tampar tudo que estiver por traz, dando a impressão que só tem o modal na página.
Conforme dito no comentário o problema do *{ display:none; } é que quando vc da display:none no pai vc obrigatoriamente tb está dando display:none no filho, não há como vc dar display:none no pai e manter o filho com block, pois tudo dentro do pai tb vai estar como none.... E mesmo colocando :not(#modal-protocolo) {display:none} não vai adiantar...
Segue o código caso queira usa-lo:
Para testar clique em Executar como "Página toda" e depois de Ctrl+P e vc vai ver que os formes não aparecem na página, apenas o modal.

<!DOCTYPE html>

 <meta charset="utf-8" />
 <title>Page Title</title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
 <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

    <form>

      Email address
      <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
      We'll never share your email with anyone else.

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

      <input type="checkbox" class="form-check-input" id="exampleCheck1">
      Check me out

     <button type="submit" class="btn btn-primary">Submit</button>
    </form>

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>

    <form>

      Email address
      <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
      We'll never share your email with anyone else.

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

      <input type="checkbox" class="form-check-input" id="exampleCheck1">
      Check me out

     <button type="submit" class="btn btn-primary">Submit</button>
    </form>

Modal title

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

  ...

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

Uma imagem com o resultado na hora do print.
Comment: @GabrielCarneiro sim, eu imaginei que para telas com muito conteúdo e um longo scroll esse problema poderia acontecer. Mas deixa a dica ai como registro, as vezes serve para quem está com problema similar, porem em uma situação diferente. Tmj
Comment: Uma boa forma de resolver, contudo o meu DOM é muito grande, a modal iria ficar centralizada na página e com conteúdo pequeno... já tentei fazer algo parecido. Mesmo assim, obrigado.
Comment: Valeu, abraços meu velho
Answer: O problema é que o seletor * seleciona TODOS os elementos do HTML (DOM), inclusive as tags HTML e BODY. Portanto se você oculta, por exemplo, o BODY com display: none, qualquer tag dentro do BODY estará oculto.
Para atingir esse resultado que você quer, a estrutura deve seguir o exemplo:

body > * {
  display:none;
}
/* MODAL PROTOCOLO */
#modal-protocolo{
  display: block;
}
<!DOCTYPE html>

  <title>Teste</title>

Título de exemplo

Conteúdo de exemplo

  CONTEUDO DA MODAL...

Comment: Sua solução funciona com alguns ajustes, contudo ainda fico com o Jquery, vou aceitar sua resposta, pois o que eu queria era uma solução apenas com CSS,  abraços meu amigo...
Answer: Bom, não consegui resolver utilizando somente CSS, parti pro uso de um Plugin Jquery chamado printThis, que é fácil de usar e não me deu tanto problema, seguem mais informações...:
$('#imprime-protocolo').click(function(){
    $(".imprimivel").html($("#modal-protocolo").html());
    $(".imprimivel #imprime-protocolo").remove();
    $(".imprimivel .fecha-modal-protocolo").remove();
    $(".imprimivel").printThis();
});

Plugin Disponível em: https://github.com/jasonday/printThis
Inseri uma Div vazia logo após o main:

E configurei o CSS assim:
.imprimivel {
    display: none;
}
/* print styles*/
@media print {
    .imprimivel {
        display: block;
    }
}


Difference between JScrollPane.setviewportview vs JScrollPane.add

Question: I faced this new thing today, and I didn't know why. When I want to show something in panel for example, I just add it to panel; but why I cannot add a table to scroll pane directly, and why I have to call the setviewportview() method? What does add() method do and what does setViewProtView() do?
Answer: Basically, you should not use JScrollPane#add.
JScrollPane has a single component already attached to it, a JViewport, this is what the JScrollPane uses to display any component added to the view port.

setViewportView is a convenience method for for JScrollPane#getViewport#setView
The basic concept comes down to the fact that from the scroll panes point of view, it will only show a single component, so add doesn't actually make any sense for it.  The method is a consequence of extending from JComponent -> Container
Comment: Great answer. I found several answers pointing to use setViewPortView, but no one explained like you did here - 1.  basically JScrollpane already has a component called Viewport, 2. add is just redundant method came through inheritance! Thanks for explaining it nicely.
Comment: @gdbj You'd have to ask the original framework developers, but, `add` comes from `java.awt.Container`, so it's inheritance issue
Comment: Why couldn't JScrollPane#add be overridden to behave as expected?


How many models does gbm fit?

Question: In gbm funtion, if we set train.fraction=0.5, cv.fold=5. Does gbm fit twice for trained sample and CV sample,respectively? 1) 50% of sample is used as trained data to fit the 1st model. 2) 80% of sample is used as CV sample to fit the second model
If that is the case, why gbm.perf only reports the same error curve for both the cases? The only thing differs is just the best iteration number....
If not the case, how does gbm work behind the scene?
Thank you very much!
Answer: In this situation you will fit:

Five full gradient boosted models, each on $\frac{4}{5}$ of the available training data.  Each tree trained within these five boosters has access to all and only $\frac{4}{5}$ of the training data, and it's the same $\frac{4}{5}$ for each tree.
Within each of these five boosted models, each tree will be trained on a different $\frac{1}{2}$ of the in-fold training data.  This works out to $\frac{4}{5} \times \frac{1}{2} = \frac{2}{5}$ of the total available training data.

The subsampling only serves to diversify the  trees fit in a single boosted model, it plays no role in evaluating the model.  The curves pictured are the average out-of-fold error, with the average taken over the five full boosted models created during cross validation.

How many models does gbm fit?


Array de numeros com quantidade variavel Java Android

Question: Estou fazendo um programa para Android e quero fazer um Array de inteiros, porem necesito definir a quandidade de numeros com uma variavel que tem 3 opcoes de valores: 20, 50 e 100.
Tentei usar o codigo abaixo:
private int[] listNumbers1 = new int[maxNumber];

    for (int number=0; number<maxNumber; number++) {

    listNumbers1[number] = number+1;

}

Answer: O seu código só vai apresentar problemas dependendo de onde você posicionar a variável listNumbers1.
Basicamente, você precisa posicioná-la no escopo de classe, se caso quiser manter o modificador de acesso private, e também pode colocá-la em um método, mas já não poderia usar o modificador private, já que ela agora pertence ao método.
public class MainScreen extends Activity {

    private int[] listNumbers1;

    @Override
    public void onCreate(Bundle state) {
        // super....

        int maxNumbers = 50; // Inicialize a variável aqui
        listNumbers1 = new int[maxNumbers]; // crie sua lista utilizando a referência da variável maxNumbers... que já foi inicializada

        for (int number = 0; number < maxNumbers ; number++) {
            listNumbers1[number] = number+1;
        }
    }
}

O código acima deve funcionar normalmente. Você também pode criar a lista listNumbers1 dentro do método onCreate(), se caso preferir que ela seja local. Mas lembre-se que, neste caso, a keyword private deve ser removida.
Comment: Vou verificar se resolve, o mais estranho é que esta dando um erro nessa parte do codigo "number < maxNumber; number++" diz que maxNumber e number++ sao classes vazias, mas eles sao variaveis!
Comment: acredito que tenha sido pq eu coloquei como maxNumber ao invés de maxNumbers... errei ao digitar o codigo


Dropbox API Android

Question: This question would be related mostly to Android, however it is a little more general.
I can upload and download files using getFile and such API calls, however, I am trying to access a directory which exists already on Dropbox and list it's content.
Using the API, I would like to be able to reference the directory at path '/path/to/dir/' and list all the Entry objects inside it using Entry.contents.
I've tried this and it doesn't work:
Entry dir = new Entry();
dir.path = "/path/to/dir";
Log.d(TAG, "isDir ? " + Boolean.toString(dir.isDir));
for (Entry entry : dir.contents) {
    Log.d(TAG, entry.filename());
}

The directory is not empty. isDir returns false and no filenames are printed.
Is there a way to do this, or do I need to use the search method?
All I want is the list of files in an existing directory.
Thanks a lot
Answer: This can be done with the metadata function:
String path2Dir = "path/to/dir";
Entry dir = mDropboxApiInstance.metadata(path2Dir, null, true, null);
List<Entry> contents = dir.contents;
for (Entry dropboxFile : contents){
  // do stuff with remote file's data
}

Dropbox API Android


Custom node access control not working with access filter?

Question: In some of mine content types I have checkbox field "Content protect". If checked that node should be visible only to registered user. If not checked - visible to everyone:
function hook_node_access($node, $op, $account) {

  // If $node is a string, the node has not yet been created. We don't care
  // about that case.
  if (is_string($node)) {
    return new AccessResultNeutral();
  }
  if ($node->hasField('field_content_protect')) {
    $protected = ($node->field_content_protect->value == 1) ? TRUE : FALSE;
    $userId = $account->id();
    if ($protected && $userId == 0) {
      return new AccessResultForbidden();
    }
  }
  return new AccessResultNeutral();
}

And this works well when I try to access node directly. If it's protected anonymous users can't access it.
Now, I have a view that lists some of those nodes. I want to apply same logic and to exclude protected nodes for anonymous users. So in my view I added filter:
Content access: Access

But it's not working as expected. For authenticated users content is there, but for anonymous users simply whole block content is missing?!? Nodes that don't have this "Content protect" field checked are also not listed?!? Why is that? This filter has no options/settings.
I do have other option, to duplicate view display, check directly the field and display first or second block view depending on user, but this solution with Content access filter looks more elegant.
Answer: Lists like views will not be passed through hook_node_access(), as this would create too much overhead. Views does a query on the database to get the results. hook_node_access() is run in PHP, so these won't work (easily/well/efficently) together.
To deal with lists, you will need to create a grant system, using hook_node_access_records() and hook_node_grants(). This system writes to the {node_access} table in the database, and when a list is created, the database query is cross-referenced with that table.
hook_node_access_records() is called when a node is saved. Modules that implement this hook can set up various states by which the node is allowed to be accessed.
hook_node_grants() is then called when the node is viewed/updated/deleted. A set of potential grants is created based on the current environment, and these are compared with the states created in hook_node_access_records(). If there is a match, access is provided.
In your case, hook_node_access_records() should create a state whereby if the node has the field field_content_protect, then a state should be created upon which view access can be either granted or denied in hook_node_grants(). Example:
function MODULE_node_access_records(\Drupal\node\NodeInterface $node) {
  if ($node->hasField('field_content_protect')) {
    $grants = [];

    $grants[] = [
      'realm' => 'MODULE_protect_content',
      // This is set to 1. In hook_node_grants(),
      // A value will be created based on the user's
      // logged in state, and compared to this value.
      'gid' => 1,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
    ];

    return $grants;
  }
}

The above sets up a state, whereby if a grant is created for the realm MODULE_protect_content that has a value of 1, the user should be granted view access. The next thing is to implement hook_node_grants() and create a grant based on the current user's status.
function MODULE_node_grants() {
  $current_user = \Drupal::currentUser();
  $grants = [];

  // This will set a value of 0 (zero) or 1 (one)
  // for the realm MODULE_protect_content. If the
  // value is 1 (authenticated user) the user will
  // be provided view access to the node. Note
  // that an array of values must be passed for
  // realms.
  $status = (int) $current_user->isAuthenticated();
  $grants['MODULE_protect_content'] = [$status];

  return $grants.
}

For the above code, a grant is created based on the logged in status of the current user. If they are logged in, $status will equal 1, which is compared with the state provided in hook_node_access_records() providing access to the user.
You could actually alter the above hook_node_grants() to only return a grant if the user is logged in. I'm not sure which one would be more efficient. I suspect the code below may be:
function MODULE_node_grants() {
  $current_user = \Drupal::currentUser();

  if ($status = (int) $current_user->isAuthenticated()) {
    $grants = [];
    // This will set a value of 1 (one)
    // for the realm MODULE_protect_content, which
    // matches the state created in
    // hook_node_access_records(). Note that
    // an array of values must be passed for
    // realms.
    $grants['MODULE_protect_content'] = [$status];

    return $grants.
  }
}


Como trabalhar com media queries CSS?

Question: Gostaria de uma informação sobre como usar media queries.
Como faço para definir media de um site nas abaixo?

2560 x 1440
2560 x 1080
1920 x 1080
1366 x 768
1280 x 1024
1280 x 768

Sendo que meu site é estendido a tela toda, ele é um layout que o height não desce fazendo barra lateral, e eu puxo a media pelo height.
Exemplo:
@media screen and (min-height:768px) and (max-height:1080px){
    ...
}

Usar os valores 2560 x 1440, 2560 x 1080, 1920 x 1080, 1366 x 768 e 1280 x 768 causa conflitos no media.
Como resolver?
Comment: Uma observação para outros users: se o site rola na vertical (que não é seu caso, pelo texto), você deve usar o `width` para fazer as queries, e não o `height`. Só faz sentido calibrar o media na vertical para coisas que tenham rolagem horizontal, (ou nenhuma, como na pergunta) ou para elementos específicos da página como navegação, etc, e não para o layout todo. Em casos extremos, dá pra usar juntos o width e o height no mesmo query, mas geralmente é exagero. TALVEZ no caso da pergunta em específico, seja a solução.
Answer: Separe as medidas horizontais e vericais de cada elememnto em suas respectivas queries horizontais e verticais:
@media screen and (min-width:1280px)
   ... aqui voce põe larguras e posições horizontais dos elementos ...
   #minhadiv {width: 400px; left: 10px;}
}

@media screen and (min-width:1366px)
   ... aqui voce põe larguras e posições horizontais dos elementos ...
   #minhadiv {width: 450px; left: 15px;}
}

@media screen and (min-width:1920px)
   ... aqui voce põe larguras e posições horizontais dos elementos ...
   #minhadiv {width: 600px; left: 20px;}
}

@media screen and (min-height:768px)
   ... aqui voce põe alturas e posições verticais dos elementos ...
   #minhadiv {height: 200px; top: 10px;}
}

@media screen and (min-height:1080px)
   ... aqui voce põe alturas e posições verticais dos elementos ...
   #minhadiv {height: 300px; top: 20px;}
}

Se precisar de alguma combinação especial, basta usar as duas medidas juntas, mas cuidado que, ao ser muito específico, fica mais complicado de localizar problemas:
@media screen and (min-width:1366px) and (min-height:1080px)
   #minhadiv {width: 200px; height: 300px; left:80px; top: 20px; color:#eee ... }
}

Como trabalhar com media queries CSS?


What file access problems does the "You are about to change permissions on the root directory of the startup disk..." warning refer to?

Question: In an AD environment as a local admin to a server, I went to give a colleague full permissions to a drive (right-click the drive, Security, Edit, add him and give him some rights) temporarily while waiting for him to be added to the correct AD group, and got this warning:

You are about to change permissions on the root directory of the startup disk. This can reduce the security of your computer and cause users to have problems accessing files. Do you want to continue?

I get the first part (security), but what is "cause users to have problems accessing files" talking about? Is that a catch-all in case the change I'm making reduces someone's access to the drive, or...?
Answer: I think it means user with full permissions of hdd will also has read permission on all file on that hdd, this may consider as insecure.  The user can also change some permisson on files on that hdd so other users may not able to access them. This situation can consider like give someone sudo permisson on linux.


"Invalid column name" thrown for Spring Data Native JPA Query

Question: I have been trying to fix this for a long time and have tried numerous solutions I've found here today and yesterday and still have not been able to solve my problem. This was working fine and then suddenly stopped and I can't get it to go back to working.
I have a Customer entity and it is mapping to a native sql query. I have tried everything from @Column annotations to setting the physical/implicit naming strategies, etc.
When I run the query directly against the mySQL DB it returns the data I would expect it to in the correct format.
My native query repo looks like this:
public interface CustomerRepository extends JpaRepository<CustomerEntity, Integer> {

@Query(value = "SELECT * FROM (SELECT CUSTOMER_ID AS customerId, CUSTOMER_NAME AS customerName FROM CUSTDBO.CUSTOMERS)", nativeQuery = true)
List<CustomerEntity> getCustomerData();

}

My entity looks like this:
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class CustomerEntity {

@Id
private int customerId;

private String customerName;
}

Even though this was working before, now when I try to retrieve the data I get this error:
java.sql.SQLException: Invalid column name

The stack trace doesn't point to any class nor reveal exactly what the error is. I turned on Hibernate logging to see the query being executed and this is what it shows:
Hibernate:
SELECT
    *
FROM
    ( SELECT
        CUSTOMER_ID AS customerId,
        CUSTOMER_NAME AS customerName
    FROM
        CUSTDBO.CUSTOMERS )

Complete stack trace:
    2023-02-21 18:28:33.292  WARN 8832 --- [nio-8080-exec-1]
    o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 17006, SQLState:
    99999
    2023-02-21 18:28:33.292 ERROR 8832 --- [nio-8080-exec-1]
    o.h.engine.jdbc.spi.SqlExceptionHelper   : Invalid column name
    2023-02-21 18:28:33.322 ERROR 8832 --- [nio-8080-exec-1] o.a.c.c.C.[.[.    [/].[dispatcherServlet]    : Servlet.service() for servlet     [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is
    org.springframework.orm.jpa.JpaSystemException: could not execute query; nested exception is org.hibernate.exception.GenericJDBCException: could not execute query] with root cause

    java.sql.SQLException: Invalid column name
        at

 oracle.jdbc.driver.OracleStatement.getColumnIndexPrimitive(OracleStatement.java:4257) ~[ojdbc8-18.104.22.168.jar:18.104.22.168.0]
        at oracle.jdbc.driver.OracleStatement.getColumnIndex(OracleStatement.java:4215) ~[ojdbc8-126.96.36.199.jar:126.96.36.199.0]
        at oracle.jdbc.driver.InsensitiveScrollableResultSet.findColumn(InsensitiveScrollableResultSet.java:299) ~[ojdbc8-18.104.22.168.jar:184.108.40.206.0]
        at oracle.jdbc.driver.GeneratedResultSet.getString(GeneratedResultSet.java:662) ~[ojdbc8-220.127.116.11.jar:18.104.22.168.0]
        at com.zaxxer.hikari.pool.HikariProxyResultSet.getString(HikariProxyResultSet.java) ~[HikariCP-4.0.3.jar:na]
        at org.hibernate.type.descriptor.sql.VarcharTypeDescriptor$2.doExtract(VarcharTypeDescriptor.java:62) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:257) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:249) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.loader.Loader.getInstanceClass(Loader.java:1949) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1732) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.loader.Loader.getRow(Loader.java:1624) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:748) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.loader.Loader.getRowsFromResultSet(Loader.java:1047) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.loader.Loader.processResultSet(Loader.java:998) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.loader.Loader.doQuery(Loader.java:967) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:357) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.loader.Loader.doList(Loader.java:2868) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.loader.Loader.doList(Loader.java:2850) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2682) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.loader.Loader.list(Loader.java:2677) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:338) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:2186) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.internal.AbstractSharedSessionContract.list(AbstractSharedSessionContract.java:1204) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.query.internal.NativeQueryImpl.doList(NativeQueryImpl.java:177) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1617) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.hibernate.query.Query.getResultList(Query.java:165) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
        at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:128) ~[spring-data-jpa-2.7.0.jar:2.7.0]
        at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:90) ~[spring-data-jpa-2.7.0.jar:2.7.0]
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:156) ~[spring-data-jpa-2.7.0.jar:2.7.0]
        at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:144) ~[spring-data-jpa-2.7.0.jar:2.7.0]
        at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.7.7.jar:2.7.7]
        at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.7.7.jar:2.7.7]
        at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:160) ~[spring-data-commons-2.7.7.jar:2.7.7]
        at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:139) ~[spring-data-commons-2.7.7.jar:2.7.7]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.25.jar:5.3.25]
        at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:81) ~[spring-data-commons-2.7.7.jar:2.7.7]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.25.jar:5.3.25]
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) ~[spring-tx-5.3.25.jar:5.3.25]
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) ~[spring-tx-5.3.25.jar:5.3.25]
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.25.jar:5.3.25]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.25.jar:5.3.25]
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.25.jar:5.3.25]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.25.jar:5.3.25]
        at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:145) ~[spring-data-jpa-2.7.0.jar:2.7.0]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.25.jar:5.3.25]
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.25.jar:5.3.25]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.25.jar:5.3.25]
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.25.jar:5.3.25]

If anyone can offer any insight it would be much appreciated.
Comment: Did you try `SELECT * FROM CUSTDBO.CUSTOMERS`?
Comment: Yes, but that returns all columns. I specifically only want those two (CUSTOMER_ID and CUSTOMER_NAME)
Comment: looking at your @Entity class, it seems you only have those 2 columns. Please specify the table structure and column names(or the naming strategy)
Comment: Yes, but that should be ok as long as I'm only selecting those two columns, correct? The query only returns customerId and customerName.
Comment: depends on the naming strategy you are using in your properties file. If you are trying using ImplicitNamingStrategy then your columns in DB will be stored as columnId (not column_id) and hence you would get `java.sql.SQLException: Invalid column name`. If you are using PhysicalNamingStrategy then it would store it as column_id
Comment: Table definition:

The table contains the following definition:

    CREATE TABLE CUSTDBO.CUSTOMERS
     (
      CUSTOMER_ID NUMBER NOT NULL,
      CUSTOMER_NAME VARCHAR(100) NOT NULL,
             CUSTOMER_ZIP VARCHAR(10) NOT NULL,
      CUSTOMER_LEVEL INT NOT NULL,
      PRIMARY KEY(CUSTOMER_ID)
     );
Comment: I have tried it with and without the naming strategies. Implicit and physical.
Comment: Even if there were some way to see the result after Hibernate executes the query it would help but it won't tell me anything other than 'Invalid column name'
Comment: Please provide the complete stack trace. Which column are you getting error for?
Comment: It doesn't specify. I can't even see the result of the query. I've added the stack trace above.
Comment: Can you try removing `@Entity` and `@Id` from that class once?
The reason I am asking for removing it is, I referred to this [page](https://www.baeldung.com/jpa-entities#entity) where it clearly says, "Entities in JPA are nothing but POJOs representing data that can be **persisted** to the database." In your case we are not persisting, we are just retrieving it.
And if you want an entity, I think you should map all columns to @Entity. Additionally, You may use `@Transient` on columns that you don't want to be persisted.
Comment: Without entity and id, the app will not start. My repository expects CustomerEntity to be a bean.
Comment: What I'm completely lost on is why this worked and with no changes suddenly stopped working.
Comment: Do you mean it worked? If yes, then I might explain the reason ... and if it failed again, whats the new error?
Comment: it failed with the expected error, no bean of type found (@Entity tags it as a bean). If I remove @Id it complains that there is no identifier on the entity. I know it has to be an entity in order for the queried data to be turned into CustomerEntity so I have to keep the annotations. This is a very silly problem and it is making doing something very simple into something very complicated.
Answer: All derived tables require an alias, in most flavors of SQL, so your native query should be:
SELECT *
FROM (
    SELECT CUSTOMER_ID AS customerId,
           CUSTOMER_NAME AS customerName
    FROM CUSTDBO.CUSTOMERS
) t;

But the subquery doesn't even look necessary, so you may simply use:
SELECT CUSTOMER_ID AS customerId,
       CUSTOMER_NAME AS customerName
FROM CUSTDBO.CUSTOMERS;

Your updated Java code:
public interface CustomerRepository extends JpaRepository<CustomerEntity, Integer> {
    @Query(value = "SELECT CUSTOMER_ID AS customerId, CUSTOMER_NAME AS customerName FROM CUSTDBO.CUSTOMERS", nativeQuery = true)
    List<CustomerEntity> getCustomerData();
}

Comment: Thank you for the reply. I tried it with both an alias and without the subquery and am getting the same result. I found that by adding a WHERE clause that left me with 0 results (WHERE 1 = 2) it gave me an empty result back with no error but when there are results something in the column mapping is failing.


New or used digital piano?

Question: My daughter (early teens) would like to learn piano, and we are on a very limited budget with only a car to move things.  I want her to start with 88 keys and an authentic feel, just in case she wants to stick with it.
I am looking at a couple of different options:
First, I can get an older used Roland 400 for about $200 to $250 locally.
Secondly, I can afford an Alesis Recital 88-Key Beginner Digital Piano from Amazon.  The cost with taxes, etc will be $350.
Much more than that will be outside of our budget.
Can someone please give me some advice?
Thank-you.
Comment: Used kawai es-100 - best purchase i ever made... you may find one used for $400 if you're lucky
Answer: Do you mean Roland rp 400? if yes then 200 bucks is a seriously good deal as it retails for over 1.5k.
Regardless, Roland's probably a better product. It's the stronger brand and you're saying you can get it cheaper. So yeah, I'd go with the used. A beginner should always go for the cheapest option just to see if they even like the aspect of playing a piano.
Also, if I may add. Try to find instructors that will teach your daughter pop music, music theory, how to play by ear and use chord progressions.
I find that in piano there's generally two types of teachers: those that teach how to read classical music from sheet music, and those that teach rock music, pop music, scales, chords / music theory, etc. Go for the latter. In my childhood I spent 4 years learning how to read classical music from an old lady down the street who went to Julliard. it was the biggest pain in the ass I ever went through. Not to mention completely unhelpful. I didnt learn a single thing about music throughout that period just a few Chopin pieces that I could care less about. Granted, some people commit their entire lives to the classical route but ask your daughter if she wants to play classical or everything else (aka what she hears on the radio).
Now that I've revisited piano I just play by ear and improvise with music theory. That's alot funner. I dont even attempt to read music anymore. Everything can be figured out by ear. just don't get a teacher that just emphasizes learning how to read classical sheet music. they suck the life out of music and turn you into a drone. my former teenage self is begging you.
Comment: That's extremely helpful.  Thanks so much.  I will look into the Roland. Right now, my daughter is downloading sheet music for popular songs and plunking them out on the piano at school, I will look for an instructor who can help her to do that properly.  Thanks for the advice.
Comment: Wait - I just looked at this.  It is a much, much older Roland.  It's the HP-400.  Is that still the better choice here?
Comment: hmm yeah, hp-400 is a dinosaur. I think it's from the 1980s. I'd be a bit iffy on that. The new Alesis would probably be better. That said, maybe there's a way for you to check out the two and compare how their keys feel? At the end of the day, as long as it just works then it'll serve its purpose as a beginner's instrument. You'll be buying another one anyway within a few years esp if you really like it. Also tell your daughter to check out videos by Karen Ramirez on youtube, especially everything she has to say about playing by ear. Sheet music is soooo boring.
Comment: also if I were you I'd go to guitarcenter (if you live in the US) and just talk to sales associates just to get more info on digital pianos, like what to look for when buying one, etc. I do think you're doing good by leaning towards weighted keys though. synthesizer keys feel so cheap compared to pianos/digital pianos.
Comment: also the Alesis supports USB/Midi which I doubt that old Roland does. this might be important since your daughter might want to connect the piano to her laptop in order to record digital music.
Comment: yeah.. if it were me I'd get the recital. it's more compact and newer. and I saw it's the #1 selling digital piano on amazon with good reviews. it's 200 bucks so that's cheap as dirt too.
Comment: "I saw it's the #1 selling digital piano on amazon" - Yeah, and if I wanted to get the "best quality books", I would obviously buy them from Steinway, not Amazon ;)
Comment: Yup, the HP-300 was the first ever Roland digital piano that had a MIDI interface. First marketed in 1983. You really don't want a 35-year-old design, unless you are into collecting vintage electronics rather than getting an instrument for a teenager to learn on. https://www.roland.co.uk/digital_piano_history
Answer: The HP 400 has the old 5-pin MIDI jacks.  You'll need a MIDI-USB box to use it with a computer.  The Alesis Recital has a 'semi-weighted' keyboard. Not quite piano feel.   But then, nothing except a real piano ever does.  And many real pianos have a quite unpleasant action, particularly if old or poorly maintained.
The Alesis doesn't seem to come with a sustain pedal (strange, for something sold as a piano), so add that to the price.  Sampling technology has come on quite a bit since 1983, so the Alexis will sound more like a piano that the Roland.
Is there an 'Alesis Recital Beginner' model that's different to the 'Alesis Recital' ?  I can't find mention of it.
On the whole, get the Alesis.
Comment: Well, if you go to the Alesis web site, the spec certainly *looks* like a "beginner instrument". Only one piano sound patch, only 4 alternatives with incredibly vague names like "organ!!!",  no sostenuto/una corda pedals, (even the sustain pedal is an optional extra,) etc, etc...  But at least you know what you are getting if you buy new. With an ancient second hand instrument, you have no idea what condition the *mechanical* parts are in (i.e. the keyboard itself), and you probably can't even find any reviews or specifications without a lot of digging.
Comment: My Bechstein upright must be a  'beginner' model then.  Just one piano sound.

New or used digital piano?


send and receive SMS from server to webapp

Question: I am in Kenya and the twilio pricing is very expensive here. I would like to send and receive sms messages, store them in a database and display them on a web app. Is it feasible to build this with node.js? How could I get a framework like express to send/receive text messages?
Answer: Well you'd still need some sms-gateway, irrespective if you're using node.js or something else.
Google: "sms gateway nodejs" for some stuff
Answer: I did some searching and found a similar service called SMSified, that seems to be priced more reasonably.  There is a node module that hasn't been updated in 3 years, but that might give you a good starting point.
Another one that is explicitly free during development/testing is Tropo.  This one has a more-recently-updated node module.
I haven't used either of these myself, but hopefully one of them should be what you're looking for.
Another option is to use an SMS gateway provided by the carriers.  Typically you can send an email to [number]@[gateway-address].  For example, to send a text to 123-456-7890 on AT&T's network, you would simply send an email to firstname.lastname@example.com.  Take a look here for a list of common carrier's gateway addresses.
If you already have email integrated with your app, this might be very easy to implement.  The only downside is that it would require users to specify their carrier before you can send them an SMS message.
Comment: on SMSified.com, it says it is powered by Tropo
Comment: @palanik didn't notice that! Interesting.


Complex SVN Permissions

Question: I am looking for a SVN setup that allows by repository permissions without using SSH. At the moment we have an SVN server with several repos and are accessing it through the SSH+SVN protocol. I created a UNIX group for each repository and add the users who needed access to that group. Essentially I am using the UNIX file permissions for access control. However we have encountered an issue when we moved to Windows 8 and the Cisco Any Connect Client for VPN access where we cannot open SSH tunnels, for whatever reason I don't know, networking and VPN is not my area of expertise. Anyway I have been asked to look into an alternative setup for our SVN server.
As far as I know the other protocols available are SVN, HTTP, and HTTPS. At one point we were using HTTP with basic_auth but anyone who had a password could read/write to all repos. We want to lock down access to a by repository basis. Is there anyway to do this with SVN using the SVN or HTTP protocol. We also want it hands off as much as possible for management purposes, meaning I don't want to have to maintain a vhost and password file for every repo. Any advice or suggestions are appreciated. We have moved to Git for new projects but still have several in SVN that developers don't want to move.
FYI, the server is Linux, CentOS 6.4 so preferable a Linux solution.
Okay So I tried setting up path based authentication but I'm running into some problems so I hope someone can help.
Here is my svn.conf file from /etc/httpd/conf.d/
LoadModule dav_svn_module       modules/mod_dav_svn.so
LoadModule authz_svn_module     modules/mod_authz_svn.so

<VirtualHost *:80>

        ServerName svn.test.net
        ServerAdmin admin.test.net
        ServerSignature Off

        <Location /svn>

                DAV svn
                SVNPath /home/svn/repos
                #SVNListParentPath on

                AuthType Basic
                AuthName "Test SVN Server"
                AuthUserFile /home/svn/svn-passwd

                AuthzSVNAccessFile /home/svn/svn-access

                Require valid-user

        </Location>

        ErrorLog /var/log/httpd/svn_error.log
        CustomLog /var/log/httpd/svn_access.log combined

</VirtualHost>

The authentication seems to be working fine however no mater what path I enter it always seems to try to read from /home/svn/repos/format
[Sun Jan 19 06:19:30 2014] [error] [client 192.168.17.117] (20014)Internal error: Can't open file '/home/svn/repos/format': No such file or directory
[Sun Jan 19 06:19:30 2014] [error] [client 192.168.17.117] Could not fetch resource information.  [500, #0]
[Sun Jan 19 06:19:30 2014] [error] [client 192.168.17.117] Could not open the requested SVN filesystem  [500, #2]
[Sun Jan 19 06:19:30 2014] [error] [client 192.168.17.117] Could not open the requested SVN filesystem  [500, #2]

If I enter http://svn.test.net.svn.repo1 or http://svn.test.net.svn.repo2 I get the same message in the error log.
All the repos are stored at /home/svn/repos. Apache has ownership of the entire /home/svn directory recursively with rwx permissions. Is there something I'm missing or configured wrong?
In my svn-access file I have something like this
[groups]
testgroup = testuser

[/]
* = r

[/repo1]
@testgroup1 = rw

Comment: Holy blob of text, batman. Perhaps edit your question to add a few paragraph breaks. :)
Comment: I cleaned it up a little :)
Answer: The most flexible way to do this would be to move back to Apache with mod_dav_svn and basic auth, and use AuthzSVNAccessFile to enforce access controls - this allows assigning users no permission, read, and read/write based on repo and logical path within the repo.
See here for more info.
Comment: Thanks, I'll look into this and if it works out for us I will mark this as the accepted answer.
Comment: I ran into a snag trying to setup path based permissions. I updated my question. I'm hoping I just missed something
Comment: @greyfox Looks like you'll want to swap `SVNPath` for `SVNParentPath` - `SVNPath` implies that there's only one repo at the exact location you're pointing to, while `SVNParentPath` is for a directory containing repos as you have.

Complex SVN Permissions


Comparar url atual com href

Question: O meu cenário é o seguinte, eu tenho 3 links e preciso identificar qual deles é o mesmo que a url atual.
Menu 1
Menu 2
Menu 3

A maneira que utilizei para comparar se a url é a mesma do href foi essa:
var url = window.location.href;
$('a').each(function(){
  var href = $(this).attr('href');
  if(url===href){
    console.log('works');
  }
});

Porém não funciona, cheguei a fazer um teste jogando o valor exato na variavel url e dá certo. Queria saber se eu devo utilizar o window.location.href mesmo ou ele dá algum problema na hora da comparação.
Esse valor do href é só um exemplo, estou tentando comparar os valores completos, por isso o uso do window.location.href
    Menu 1
    Menu 2
    Menu 3

Toda vez que eu estiver na página http://localhost/teste/index.html eu preciso adicionar uma classe ao a correto.
Uma outra alternativa que tentei foi o seletor $(".nav a[href*='/sobre']").css('color','red');, só que no lugar do 'sobre' tentei colocar a variável url, porém sem sucesso.
Answer: var url = window.location.pathname;
$('a').each(function(){
  var href = $(this).attr('href');
  if (url === href){
    console.log('works');
  }
});

var url = window.location.href; -- pega a url toda.
Então você utilizando === significa que os dados valores precisam ser exatamente iguais.
var url = window.location.pathname; -- pega só o que vem depois do host.
Exemplo: www.seusite.com.br/teste.html, utilizando o window.location.pathname ele vai retornar só teste.html
Espero ter ajudado!
Comment: Bruno, vc poderia explicar um pouco mais sua resposta?
Comment: var url = window.location.href; -- pega a url toda, então você utilizando === significa que os dados valores precisam ser exatamente iguais. Já o var url = window.location.pathname; -- pega só o que vem depois do host. Exemplo: www.seusite.com.br/teste.html, utilizando o pathname ele vai retornar só teste.html
Comment: Bruno, clica no botão editar, e coloca a explicação na resposta :)
Comment: Feito! Funcionou?
Comment: @Bruno, no meu caso eu preciso que a url seja exatamente igual a href, por isso estou usando o window.location.url
Comment: ficou melhor Bruno +1

Comparar url atual com href


Is there a mapping from an icosahedron to a sphere?

Question: I recently found a mapping from a cube to a sphere (see Can someone please explain the cube to sphere mapping formula to me?), but is there also such a mapping from an icosahedron to a sphere? If so, is there also a way to map the sphere back to an icosahedron?
Comment: Yes there is a homeomorphism from the icosahedron to the sphere, which is given by taking any point on the sphere, considering the line through the point and the origin, and mapping to the intersection of that line with the icosahedron. Assume both are centered at the origin, of course. The inverse map is exactly the same, just replace the word icosahedron with sphere and vice versa.
Comment: This mapping basically implies that the sphere, the icosahedron, and projective space are all homeomorphic.
Comment: The ray that starts from the center of the icosahedron (assuming it is inscribed in the sphere) defines a bijection between both geometric objects. Any one icosahedron can be applied to the embedded icosahedron. So you can get a composite function that answers your problem.
Answer: Contrary to the explanatiin there, I suppose a simple radial scaling
$$\begin{pmatrix}x\cr y\cr z\end{pmatrix}\mapsto \begin{pmatrix}x/\sqrt{x^2+y^2+z^2}\cr y/\sqrt{x^2+y^2+z^2}\\z/\sqrt{x^2+y^2+z^2}\end{pmatrix}$$
would be good enough (esp. as the icosahedron is already close to a sphere.
For a map sphere $\to $ icosahedron, I would collect the unit normal vectors for the faces, then determine which of these has the largest scalar product with the given point on the sphere, then divide the point by that scalar product. (This maps to the circumscribed, not inscribed icosahedron, if that matters)
Comment: Isn't there still some distortion left, then? The cube to sphere mapping was made to minimize distortion. http://g2f.nl/0tzgwme.png here, points E, F, and G get projected onto the circle. On the triangle, |EF| = |FC|, but on the circle |EF| > |FC|, which is not what I want


Can we exclude specific character in alphanumeric javascript regex?

Question: I have alphanumeric regex /^[A-Za-z\d]{8}$/
Case: I want skip exclude specific character from it lets say E, P and S.
Could anyone enhance this regex to support case I mentioned above
Comment: Though I understand Javascript is not one of them, some languages permit the regex `^[a-zA-Z0-9&&[^EPS]]{8}$`.
Answer: You can change your a-zs to only include a range of the characters you want to permit:
/^[a-df-oqrt-z\d]{8}$/i

Another method of doing the same thing is to negative lookahead for the blacklist while using a-z:
^(?:(?![eps])[a-z\d]){8}$

Comment: Are you sure it's `t-v` ?
Comment: it worked, thanks for quick response.
Answer: You can use range like this
/^[A-DF-OQRT-Z\d]{8}$/i

^ - Start of string
^[A-DF-OQRT-Z\d]

A-F - Can match any character from A to F
F-O - Can match any character from F to O
QR - Match character Q, R
T-Z - Can match any character from T to Z

let matcher = (str) =>{
  let pattern = /^[A-DF-OQRT-Z\d]{8}$/i
  return pattern.test(str)
}

console.log(matcher('abcdeh123'))
console.log(matcher('abcdh123'))


Compiling FastCGIWrap fails on slackware (nginx cgi support)

Question: I'm currently trying to get nginx to work with cgit which uses cgi.
I know nginx doesn't support cgi directly but it appears you can support it indirectly via FastCGIWrap.
The link above is pretty self explanatory but I'm having a problem with compiling the program. What I've done so far:

Installed libfcgi-2.4.0
cd fcgiwrap && autoconf -i
When I run ./configure I get this output
checking for gcc... gcc
checking for C compiler default output file name... a.out
checking whether the C compiler works... yes
checking whether we are cross compiling... no
checking for suffix of executables...
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking for FCGX_Init in -lfcgi... yes
checking how to run the C preprocessor... gcc -E
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking fcntl.h usability... yes
checking fcntl.h presence... yes
checking for fcntl.h... yes
checking limits.h usability... yes
checking limits.h presence... yes
checking for limits.h... yes
checking for stdlib.h... (cached) yes
checking for string.h... (cached) yes
checking for unistd.h... (cached) yes
checking for stdbool.h that conforms to C99... yes
checking for _Bool... yes
checking for pid_t... yes
checking for size_t... yes
checking for ssize_t... yes
checking vfork.h usability... no
checking vfork.h presence... no
checking for vfork.h... no
checking for fork... yes
checking for vfork... yes
checking for working fork... yes
checking for working vfork... (cached) yes
checking whether lstat dereferences a symlink specified with a trailing slash... yes
checking for stdlib.h... (cached) yes
checking for GNU libc compatible malloc... yes
checking for strchr... yes
checking for strdup... yes
checking for strrchr... yes
checking for dup2... yes
checking for putenv... yes
checking for select... yes
checking for setenv... yes
checking for strerror... yes
configure: creating ./config.status
config.status: creating Makefile
config.status: WARNING:  'Makefile.in' seems to ignore the --datarootdir setting
config.status: error: cannot find input file: config.h.in

After this I can't do make -s && make -s install because it can't find config.h.in.
Is there another way to install this on slackware 12.2 or is there any package of it or this program is meant only for Debian/Ubuntu like distros?

Edit:
automake returns:
Useless use of /d modifier in transliteration operator at /usr/share/automake-1.10/Automake/Wrap.pm line 60.
configure.ac: no proper invocation of AM_INIT_AUTOMAKE was found.
configure.ac: You should verify that configure.ac invokes AM_INIT_AUTOMAKE,
configure.ac: that aclocal.m4 is present in the top-level directory,
configure.ac: and that aclocal.m4 was recently regenerated (using aclocal).
automake: no `Makefile.am' found for any configure output

Comment: Please double-check: in the question you wrote `autoconf -i` while the instructions ask for `autoREconf -i`. If yes, then I'd suggest to reach Grzesiek, the author of the package, for his insight.
Comment: Try to re-unpack the distro but this time omit `autoconf` step.
Comment: I'd usually do that but in this case, if you download the archive, you'll see there's no `./configure` script. You can't do `make && make install` because it fails with `make: *** No targets specified and no makefile found.  Stop.`
Comment: then, try doing `automake` before `autoconf`.
Comment: Question updated with the result..
Comment: have you tried `autoreconf -i`?
Comment: Yes I have. But I forgot to put it in the question. Sorry 'bout that.
Comment: `autoreconfig` definitely did the work! Thanks for the help! :)
Answer: Autoreconf's option -i should generate missing autotool files using library defaults.


What is the expected number of bins with at least one ball?

Question: Consider an random variable $X$, that follows a binomial distribution with parameters:

$n=B$ (i.e. the number of attempts is $B$)
$p=P$ (i.e. the probability of having a success is $P$)

So, $X \sim Bin(B,P)$.
Then, we read $X$.
After that, we create exactly $X$ bins and $X$ balls.
Finally, we toss the uniformly at random to the bins.
All the tosses are independent from each other.
How can I obtain lower bounds on the expected number of bins with at least one ball?
Thanks in advance.
Comment: Can you find an expression for this expectation under extra condition $X=k$?
Comment: @drhab for an already known $X$, yes. My problem is exactly for a random $X$.
Answer: Suppose $X = m$. Let $Y_{i}$ denote a random variable, such that:
$$ Y_{i} = \left\{\begin{matrix}
1 & \text{if the }i\text{-th bin has at least one ball} \\
0 & \text{otherwise}
\end{matrix}\right.$$
Then, we have
$$
\Pr[Y_i = 0 \mid X = m] = \left(\frac{m-1}{m}\right)^m
$$
because all $m$ balls are tossed into other $m-1$ bins.
Therefore,
$$
\Pr[Y_i = 1 \mid X = m] = 1 - \left(\frac{m-1}{m}\right)^m
$$
and
$$
\mathbb{E}[Y_i \mid X = m] = 1 - \left(\frac{m-1}{m}\right)^m \geq 1 - \frac{1}{e}
$$
Let $Z$ denote the number of bins with at least $1$ ball.
Then, by the linearity of the expectation:
$$
\mathbb{E}[Z \mid X = m] = \mathbb{E}[Y_1 + Y_2 + \cdots + Y_m \mid X = m] \geq m\left(1 - \frac{1}{e}\right)
$$
Thus, by the law of total expectation:
\begin{align}
\mathbb{E}[Z] =& \sum_{m=0}^B \mathbb{E}[Z \mid X = m]\cdot\Pr[X=m]  \\
\geq &\sum_{m=0}^B m\left(1 - \frac{1}{e}\right)\cdot\Pr[X=m] \\
=& \left(1-\frac{1}{e}\right) \sum_{m=0}^Bm\cdot\Pr[X=m] \\
=& \left(1 - \frac{1}{e}\right) \cdot\mathbb{E}[X] = \left(1-\frac{1}{e}\right)BP
\end{align}
Comment: Before I accept it, I'll look at it very carefully. Thank you for the answer :)
Comment: @guilhermemtr this is what I had in mind.
Comment: @drhab, nice. I am sorry if my question was not clear enough right away so that you could answer right away as well. But thank you a lot for your help.
Comment: @NP-hard your answer makes sense to me. Let me double check it (I am very careful with these things, since these results are important to me).
Comment: @NP-hard, do you mind if I edit your answer, just to add which theorems and lemmas are used in some of the steps? For newbies like me, that is important.
Comment: @guilhermemtr Please edit the answer if it makes you understand the answer better.
Comment: @NP-hard, does it look ok to you?
Comment: @guilhermemtr Nice. Looks good to me. Thanks for improving the answer.


Using Boolean Module as filter in Views

Question: We are trying to use Boolean module inside Drupal 7 to define a boolean field for a custom content type , news .
the module seems to be enabled without any visible issues . the issue comes when we wish to use that boolean field's data for Filtering in a view.
e.g The boolean field is called editor-choice , in the View we wish to get all news content type that is published and has Editor's choice value to true.  please see below screenshots of the three steps being performed.

kindly assist what can be the possible issue, or if possible, suggest some other plugin that may be used foe this purpose.
Comment: Boolean field is already available in Drupal7. May I ask why you need to use boolean module to achieve that?
Comment: could not find a boolean field by default :) . can you guide by which name it exists.
Answer: If you are using Drupal latest version, boolean field is available by default in core.
Goto your content type => Manage field => Add new field => Select field type

In the manage field configuration, give 'on' value and 'off' value. Here I have given, Yes and No.

In the views filter, select the option you wish to filter. Thats it.
Comment: ok. thank you got it :) . can you also guide in more small thing about Views.. it seems that it is repeating the contents. e.g. currently only one node value was set to true but it is repeating 2-3 times.
Comment: updated the answer. pls check

Using Boolean Module as filter in Views


Como medir a complexidade de um algoritmo?

Question: Eu preciso saber se meu algoritmo atende a demanda do seguinte enunciado:

Implemente um algoritmo com complexidade O(n) que realize o fatorial
  de um número x tal que x pertence aos Naturais.

#include <stdio.h>
/* recebe um inteiro x;
 * retorna o fatorial de x.
*/
int fatorial (int x)
{
if (x == 0)
    return 1;
return x * fatorial(x-1);
}
int main (void)
{
int n;
scanf("%d", &n);
printf("%d\n", fatorial(n));

return 0;
}

Se possível me expliquem como fazer a medição.
Comment: Relacionado: [Definição da notação "Big O"](http://pt.stackoverflow.com/questions/56836/defini%C3%A7%C3%A3o-da-nota%C3%A7%C3%A3o-big-o)
Answer: A medição da complexidade de um algoritmo é tradicionalmente feita em ciências da computação utilizando-se análise assintótica a qual utiliza o que é chamado de notação Big O (o O(n) do qual seu enunciado fala).
Um algoritmo com complexidade O(n) é nada mais que um algoritmo de tempo linear, o que significa que o tempo que ele leva para executar é um reflexo direto do tamanho da entrada de dados que ele utiliza e que esse tempo cresce de forma constante e...linear!
Em termos práticos o desejado pelo enunciado do seu problema é que se digamos seu algoritmo realize uma etapa que leve aproximadamente 1 segundo para calcular a fatorial de 1 o cálculo da fatorial de 2 deveria realizar duas etapas e levar aproxidamente 2 segundos, a fatorial de 3 realizaria três etapas e levaria aproxidamente 3 segundos, e assim sucessivamente, para cada valor acima seu tempo cresce linearmente.
Quanto a seu algoritmo atender a demanda, sim ele atende, isso pode ser confirmado vendo que cada fatorial acima de um anterior gera apenas uma chamada extra a  fatorial sendo que fatorial realiza apenas operações de tempo constante (não vou entrar em mais detalhes aqui pois o assunto é extenso, sugiro que veja os links que usei sobre análise assintótica e Big O).
Answer: A complexidade O(n) (linear) significa que para cada elemento da coleção que precisa manipular, deve haver no máximo um passo no algoritmo.
Você pode determinar a quantidade de passos fazendo um teste de mesa, ou seja, executar mentalmente o algoritmo e ir anotando as mudanças de estado das variáveis e sub-expressões, e ir contando os passos para atingir o objetivo.
Então por exemplo, se pedir o fatorial de 5 pode executar em até 5 passos. Para o fatorial de 8, pode fazer em até 8 passos.
Neste caso "passo" pode ser entendido a chamada à função fatorial.
Outra forma é ativar o debug e ir executando e vendo quantos passos ocorreram.
Mas o cálculo básico do fatorial é conhecido como sendo complexidade O(n) mesmo.
Coloquei no GitHub para referência futura.
Answer: A complexidade de algoritmos pode ser medida de diferentes modos, desde de intuitivamente para algoritmos fáceis, por exemplo, com laços de iteração, porém para algoritmos que envolvam recursão o método mais recomendo e formal, indico que pesquise sobre o Teorema Mestre, o qual envolvem três tipos de notação.


blocked:mixed-content em https chamando iframe sem https

Question: Tenho um site em https e preciso chamar através de um iframe uma página em outro servidor, que infelizmente não tem https.
O Navegador Chrome bloqueia essa requisição por ser fora do https.
(blocked:mixed-content)

Existe como eu conseguir chamar essa página?
Infelizmente acho que vou fechar minha pergunta ou colocar uma própria resposta, pois é impossível fazer o que quero.
Motivo:
https://developers.google.com/web/fundamentals/security/prevent-mixed-content/fixing-mixed-content?hl=pt-br
Comment: Só hoje vi no FB sua mensagem, te adicionei lá. Vou apagar aqui.
Answer: Infelizmente acho que vou fechar minha pergunta ou colocar uma própria resposta, pois é impossível fazer o que quero.
Motivo: https://developers.google.com/web/fundamentals/security/prevent-mixed-content/fixing-mixed-content?hl=pt-br
Pois o conteúdo é considerado como ativo, entrada de texto, iframe é bloqueado por todos os navegadores.


How do I rename an instrument in OpenMPT?

Question:
How do I rename an instrument?
Answer: It's a rather complicated two-phase process that's best explained with the following usage-scenario-logic diagram that applies to at least OpenMPT version 1.27.09.00.
Answer: update: OpenMpt 1.28.00
have you got this one?
there is a new tab insturments between samples and comments.
type in the name. that's it
if not:
go to comments:
chose or type the new name in the upper window
select the instrument in the lower window
finished


Inquiry to Voice Classification

Question: I'm a 24 male who is interested in vocal arts and have yet to receive any formal voice training.  But I would like to know my voice type. Attached are two audio clips of me descending from middle C to as low as I could and ascending from F4 to as high as I could (while trying not to break into falsetto).

https://www.facebook.com/photo.php?v=10151715356814058&l=6528702054606550815

https://www.facebook.com/photo.php?v=10151715360319058&l=3781106173026876953
Apologies for the poor recording device and voice quality.
Answer: First, a disclaimer: Labeling a voice type isn't something that is merely based on range - it's as much an issue of quality and agility (though admittedly less-so for male voices).  Beyond that, you're an untrained singer.  With training, not only would the extremes of your range likely extend, but the relative ease of singing in certain tessituras would be more evident.
That being said, based on your recordings, I think it's pretty safe to say you're a tenor.  It doesn't sound like you have many notes below C3, and the overall quality sounds tenorish to me.  Plus, the fact that you have a decent F4 and G4 without training is not at all typical of lower voice types.
Further training and diagnostic exercises would allow a voice teacher or vocal coach to make more specific qualifications.
Comment: It sounds like it's wanting to slip into a new register, but I wouldn't call it falsetto.  It mostly just sounds tight and strained, and I think with some quality training you could have a really nice high Bb.
Comment: I'm a professional vocal coach/collaborative pianist.  I sing also, but not professionally.
Comment: Thank you for the great advice! I'm wondering if that last high note in my 1st clip is a falsetto? But it sounds neither chesty nor exactly falsetto when I sing it.
Comment: I see. I have just checked and it is D5. I can at most probably go a semitone/full tone higher than that in that same type of vocal production. On other hand, I notice that whenever I try to ascend from F#4/G4  onwards, there is prominent register change in my voice and I have some difficulty coordinating my voice (i.e. it might crack) when I descend from any notes above G#4 to G4.
Comment: Ah, that makes more sense... I'm not near a piano to confirm what pitches you were singing.  A register break is normal around F#4 for the male voice.  Negotiating breaks is tricky for everyone and usually a large part of vocal training will focus on that.
Comment: What makes more sense? :P
Comment: I thought you were singing F4, G4, A4, and Bb4, not up to a D5.  So you were singing higher than I initially thought, which places the register breaks in the expected places and further confirms my guess that you're a tenor.
Comment: I see. You seem knowledgeable in voice. You sing as well:) ?
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/13212/discussion-between-alexy-vincenzo-and-munchywilly)
Comment: @MunchyWilly, welcome to Musical Performance & Practice.

Inquiry to Voice Classification


All continuous maps $f:M\to S^1$ are null-homotopic, is $M$ simply connected?

Question: Suppose that $M$ is a connected topological manifold so that $M$ is path connected, locally path connected and locally connected. Suppose we know that for all continuous maps $f:M\to S^1$ we know that $f_*:\pi_1(M)\to \pi_1(S^1)$ is the trivial map. I have shown that this is equivalent to all continuous functions $f:M\to S^1$ being null-homotopic. Is it possible that this also implies that $M$ is simply connected?
If $M$ is simply connected, then $\pi_1(M) = 0$ implies that $f_* = 0$ for all continuous $f$. But it is not clear to me that a converse should hold. That is $f_* = 0$ for all continuous functions $f:M\to S^1$ implies that $\pi_1(M) = 0$.
Comment: "Locally connected" is redundant if you impose "locally path connected", which is itself redundant if you impose "topological manifold". Moreover, "connected + locally path connected" is equivalent to "path connected + locally path connected". Putting all together, the portion of the first sentence after "connected topological manifold" is redundant.
Comment: @SassatelliGiulio I am aware they are redundant. I am just unsure which condition might be relevant.
Comment: this is equivalent to asking if all group homomorphisms $G \to \mathbb Z$ are trivial, then is $G$ trivial.
Answer: $\mathbb{RP}^2$ is connected, path connected, and not simply connected, but since $f_*:\pi_1(X) \to \pi_1(Y)$ is a group homomorphism it means that $f_*:\pi_1(\mathbb{RP}^2) \to \pi_1(S^1)$ must be the trivial map. Since $\pi_1(\mathbb{RP}^2) \cong \mathbb{Z}_2$ and $\pi_1(S^1) \cong \mathbb{Z}$.
Answer: Here's a method for basically constructing all counterexamples.
A continuous map $f : M \to S^1$ is homotopic to a constant if and only if the induced fundamental group homomorphism $f_* : \pi_1(M) \to \pi_1(S^1) \approx \mathbb Z$ is trivial. Furthermore, every homomorphism $\pi_1(M) \to \pi_1(S^1)$ is the induced homomorphism of a continuous function $M \to S^1$. These two facts are guaranteed by applying the fact that $S^1$ has contractible universal cover; in other words, $S^1$ is an Eilenberg-MacClane space, specifically $S^1=K(\mathbb Z,1)$.
It follows that $M$ satisfies the property

All continuous maps $M \mapsto S^1$ are homotopic to a constant

if and only if every homomorphism $\pi_1(M) \to \mathbb Z$ is trivial, which holds if and only if every homomorphism $H_1(M) \to \mathbb Z$ is trivial. Assuming in addition that $M$ is compact --- and hence $H_1(M)$ is a finitely generated abelian group --- this holds if and only if $H_1(M)$ is finite.
But, there are lots of finitely generated groups with nontrivial, finite abelianization, and each of them can be realized as the fundamental group $\pi_1(M)$ of some compact manifold $M$, in which case $\text{ab}(\pi_1(M)) \approx H_1(M)$ has no homomorphisms to $\mathbb Z$. And yet in this case $\pi_1(M)$ is nontrivial, so $M$ is not simply connected.


Custom translation function

Question: I need own translation function in my custom module where i have defined language codes ('en','ja','de'....etc)
Now i just wanted to pass word and language code as a parameter and it returns translation of that word according to language code.
I am trying this inside my translation but it doesn't work it is returning 'yes' instead i don't know why.
 $japanese_value = t('yes', array(), array('langcode' => 'ja'));
 print_r($japanese_value);

And please let me know if there is a better way to do this or any other translation module.
Comment: That looks to me as if it should work. Have you translated the value of _yes_ to _はい_ in your system?
Answer: Requiring t() to translate the string in a specific language is perfectly fine. The function will return a translation, if the Locale module is installed and enabled, and that string is present in the site; it doesn't use a remote service to translate the string passed as first argument.
Present in the site means:

The translation has been added using the form on admin/config/regional/translate

The translation has been imported using the form on admin/config/regional/translate/import

The settings.php file contains a custom translation in the $conf['locale_custom_strings_ja'] array (for Japanese). For example, the following array would allow to get the Italian translation for Forum and node. (I used Italian just because I know how to translated those words.)
$conf['locale_custom_strings_it'][''] = array(
  'Forum' => 'Bacheca discussioni',
  'node' => 'contenuto',
);

Note that in the latter case, the Local module doesn't need to be enabled.
Comment: thankyou, I wanted to ask you if i add translation in content type -> field ( list (yes,no))  -> edit -> translate ..... is it possible to call some functions to get a translation from there... ?
Comment: Do you mean from `$conf['locale_custom_strings_ja']`? That is automatically done from Drupal.
Comment: admin/config/regional/translate/translate (here i can see the translation of yes , no )....... now i have this value in form array with a field_name and value (yes)............I am creating reports by my custom module i just wanted to translate before generating PDF......... .....so i am tring to create function where i can pass that field name and value to get translation in return ..
Comment: would be very thankful i m new and stuck in this task from friday
Comment: So you are trying to translate the content of a field, not a static string like `'yes'`. Retrieve the value of that field, and pass it to `t()`. If the value of that field can be any value users enter, than it won't work, anyway, as you would need to add as translation any possible value users could enter. Keep in mind that `t()` can only give you a translated string if the translation of the full string is present. Given, for example, *Yes, I know that.* Drupal would not retrieve the translation for *Yes*, *I*, *know*, and *that*.
Comment: Anyway, this is a different question that should be posted as new question. It also requires more details to be answered, and a back-and-forth on comments is not the ideal to answer to questions.
Comment: https://drupal.stackexchange.com/questions/304164/get-translation-programmatically-of-field-value-in-specific-language

Custom translation function


Remove label Search terms from Views exposed form

Question: On this site in the sidebar i have a views_exposed_form to search. I need this search functionality to show my search results for restricted pages.

How do i remove the label 'Search Terms'. Is it possible within
template.php with a hook?
How do i add a placeholder to the input field?
Comment: You can do this by adding form_alter hook in custom module.
Answer: function views_exposed_form($form, &$form_state) {

if ($info = $handler->exposed_info()) {
          $form['#info']["$type-$id"] = $info;
          /**enter your code here  *****/

        }
/**for place holer**/

if (isset($form['title'])) {
        $form['title'][] = array('#placeholder' => t('Gemeente...'));
}

}

Comment: it's not working? I tried it in `template.php`
Answer:
Remove label : In exposed form settings there is a label text if you will not add any value on that it will not display any label

    /* for placeholder */

    function hook_form_alter(&$form, &$form_state, $form_id) {
     if ($form_id == 'views_exposed_form') {
                    $form['title']['#attributes']['placeholder'] = t('Place holder');

    }
    }

Comment: above code i placed in `template.php` but i don't see a placeholder..
Comment: Please add your code what you have written in template.php


On the "Check for running processes" activity, the "Include launchers" option does nothing

Question: I am using install4j Windows Edition 6.1.1 (build 6254).
I have an installer that installs (up to) 3 components, each with a Launcher (exe).
In the uninstall process, I use a "Check for running processes" activity, as suggested here. The "Include launchers" option is checked, but no processes are detected.
When I add the exe files manually to "Additional executables", it works as expected.
Is this a bug, or did I miss something?
Additional question: When I list the "Additional executables", can I give them names by which they are reported to the user when they are running, rather than just filename with path?
In case it matters: The components are Eclipse RCP application, and they are not placed in the installation root, but each in its own subdirectory.
Comment: Does this also happen with the most recent version?
Comment: Yes, I just reproduced this behaviour with this version: install4j Windows Edition 7.0.9 (build 7273).
Comment: Is this a generated launcher or an external launcher?
Comment: It is an external launcher. The exe is created during the Maven build, before install4j is called.
Answer: As of install4j 7.0.9, the "Include launchers" option of the "Check for processes" action only handles generated launchers and you have to pass the external launchers explicitly in the "Additional executables" property.
Comment: I accepted the answer, since it gives me useful information and I can move on. However, this does not explain the behaviour as observed with version 6.1.1. Also, it would be nice if the GUI could mention this limitation.


Converter data para timestamp do Unix

Question: Tenho uma tabela num banco MySQL que possui um coluna data VARCHAR, tipo 20-09-2017 e preciso migrar essa coluna para uma coluna bigint(8) que usa o formato de data timestamp do Unix.
Como fazer isso?
Answer: UNIX_TIMESTAMP('2017-09-20 00:00:00')

Documentação.
Se estiver em outro formato, aí tem que formatar antes:
STR_TO_DATE('20-09-2017', '%d-%m-%Y')

Coloquei no GitHub para referência futura.
Answer: Segue a solução que eu utilizei.
Convertendo de string para data:
Update `tabela`
set date = STR_TO_DATE(date_text, '%d/%m/%Y')

Convertendo de data para unix timestamp:
Update `tabela`
set date_unix = UNIX_TIMESTAMP('date');

Comment: No caso, nota-se que a solução é justamente o que foi postado na outra resposta, é isso? Seria bom marcá-la como aceita para fechar a questão.
Comment: O problema é quando eu fiz a pergunta eu não tinha me registrado ainda.
Agora não consigo aceitar a resposta do Maniero. Sorry pelo BO.
Comment: Se for o caso, pode sinalizar para equipe do site mesclar suas postagens, caso seja possível que eles determinem as que são realmente suas. Desta forma acredito que você poderia receber a pontuação "perdida" de volta; quanto ao ocorrido, fique tranquila. Não há necessidade de pedir desculpas, foi apenas uma recomendação por uma questão de organização do site.

Converter data para timestamp do Unix


Problema ao subir e converter arquivos.txt

Question: Toda vez que eu tento fazer a operação abaixo eu obtenho um erro:
setwd('C:\\Users\\MatheuS\\Documents\\file')

library(readr)

fns = list.files(patt="\\.txt")

sapply(fns, function(x){ assign(gsub("C:\\Users\\MatheusdosSantos\\Documents\\files\\.txt","", x), read.table(x, head=T,sep=";"),
                                envir=.GlobalEnv); NULL})

n <- length(fns)

for (i in 1:n){
  dado1[i] <- read.table(fns[i], head=T,sep=";")
  names(fns[i])[grep("ï..ID", names(fns[i]))] <- "ID"
  write.table(fns[i], dado1, sep="\t", row.names = FALSE, quote=FALSE, na= "", eol = "\r\n")
}

dado1 <- read.table(fns[i], head=T,sep=";")

Essa operação sobe (upa) um arquivo.txt separado por ; e exporta ele com o mesmo nome sobrescrevendo o arquivo antigo separando o mesmo agora por \t (tabulação) e troca o nome.
Porém sempre dá esse erro:
Error in isOpen(file, "w") : invalid connection
In addition: Warning messages:
1: In `[<-.data.frame`(`*tmp*`, i, value = list(ï..ID = 1:29998, NR_CONTA = c(10000063L,  :
  provided 53 variables to replace 1 variables
2: In if (file == "") file <- stdout() else if (is.character(file)) { :
  the condition has length > 1 and only the first element will be used

Comment: Olha, só umas dúvidas antes. O `sapply ` tá assim mesmo? Porque ele não tá sendo associado a variável nenhuma, ele não tá atualizando `fns`. E as ordens em `write.table` parecem estar erradas. Primeiro vem a tabela, que seria `dado1` e depois o nome `fns[1]`, que é uma string.
Comment: No `sapply` lê os ficheiros e depois no `for` volta a lê-los, porquê? Se só quer mudar o separador de colunas e o nome de uma das colunas (de `"ï..ID"` para `"ID"`), está a complicar imenso. E, já agora, pode explicar porquê mudar o separador de `";"` para `"\t"`?
Answer: O código desta resposta foi testado com ficheiros que correspondem ao que sabemos pela descrição na pergunta, não é garantido que funcione sem erros ou adaptação.
Em primeiro lugar, se vai mudar de diretório, obtenha o atual para depois o repor se for necessário.
old_dir <- getwd()
setwd('~/Documentos')

Agora o processamento. Os ficheiros são lidos todos numa só instrução muito mais simples, o read.csv2 já tem sep = ";" e header = TRUE como valores dos respetivos argumentos a passar à função mais geral read.table.
fns <- list.files(pattern = '\\.txt')

df_list <- lapply(fns, read.csv2)
df_list <- lapply(df_list, function(DF){
  i <- grep('\\.\\.ID', names(DF), ignore.case = TRUE)
  names(DF)[i] <- 'ID'
  DF
})
lapply(seq_along(df_list), function(i){
  write.table(df_list[[i]], fns[i], row.names = FALSE, sep = '\t', quote = FALSE, na = '')
})

Este código pode ser ainda mais simplificado, executando só um ciclo lapply que faz tudo e tem como saída a mesma lista df_list com todas as tabelas.
fns <- list.files(pattern = '\\.txt')

df_list <- lapply(fns, function(x){
  DF <- read.csv2(x)
  i <- grep('\\.\\.ID', names(DF), ignore.case = TRUE)
  names(DF)[i] <- 'ID'
  write.table(DF, x, row.names = FALSE, sep = '\t', quote = FALSE, na = '')
  DF
})

E no fim repor o diretório inicial, se for preciso, tal como disse acima.
setwd(old_dir)


Rolling a fair die 18 times, what is the probability of rolling 1,2,3,4,5,6 (each) three times?

Question: The problem statement and solution is below. I understand that each die toss is independent but it doesn't make sense to me why the probability is multiplied by the number of sequences, as in the solution.
When you roll a die 18 times, it is possible to get a countable number of sequences such that a 1,2,3,4,5,6 each appear 3 times. Wouldn't the probability that each number appears exactly 3 times be equal to the ratio of the number of sequences in which 1,2,3,4,5,6 appear 3 times to the total number of sequences you can have (6^18)?
Answer: This questions ask you for the number of possible sequences that meet your conditions.
So, consider this: The sequence 1,2,3,4,5,6 is not the same sequence as 1,3,2,6,5,4. However, each number has occurred exactly once. Since order matters, you must treat this as a permutation.
You could roll something like: {(1,2,3,4,5,6)  (1,2,3,4,5,6) (1,2,3,4,5,6)} or something like {(1,1,1,2,2,2) (3,3,3,4,4,4) ...} and as you can see both meet your criteria and both are different.
So, $$(\frac{1}{6})^{18}$$
is the probability of one of these possible sequences occurring.
$$\frac{18!}{(3!)^6}$$
gives the possible number of these sequences.
$$(\frac{1}{6})^{18}\frac{18!}{(3!)^6}$$
yields the probability of any such sequence occurring.
Comment: http://mathworld.wolfram.com/MultinomialCoefficient.html is a good link for multinomial coefficient, which John correctly mentions in his answer.
Comment: The last statement would be how I would represent the solution algebraically. I'm unsure if it doesn't make sense to say that the solution is the probability of one of these events that fits our condition occurring times the number of sequences that fits our condition.
Comment: Is that equivalent to saying that it's the _ratio_ of "what we want" to the total number of ways it can happen (the total number of possible sequences we can have, rolling a die 18 times).
Comment: Yes, I think could find this using the $\frac{N_a}{N}$ method if you prefer. Where $N_a$ are all the different ways we could roll a die 18 times and meet our given conditions and N represents every possible outcome for rolling a die 18 times.
Answer:
Wouldn't the probability that each number appears exactly 3 times be equal to the ratio of the number of sequences in which 1,2,3,4,5,6 appear 3 times to the total number of sequences you can have (6^18)?

Yes, and the number of sequences is exactly what's calculated with the multinomial coefficient.  You choose the positions in the sequence for the $1$'s, then for the $2$'s, and so forth.  The collection of these sequences is counted by the multinomial coefficient.
Answer: The sequence 1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,4,5,6 (assuming that OP meant this) is just one of the possible permutations of 18 die rolls. There are $6^{18}$ such permutations in total. Therefore the odds are 1 in $6^{18}$, or $(6^{18}) - 1$ to 1 against.
Comment: I doubt this is what the OP meant.  You are counting the number of all possible sequences that result from rolling a die six times including $1,2,6,3, 6,2, 5, 1, 4, 5, 4, 1, 2 ,6, 6, 1,2, 5$, but this string/sequence cannot be included, like many many sequences cannot be included in the number of *those for which each digit on the die appears exactly three times.*
Comment: Aah, I see now, yes - forgive me for being slow and thanks for your comment!


MS Virtual Server 2005R2 - VM won't start

Question: Something apparently happened to one of our VMs, and our admin is no longer available.
I can log into the host server, and access the web-based management interface, but when I try to restart the VM I have the following options:
Restore from saved state
Discard Saved State
Merge Undo Disks
Remove

When I try to restore from saved state, I get an error:

The following error occurred:
The virtual machine could not be started. The virtual machine could not be started. The account name and password are invalid

Could it be trying to use the now-disabled credentials of the former admin? How can I find out which user it's trying to use?
I have restarted the "Virtual Server" and "Virtual Machine Helper" services, but that didn't seem to help.  There is an error in the Virtual Server event log:

The VSS writer failed to get the properties of the virtual machine
  VMNAME, since the operation did not complete in maximum allowed time.
  The virtual machine is allowed for Offline backup only. Check if the
  virtual machine VMNAME is running and then retry the operation, if
  needed to be backed Online.

There is a 2nd VM running on the machine, and it seems to be OK, so it's apparently something with that VM instance.
What do I need to do to get this VM restarted?
Answer: If you don't care about the state the machine was in last, you can Discard State and then Start the machine. It's currently in a saved state, like hibernation, where it should be able to simply resume from where it was saved.
The account error is certainly a strange one. It might be the case that the saved data is owned by someone other than the VS account. Presumably your account wouldn't have access and it's throwing that error. This is just a theory, I've never seen that error in VS2005.
On a side note, VS2005 is 6+ year old technology and you should have upgraded to something else by now. Hyper-V is a pretty straight forward migration path, though others like ESX and KVM can be worked.