Como mudar URL de links ancoras?

Question: Como alterar aquele sinal de "#" dos links ancorados?
Estou a criar um menu slide em CSS e é horrível este sinal na barra do navegador. Há alguma solução viável? Li a respeito do jQuery Address, mas confesso que não entendi "bulhufas".
Eu estou a usar CSS para mudar o margin-left e fazer a div em questão aparecer:
.panel:target{
    margin-left: 0%;
    background-color: #9887F8;
}

jsFiddle
Answer: Para mudar o href de uma elemento podes fazer assim:
elemento.href = 'http://stackoverflow.com';

Podes usar também o .setAttribute que altera no HTML diretamente:
elemento.setAttribute('href', 'http://stackoverflow.com');

são maneiras diferentes, com algumas diferênças.

Com jQuery podes fazer com .attr() ou .prop() seguindo a mesma lógica:
$("a").attr("href", "http://www.outra.coisa/");

Se o que quer é evitar ter no URL o simbolo #, pode usar href="javascript:void(0)". Se não o tiver assim de inicio, pode usar:
$("a").attr("href", "javascript:void(0)"); // talvez queira ser mais específco e usar $("#meuSlideShow a")...

Usar # é um truque antigo e muito útil. Esse # ir parar à URL pode ser evitado com o .preventDefault() também. Mas parece-me que é a ferramenta errada se o que quer é somente não mostrar o #.
Porém para essa funcionalidade não precisa de uma ancora, pode funcionar tão bem ou melhor com outro elemento como
, <fiv> ou até <button>...

Vendo agora o seu HTML e CSS, aqui fica uma nova solução, com jQuery:
var elementosMenu = $('.slide_menu .panel');
$('#page a[id^="link-"]').on('click', function(e){
   e.preventDefault();
    elementosMenu.css('margin-left', '-102%');
    var targetID = this.getAttribute('href').substr(1);
    document.getElementById(targetID).style.marginLeft = '0%';
});

jsFiddle: http://jsfiddle.net/Lx4Vz/
Comment: Cara se salvou a pátria thanks man! Resolveu em 100%!
Comment: É verdade, tinha me esquecido completamente do void(0). Perfeito!
Answer: Não há como mudar este símbolo, pois se você mudasse não seria mais uma âncora.
O que você pode fazer é impedir que o evento de click se propague, impedindo que o browser execute a ação padrão do click. É bem simples. Basta usar o preventDefault() do jQuery.
Exemplo:
HTML
Clique me

JAVASCRIPT
$(".link").click(function(event){
    event.preventDefault();
    // Aqui entra o resto do seu código referente ao que quer fazer com o click do usuário
});

Comment: O click chama na tela uma div com o atributo id...más mostra na barra do browser o id da div tipo (#galeria). Estou tentando contornar isto. Estou dando uma olhada em [link]https://github.com/tombonner/jurlp que diz fazer isto...más por hora ainda não resolvi :(
Comment: Pode colocar esse código aqui pra eu analisar?
Comment: jsfiddle [link] http://jsfiddle.net/subversivo58/F8LxF/
Comment: Então, temos um problema. Você pode usar o stopPropagation() assim: http://jsfiddle.net/nqV95/1/ Porém, ele irá impedir a execução padrão do elemento , ou seja, a animação não vai funcionar. Você teria que criar essa animacao no JS, e não no CSS. Não creio que seja possível fazer o que você quer desta forma.

Como mudar URL de links ancoras?


CannotDetermineEntityError when saving entities with TypeORM

Question: I created a NestJS and used TypeORM for the RDBMS(I used postgres in my project).
Post is an @Entity class, PostRepository is a Repository class for Post.
I was trying to create OnModuleInit service to initialize some data.
@Injectable()
export class PostsDataInitializer implements OnModuleInit {
  private data: Post[] = [
    {
      title: 'Generate a NestJS project',
      content: 'content',
    },
    {
      title: 'Create GrapQL APIs',
      content: 'content',
    },
    {
      title: 'Connect to Postgres via TypeORM',
      content: 'content',
    },
  ];

  constructor(private readonly postRepository: PostRepository) {}
  async onModuleInit(): Promise<void> {
    await this.postRepository.manager.transaction(async (manager) => {
      // NOTE: you must perform all database operations using the given manager instance
      // it's a special instance of EntityManager working with this transaction
      // and don't forget to await things here
      await manager.delete(Post, {});
      console.log('deleted: {} ');
      this.data.forEach(async (d) => await manager.save(d as Post));
      const savedPosts = await manager.find<Post>(Post);
      savedPosts.forEach((p) => {
        console.log('saved: {}', p);
      });
    });
  }
}

When starting up the application, I got the following error.

CannotDetermineEntityError: Cannot save, given value must be instance of entity class, instead object literal is given. Or you must specify an entity target to method call.

But the above save was accepting an instance of Post.
Answer: I think it is pretty much what the error says. You cannot pass literal objects to .save
  private data = [
    {
      title: 'Generate a NestJS project',
      content: 'content',
    },
    {
      title: 'Create GrapQL APIs',
      content: 'content',
    },
    {
      title: 'Connect to Postgres via TypeORM',
      content: 'content',
    },
  ].map(data => {
    const post = new Post();
    Object.assign(post, data);
    return post;
  })

the above might solve this.
Comment: btw typecasting  in strongly typed languages allow us to convert types. Since javascript is not strongly typed, the _type assertion_ that you used will no longer exist at runtime. See [this example](https://www.typescriptlang.org/play?#code/MYGwhgzhAEBiD29oG8BQ0PWPAdhALgE4Cuw+8hAFIQKZgAmuIAntGAFzQ7EC2ARjUIBKFAF9U41Njz5o8PgCtoAXhTpMHaABYJAblSpK8pZDiIhAOjCogA)
Comment: I used  `d as Post` to cast it to `Post`, why this does not work. What is the difference between object literal and instance in typescript?
Comment: the difference isn't up to ts but to js. `new Foo()` objects will be `instance of Foo`, while a literal object that just has the shape of `Foo` won't. And TypeORM expect to work with instances of `Foo`
Answer: You can alternatively specify the target type as per the error message like so:
await manager.save(Post, d)

From the documentation of save() I see there is such a method as:
save<Entity, T extends DeepPartial<Entity>>(targetOrEntity: EntityTarget<Entity>, entity: T, options?: SaveOptions): Promise<T & Entity>;

nest version 9.1.8
Comment: Works better for me than the accepted answer
Comment: This answer worked well for me.


unicode to human readable string c# .net

Question: This is probably a very basic question, but really appreciate if you could help me with this:
I want to convert an string that contains characters like \u000d\u000a\u000d\u000 to a human readable string, however I don't want to use .Replace method since the Unicode characters might be much more than what I include the software to check and replace.
string = "Test \u000d\u000a\u000d\u000aTesting with new line. \u000d\u000a\u000d\u000aone more new line"

I receive this string as a json Object from my server.
Comment: Can you just use it to display?
Comment: One possibility is described here:

[How do convert unicode escape sequences to unicode characters in a .NET string][1]

  [1]: http://stackoverflow.com/questions/183907/how-do-convert-unicode-escape-sequences-to-unicode-characters-in-a-net-string
Comment: thanks @uncoder I just used "Regex.Unescape(str)" wondering if this is a safe and sounds way of doing it.
Answer: Do you even need that?
For example, the following code will print abc which is the actual decoded value:
var unicodeString = "\u0061\u0062\u0063";
Console.WriteLine(unicodeString);

Comment: yes unfortunately the UI element in the software shows all the unicode characters..
Comment: Well, there is difference between ``"\u0033"`` and ``"\\u0033"`` The first one contains an escape sequence ``\u`` which indicates a Unicode character. The second one simply starts with an escaped backslash (and that's what you're seeing in your app.)


Azure Application Gateway with App Service

Question: Requirement I have -
I want to do redirection like this. I have multiple App service that will be running and based on the url I want to do redirection to the proper one.
Something like this -
test.com/v1 -> app service appv1.com
 test.com/v2 -> app service appv2.com
 test.com/v3 -> app service appv3.com
Is azure application gateway the right choice for this considering it supports url mapping.
Though, I am unsure if application gateway for a app service will work? Does the public IP of the App service static ? Should that be used for configuration with the Application gateway
Answer: It is possible to route traffic to different backend pools (including VMs and Azure App Services) via URL paths by using Path-Based Rules - https://learn.microsoft.com/en-us/azure/application-gateway/application-gateway-create-url-route-portal.
This will allow you to use a "static" root domain (which you might want to purchase an SSL certificate for) and route traffic according to the path after the '/'.
Answer:
Is azure application gateway the right choice for this considering it
  supports url mapping?

I don't think so. Consider the pricing of Application Gateway. To have SLA support you need at least 2 medium instances. That is ~$51.10/month or let's say $100 per month for just the redirection. What kind of traffic you expect for this redirection?
Consider adding a another Web App to one of the existing App Services you have for for appv1.com, appv2.com, or appv3.com.
Another web app would have custom domain binding for test.com and redirect rules (I don't know if this is Windows or Linux web app).
Answer: In the moment Application Gateway only supports multiple sites based on different hostnames / FQDNs. I would not know how to add multiple sites with different paths / routes.
Also check out


Assembly program (in MARIE), How to fill First and second pass?

Question: I really did the sympol table and did fill it its easy but the code has many errors like Repeat is not vaild and values var1,var2 & res where no datatype for the HEX OR DEC etc.. so what to fill really confusing
Click to see the problem
Any help ?
Comment: You're right: `Repeat` is not defined, so the problem cannot be finished.  Probably a typo, and they meant to use the properly-defined label `Again` instead of `Repeat`.  Suggest you proceed with that assumption, and state the assumption clearly in the work you turn in, if possible.
Comment: @ErikEidt and how to complete the tables below ?
Answer: You're right: Repeat is not defined, so technically, the problem cannot be finished.  Probably a typo, and they meant to use the properly-defined label Again instead of Repeat. Suggest you proceed with that assumption, and state such assumption clearly in the work you turn in, if possible.

The post-first-pass table shows the opcode and the operand, and while the first operand is shown numerically, the second operand is shown symbolically when necessary (or numerically if known as such, e.g. for SkipCond since the operand is numeric already).
So, for the first instruction, we have 1, Var1, which is a representation of the machine code instruction where the opcode is 1 (Load) and the operand is Var1.

When we get to the post-second-pass table, the symbolic operands (as names) are replaced with the numeric values that the processor will see when executing this program.  In many cases, the numeric values of these names are not known until the completion of the first pass, which gives numbers to labels.  So, after the 2nd pass now we have a fully numeric representation of the machine code for the program.


ideal I=(x^3,x^5) of the polynomial ring Q[x]

Question: Given the ideal I=(x^3,x^5) of the polynomial ring Q[x]
1) 1 example of a polynomial which belongs to I and has 4 non-zero terms
2) 1 example of a polynomial which doesn't belong to I and has 3 non-zero terms.
I didn't really understand when a polynomial belongs to an ideal in this kind of a situation (x^3,x^5)
An advice /explication would be enough and much appreciated.
Comment: A polynomial p belongs to I if it's a combination of the generators multiplied by some other polynomials of Q[x]. A trivial example is their sum but $x*x^3 + 3*x^5$ also belongs for example
Comment: Is not $I=(x^3)$?? Because $(x^5)\sunset (x^3)$
Comment: Lol yes totally forgot about that.
Answer: If by term you mean coefficient then $(1+x)*x^3 + (1+x)*x^5$ is an example for the first. $1+x+x^2$ is an example for the second question
Comment: thanks, i thought the teacher wanted terms(bcs in the problem is using the word terms) but maybe coefficients made more sense.
Comment: I am not sure the second example is correct ...             bcs  x^3(1/x^2-1/x)+x^5(1/x^3+1/x^5+1/x^3)=1+x+x^2


passing data between viewController and UIView

Question: When I pass data between ViwControllers I have a great result:
    //ClassA
//.h
#import "ClassB.h"
@class ClassB;
@interface...

@property (nonatomic, strong) ClassB *classBObj;

    //.m
    -(void)ViewDidLoad
    {
    self.classBObj = [[ClassB alloc] init];
    }
    -(IBAction)PassingData:(id)sender
    {
    self.classBObj.intValue = 3;
    }

This is ClassB describe
    //ClassB
//.h
#import "ClassA"
@property (retain) NSNumber intValue;

That's it ! intValue has value equal 3. But if i try to do the same thing between ViewController and UIView I receive nil in property (of UIView). How to pass data from ViewController not only another ViewController? Thanks everybody.
Comment: is your app using ARC or non-ARC?
Comment: I check it by this code  `NSString *dummy = [[[NSString alloc] init] autorelease];` and i get an error `ARC forbids explicit message of 'autorelease'`. So I use ARC
Answer: Use strong instead of retain.
@property (strong) NSNumber intValue;
Also wen you are sending an value to NSNumber send an NSNumber so change your line of code like this
self.classBObj.intValue = [NSNumber numberWithInt:3];

Comment: Thanks, I've done it. But still it's nil. If I do it between ViewControllers there is no problem
Comment: Is your view a subclass of UIView?
Comment: Try printing the value of `self.classBObj.intValue` before and after assigning the value to it..`-(IBAction)PassingData:(id)sender
    { NSLog(@"%@", self.classBObj.intValue);
    self.classBObj.intValue = 3;   NSLog(@"%@", self.classBObj.intValue);
    }`    also consider changing the name of the instance variable to something else since `intValue` is a method in `NSNumber`.
Comment: Also is there particular reason why you use an `NSNumber`, if not just declare the property as `@property (assign) NSInteger anIntegerValue;`


While não exibe se eu usar o get id?

Question: Alguém me ajuda a entender o porque esse código não ta conseguindo exibir o genero do banco?

      <?php
       $vide = $_GET['i'];
include "core/home/database.php";
$consultaGe = "SELECT * FROM generos WHERE id='$vide'";
$conGenre = $mysqli->query($consultaGe) or die (@mysqli_error());

?>
      Generos:
    <?php while($gene = $conGenre->fetch_array()){ ?>

         <h5 class="cop_genre" value="<?php echo $gene['id'];?>"><?php echo $gene['genre']; ?>

    <?php } ?>

Se eu tiro o WHERE id='$vide' ai ele exibe, mas ele exibe todos os generos, e não somente o dele. O que está errado ai?
A estrutura da tabela generos:
Comment: Não concatene os valores direto na query, pois isso deixa a aplicação vulnerável a ataques de SQL injection. Leia mais sobre o assunto aqui: https://pt.stackoverflow.com/q/9734/112052
Comment: `WHERE id='$vide'`, se `$vide` é 1, a query será `id='1'`, mas a coluna `id` é do tipo INT, não precisa as aspas. Deveria ser `id=$vide` (mas melhor que isso seria se você usasse o `prepare` do MySQLi).
Comment: Isto responde à sua pergunta? [Consulta ao banco de dados em PHP com WHERE não retorna valor](https://pt.stackoverflow.com/questions/489833/consulta-ao-banco-de-dados-em-php-com-where-n%c3%a3o-retorna-valor)
Comment: o while esta engolindo o h5 e não sei o porque
Comment: Apenas para esclarecer, na URL chamada você está incluindo o parâmetro "i"? Por exemplo `https://example.com/index.php?i=generodesejado`.
Comment: sim ele esta, tanto que todo o resto funciona, a unica coisa é que ele pega o "i" de tudo do filme. Não somente do genero
Comment: Tipo, ele não esta pegando o gênero do banco dos gêneros e sim o numero do gênero que esta no banco do filme, acho que isso pode estar sendo o problema, mas ainda não sei como resolver, por isso que se eu colocar só `$v['genre'];` ele aparece o numero do genero e não o nome dele, dai tentei esse código ai em cima, mas sem sucesso, ele não mostra o nome.
Comment: Poderia colocar a estrutura da tabela `generos`?
Comment: claro posso sim
Answer: Vinicius,
Como quando você retira a condição WHERE id='$vide' são exibidos todos os gêneros acredito que o "problema" está no parâmetro i.
Pelos seus comentários e pelo nome da variável ($vide) acredito que você está passando o id do vídeo e não do gênero. Se for isso mesmo você precisa alterar sua consulta para que você busque o id do gênero dentro da tabela de vídeos (em uma subconsulta) e usar na consulta do gênero.
Ficaria algo assim (não sei como é sua tabela de vídeos):
$consultaGe = "SELECT * FROM generos WHERE id=(SELECT id_genero FROM videos WHERE id='$vide')";

Edit: Atente ao comentário do @hkotsubo e procure formas de melhorar a segurança do seu aplicativo.
Comment: Muito obrigado, no caso sim, o i estava pagando o do vídeo e não somente do gênero, mas com a subconsulta funcionou perfeitamente. Em relação a segurança estou pesquisando meios de aprimorar esta parte no meu código. Mas obrigado ajudou muito

While não exibe se eu usar o get id?


Filter node display

Question: I have this nodes:

I want to filter the nodes display based on the user logged in and the value of a specific field in the 'Document' Content Type.
How will I do that? In the picture above first node must not be displayed.
Comment: By setting roles as authenticated user in page setting section of the view.
Answer: you have to create a custom template for your nodes  : node--"ContentTypeMachineName".tpl.php , then check if the use is login with :  user_is_logged_in()  and the value for the field inside your content type in your case document , after that you can simply use conditional statements to control the output of your template.
Comment: Thanks for giving me an idea, can you point me something that will guide me in creating custom template for nodes. I really dont have any idea in theming but I know module development.
Comment: it's easy to do , go to your theme's template forlder create a new file and name it "node--article.tpl.php" copy the default node.tpl.php inside of it then  start dumping some vars to know what you have as variables and use some functions to filter the display per user login status
Comment: One more question. Whats the difference between node--article.tpl.php and node-article.tpl.php? Which is the right filename convention?
Comment: node-article.tpl.php will never work no matter what you do , you have to put node--[contenttypemachinename].tpl.php for drupal to see it

Filter node display


Three fair six-sided dice are rolled.

Question: Three fair six-sided dice are rolled. Find the probability that the total on all three dice is five or less.
Comment: Hello. Welcome to Math SE. On this forum it's usually nice to explain what you have tried doing in order to solve the problem. We're not machines that solve random homeworks, we wanna make you understand the whole  topic better.
Answer: Say $(D_1,D_2,D_3)$ denote the outcomes of the 3 dice respectively.
The possible ways are as follows:
$(1,1,1),(1,1,2),(2,1,1),(1,2,1),(1,2,2),(2,1,2),(2,2,1),(1,1,3),(1,3,1),(3,1,1)$
i.e. $10$ outcomes.
The total number of outcomes is
$$ 6\times 6\times 6 = 216$$
Hence probability is
$$\frac{10}{216} = \frac{5}{108}$$
Answer: If you want to approach the problem more analytically, consider that the probability is the number of ways of choosing $x_1,x_2,x_3$ (call this $N$) such that each is a positive integer (and the sum is five or less) divided by the the total number of different outcomes for the three dice ($6^3=216$).
$$x_1+x_2+x_3\le5$$
Introduce a slack variable $x_4\ge1$, and find the total number of solutions to
$$x_1+x_2+x_3+x_4=6$$, where each of the $x_i\ge1$. By stars and bars, this is
$$N=\binom{6-1}{4-1}=\binom{5}{3}=10$$
so the probability is $\frac{10}{216}=\frac{5}{108}\approx0.0463$.
Answer: So, because dice re dice, we know that the minimum roll is a 1. This means that no die can be larger than a three as well, because $n=3$ in the equation $5-1(n-1)=3$.
Pretend die A is rolled and is a $3$ (a $\frac{1}{6}$ chance). At this point, both die B and die C need to be $1$s in order for the sum to be less than or equal to $5$. The combination of $[3,1,1]$ in that specific order has a $\frac{1*1*1}{6*6*6} = \frac{1}{216}$ chance of concurring.
What happens if die A is rolled and is a two? How many combinations of the last two dice exist where the sum is less than or equal to $3$? $[2,1,1],[2,2,1],[2,1,2]$ are all possibilities, and those are three more $\frac{1}{216}$s that can occur.
There are more combinations when die A is a $1$, but I'll leave that up to you.

Three fair six-sided dice are rolled.


Duas requisições Ajax em uma mesma função

Question: Ao carregar uma página, tenho duas requisições Ajax em sequência que preenchem dois select´s com as opções que vem de tabelas diferentes no banco.
Porém apenas a primeira é executada, a segunda não chega nem a chamar. Já acompanhei com debug, coloquei breakpoint para ver se a segunda requisição entra e não funciona.
As duas são independentes. Segue o código:
function Inicio(){
   // Primeira requisição que é executada
   $.get('ctrl/administrativo/modcadcon.ctrl.php',
           {'acao':'todos_atv', 'campo':'mod_status', 'valor':'1'},
           function(ret_mod){

           // Preenche o select com o resultado

           }
   );

   // Segunda requisição não é executada
   $.get('ctrl/administrativo/procadcon.ctrl.php',
           {'acao':'consultar', 'campo':'pro_status', 'valor':'1'},
           function(ret_pro){

           // Não chega aqui...!
           }
   );
}

[RESOLVIDO]
Havia um erro no script PHP que recebia a segunda requisição...
Agora as duas funcionam.
Comment: Já colocou um console.log no segundo para ver se há ação?
Comment: Observe também se ocorreu algum erro de javascript na execução da página, pois quando isso acontece, o restante do código que existe depois do erro não roda.
Comment: @sam e @Marcell Alves - a hora que chega na linha do segundo `$.get...`, seguindo com o debug, ele não executa. Deve ter algo errado aqui. O arquivo php existe... tá muito estranho isso.
Answer: Tenta assim :
function Inicio(){
   // Primeira requisição que é executada
   $.get('ctrl/administrativo/modcadcon.ctrl.php',{'acao':'todos_atv', 'campo':'mod_status', 'valor':'1'})
         .done(function( data ) {
            console.log('Preenche o select com : ' + data)
            $.get('ctrl/administrativo/procadcon.ctrl.php',{'acao':'consultar', 'campo':'pro_status', 'valor':'1'})
               .done(function( data2 ) {
                  console.log('Preenche o select com : ' + data2)
               });
         });
  }

Comment: Essa solução é válida, porém demorei para perceber que o erro estava no script PHP. Muito obrigado pela ajuda!
Comment: Mesmo assim acho mais seguro de esperar um requisito finalizar antes de fazer o segundo !


how to display dynamic array values to view from model in codeigniter

Question: here is my model code:
foreach ($query->result() as $row)
{
    $data = array(
                   'ptitle' =>$row->ptitle,
                    'technology' => $row->technology,
                    'description' => $row->description,

                    );

    $this->session->set_userdata('project',$data);
}

here is my View code:
<?php
if (isset($this->session->userdata['project']))
{

     $ptitle = ($this->session->userdata['project']['ptitle']);
    $technology = ($this->session->userdata['project']['technology']);
    $description =  ($this->session->userdata['project']['description']);

}
?>

when i print array it displays

Array ( [ptitle] => opmp [technology] => hbh [description] => kg ) Array ( [ptitle] => icicse [technology] => vv [description] => bhjv ) .can someone help me to print this values in view
Comment: add the above comment also in description.
Answer: Setting session should be like this
$data = array(
    'ptitle'        => $row['ptitle'],
    'technology'    => $row['technology'],
    'description'   => $row['description'],
);

$this->session->set_userdata($data);

To retrive them use
if (isset($this->session->userdata['project']))
{

    $ptitle         = $this->session->userdata('ptitle');
    $technology     = $this->session->userdata('technology');
    $description    =  $this->session->userdata('description');

}

Answer: If your are storing multiple as array in SESSION then you surely need foreach in your view too.
Change from
if(isset($this->session->userdata['project']))
{
    $ptitle = ($this->session->userdata['project']['ptitle']);
    $technology = ($this->session->userdata['project']['technology']);
    $description =  ($this->session->userdata['project']['description']);
}

into
if(isset($this->session->userdata['project']))
{
    foreach($this->session->userdata['project'] as $project)
    {
        $ptitle = $project['ptitle'];
        $technology = $project['technology'];
        $description =  $project['description'];
        echo $ptitle.'
'.$technology.'
'.$description.'
';
    }
}

Comment: i am getting only single array .i want multiple array to print in view
Answer: Try setting your array like bellow and then pass it to session set data.
$project = array("project" =>
                         array(
                             'ptitle' => "ptitle",
                             'technology' => "technology",
                             'description' => "description",
                         )
                  );

$this->session->set_userdata($project);


How is JS both non-blocking / asynchronous but single-threaded?

Question: I'm having trouble visualizing how Javascript can be both single-threaded but non-blocking on the client. I've always envisioned something like an assembly line:

At the start of your code execution, you've got a single assembly line putting together different parts to a car.
We get to a point at 20%-to-completion where an engine needs to be added, but an engine hasn't been assembled yet.
Instead of waiting for the engine to be assembled, the assembly line gets broken up into two assembly lines - two threads, right?
Line 1 continues to assemble the other parts of the car.
Line 2 starts to assemble the engine.
When Line 2 finishes the assembly of the engine, it goes back into Line 1 and the engine is added.
Line 1 could be at 30%-to-completion, 99%-to-completion, etc at this point depending on how fast the engine was assembled.

This is how I envisioned non-blocking, async code. The main thread of Line 1 gets to continue to chug along without having to wait for Line 2 to finish first. But this assembly line metaphor requires two assembly lines, or two threads, but JS is single-threaded.
So now I'm confused.
Comment: Not Javascript but might help: [Concurrency is not parallelism](https://www.youtube.com/watch?v=cN_DpYBzKso)
Answer: In short, the runtime has an event loop that kinda simulates async in 1 thread.
In long, I found this video and text to be a good explanation:
http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html
Comment: Thanks. That video is amazing and clears up a LOT of things. It even using the word `defer` which is what originally brought me to make this question as I was trying to figure out how `Meteor.defer()` works.
Answer: No, a thread is not an assembly line. To keep your metaphor:

an assembly line is sequence of things that need to be done to your automobile (or whatever things the line is producing)
a thread is like a workman who is working on these assembly lines

Yes, in a single-threaded environment (one-man factory) the worker can only work in one assembly line at a time. But that doesn't mean the assembly lines cannot be run concurrently. The worker can start a machine that paints the car, then go over to the other line and install a part of the motor, then go back to the now painted car and start drying it…
That's how JS works. The worker has to finish his current step before he can work on the next task, but then he can choose another assembly line as he sees it fitting. And this even allows parallel processing when all he needs to do is start a machine that does some work in the background, as he then is available to do other things while waiting for a signal that the machine has finished.


What kind of digital piano instrument should I look for when I like to play pop?

Question: Currently I have an old simple Casio (touch-sensitive keys, awful synthesis) and now I'm looking for another digital piano instrument. I think that it's a good idea to have weighted keyboard (It's similar to piano, so it'd be simpler to change instrument later).
Given that I usually play pop, pop-rock and pop-metal, but sometimes some classics too; should I go for a digital piano or keyboard? If both are an option, which one is more cheap in general? Are 61 keys enough for this? What do you think?
Answer: Generally, you should primarily be looking at two things when deciding on the purchase: the quality of the keyboard and the quality of the sound.
Most keyboards/synthesisers will have a half-weighted keyboard which offers a somewhat different feel to an acoustic piano. Dedicated electronic pianos will generally have a weighted keyboard and possibly a hammer-action playing mechanism, designed to replicate the playing feel of an acoustic instrument.
The number of keys is a question of compromise between range and portability. A 61-key keyboard will be easy to transport to rehearsals/gigs, but you may find it too limiting for classical piano repertoire. Many companies sell a number of versions of their keyboards/synthesisers, so you may be able to choose between 61, 76 or 88 keys. If five octaves seems too limiting and the 88-key version is too big, the 76-key option may be a good compromise. It's also worth noting that 61 and 76-key keyboards tend to be half-weighted, while 88-key keyboards are generally full-wieghted.
With regards to sound options, digital pianos tend to have a limited sound selection: generally several acoustic and electric piano models, plus maybe some strings or organ sounds. If require a more flexible sound bank, you would need to connect an external sound module or a computer running a software synth via MIDI.
Synthesisers will of course have a lot more preset sounds and editing tools for creating your own. I'd generally advise against purchasing a keyboard, unless auto-accompaniament is a required feature. For most purposes in a band setting, a synthesiser/workstation is a better option. The drawback is that most synthesisers don't have built-in speakers. However, in most performance situations this isn't a drawback and the synthesiser will have proper stereo line outputs, which isn't always the case with keyboards (having these is essential in any recording/performance situation).
For the applications you've outlined, my suggestion would be to look for a synthesiser/workstation with a 76 or 88-key keyboard. It will give you a broad selection of sounds and at the same time offer enough range to play some classical repertoire. If the classical repertoire is a key consideration, however, I strongly recommend getting an instrument with an 88-key full-weighted keyboard.
Answer: I think the right answer to this is NORD, which although expensive, are the synths that Ibanez of keyboards. The sound quality is top notch and it's as versatile as it gets. The quality/price factor is a good one too.
Comment: Eh.
Kurzweil is the Ibanez of synths (in terms of cult status among shredders) :P
Answer: I would strongly consider getting a separate keyboard and sound unit. This gives you the flexibility to upgrade one or the other independently.
Keyboards are available with both MIDI and USB interfaces, so you can use them to control computers or MIDI devices. I have an M-Audio keyboard, which feels enough like a piano to keep me happy. My only complaint is some of the mechanical noise from the keys. You can spend a lot more and get a more prestigious brand such as Roland or Akai.
88 keys gives you the same range as a piano. For pop, you may well be able to make do with 61 keys -- it will save you money and is easier to store and transport.
For the sound source, you have all kinds of options. You might find that a PC/Mac can produce all the sounds you need. I find that GarageBand has some very convincing piano sounds, organ, simulations of other instruments and synths, and you can increase the range of sounds with plugins.
If you find you want to play in places you're not prepared to take a laptop, you could get a MIDI sound module. These seem to be less common than they used to be -- perhaps ousted from the market by laptops, but they're still available.
Answer: Take a look on Roland CF-30 which is a good priced 88-weighted-keys, compact and with pop piano grand. But you can't go wrong with other brands as well. It can be a decent MIDI controller.


Application crashes when trying to set OnClick for button

Question: I'm new to Android Studio and am trying to set a OnClick listener for a button using XML. I used android:onClick but when I run the app and press the button it crashes.
Here is my XML:
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Convert"
    android:id="@+id/convertButton"
    android:onClick="onConvertButtonClicked(View v)"
    android:layout_below="@+id/radioGroup"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="49dp"/>

Here is what my java code looks like:
public void onConvertButtonClicked(View v){...}

Answer: in XML put the method name without the brackets or parameters {android:onClick="onConvertButtonClicked"}


How to compare the random forest performance using R-Squared?

Question: I've trained a random forests for a regression problem. Now, I want to check if the model is not overfitted. I have tuned the parameters and then compared the R-Squared of Train and Test dataset as below
test_predict <- model%>% predict(test_data) %>% predictions
R2_test <- 1 - (sum((test_actual-test_predict )^2)/sum((test_actual-mean(test_actual))^2))

train_predict <- model%>% predict(train_data) %>% predictions
R2_train <- 1 - (sum((train_actual-train_predict )^2)/sum((train_actual-mean(train_actual))^2))

The R-Squared on train dataset is significantly higher (close to 0.9) which made think the model is overfit. Then I came across to this question Random Forest - How to handle overfitting. It is saying that predict(model, newdata=train) "treats your training data as if it was a new dataset, and runs the observations down each tree. This will result in an artificially close correlation between the predictions and the actuals, since the RF algorithm generally doesn't prune the individual trees, relying instead on the ensemble of trees to control overfitting."
I don't know what would be the best way to compare the performance of model between train and test dataset.
Answer: The gist of $R^2$ is that you compare your performance to a naïve model that always guesses the same value.
$$R^2 = 1-\dfrac{\sum\big(y_i - \hat y_i \big)^2}{\sum\big(y_i - \bar y\big)^2}$$
In the numerator, we subtract the predictions from our model from the observed value. The closer to the observed values are predictions are, the better.
The the denominator, we do the same, but we consider a model that always guesses the mean of the observed $y$ values. If you have no idea how to model the conditional expected value, the reasonable but naive model would always predict the unconditional expected value.
You know how to calculate the numerator and denominator in your software, so calculate them.
You are likely to be interested in how your model does out-of-sample (OOS), and that follows similar logic.
$$R^2_{OOS} = 1-\dfrac{\sum\big(y_{i, OOS} - \hat y_{i, OOS} \big)^2}{\sum\big(y_{i, OOS} - \bar y_{in}\big)^2}$$.
The trick is to keep the denominator as the square loss of a model that naively guesses the same value every time, and the value you guess is still the in-sample mean, since that's the model learned at training time. Don't use the out-of-sample $\bar y$, since you don't know it. (If you knew the $y_i$-values that you would need to calculate out-of-sample $\bar y$, you wouldn't need a model to predict those values. You'd just look them up and have perfect predictions.)
I discuss more here my thoughts on why the denominator should use the in-sample $\bar y$ instead of out-of-sample. As long as you divide by the same number, you will rank models in the same order, but using our-of-sample $\bar y$ seems to lack statistical motivation. Crucially, however, just squaring the Pearson correlation between the out-of-sample predictions and true observations is likely to miss crucial information, a topic I discuss here and demonstrate with pictures here.
Answer: Good afternoon!

You have provided a good link in your post. It shows that you need
  predict(model)

Why? Because it's Out Of Bag forecast (the OOB score is calculated using only a subset of decision trees not containing the OOB sample in their  training dataset), as far as I know, so it's similar to cross-validation. Using
predict(model, newdata=train)

you will make predictions using train data and model trained on that data, which seems confusing and may provide unrealistically high model performance.

I personally would pay attention to model performance on test, because model was fitted on train so it 'knows' train and will perform on train better.

Is R-squared the metric you really want to work with? It just indicates the percentage of target variable variance explained by model. Since ML models are used for forecasting, the most concern is about (surprisingly!) the accuracy of forecast. So for regression problem people usually use RMSE, MAPE etc. which describe better the average error of forecast.
Comment: $$R^2 = \dfrac{n(RMSE)^2}{\sum\big(y_i - \bar y\big)^2}$$ Consequently, any comparison of models based on which has higher $R^2$ is equivalent to asking which model has lower $RMSE$.
Comment: Good point, I have never thought about comparison by $R^2$ as of comparison by RMSE just scaled with some constant multiple. However, it seems not to work so straightforward as comparing just RMSE when we compare train and test results, since sample variance of the target variable may differ in train and test.
Comment: Please refer to my answer for how to think about out-of-sample $R^2$. // I missed the $1-$ in my comment above, yes.


Problema com strcpy

Question: Eu estou tentando preencher os campos de uma struct com strcpy mas não estou obtendo o valor esperado, como por exemplo:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

struct Aluno {
    char tipo;
    char matricula[8];
    char idade[2];
    char nome[40];
};

int main( )
{

    struct Aluno m;

    m.tipo = '5';
    strcpy(m.matricula, "20101122");
    strcpy(m.idade, "30");
    strcpy(m.nome, "Jack Revoltado");

    printf(" Tipo do aluno = %c\n",m.tipo);
    printf(" matricula %s\n",m.matricula);
    printf(" tamanho %s\n",m.idade);
    printf(" nome %s\n",m.nome);

    return 0;
}

Cuja saida é :
Tipo do aluno = 5
 matricula 2010112230Jack Revoltado
 tamanho 30Jack Revoltado
 nome Jack Revoltado

Ou seja, a função está concatenando tudo e obviamente que eu não quero isso. Por que essa função está fazendo isso se eu não passei do limite do espaço destinado a cada campo? E o que deve ser feito para que cada campo tenha seu respectivo valor?
Answer: Em C as strings precisam ter um zero binário ao final.Então, sua estrutura precisa reservar espaço para ese zero binário. Portanto sua estrutura deve ser declarada assim:
struct Aluno
{
  char tipo;
  char matricula[9]; // <---
  char idade[3];     // <---
  char nome[41];     // <---
};

Problema com strcpy


Delete checked item from list view and data from database, using adapter class

Question: <code> public class delete extends BaseAdapter {
  SQLiteDatabase db;

String am;

 private final Context c;
private final ArrayList<String> str;
 private final String[] number;

ArrayList<Integer> checks=new ArrayList<Integer>();

public delete(Context c, ArrayList<String> str, String[] number, ArrayList<Integer> checks) {
    this.c = c;

    this.str = str;

    this.number = number;
    this.checks=checks;
}

@Override
public int getCount() {

    return str.size();

}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater= (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View ListView ;

    if(convertView==null)
    {
        ListView=new View(c);
        ListView=inflater.inflate(R.layout.button,null);

        TextView textview=(TextView) ListView.findViewById(R.id.textView6);
        textview.setText(str.get(position));

    }

    else
    {
        ListView=(View)convertView;
    }

    Button btnupdate=(Button)ListView.findViewById(R.id.button4);

      //checkbox declaration
    CheckBox chk=(CheckBox)ListView.findViewById(R.id.chk1);

btnupdate.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
      db=c.openOrCreateDatabase("Student",Context.MODE_PRIVATE, null);
      String num = number[position];
      Cursor cc=db.rawQuery("select mobile from detail where mobile='"+num+"'", null);

      if (cc.moveToFirst()) {
          do {

               am = cc.getString(cc.getColumnIndex("mobile"));

             } while (cc.moveToNext());

      }

      Intent i=new Intent(c,Update.class);

      i.putExtra("value",am);
      c.startActivity(i);

  }

});

    return ListView;
  }

    }
</code>
//It show all the data in list view with update button and check box in list view. There is delete button which is suppose to delete all the item which is checked.
//Delete button is on main activity where list view is added.
Comment: what is a question in your "question" ?
Comment: I want to know how to delete the checked item from database, in listview.
Comment: see `SQLiteDatabase#delete`
Comment: I want to delete only item which is checked and that also from database. I am using custom listview.
Comment: i think nobody will want to read such badly formatted code... do something with it
Answer: You can create a method in your DataBase class and pass the table name and entry to be deleted along with id if any.Call the method at onClick of ListView item.
<code>public void deleteEntry(String tableName,String columnName,String id)
          {
              openDatabase();
              database.delete(tableName, columnName + " = ?",new String[] { id });
              closeDatabase();
          }
</code>


Rebar ./bin/sp restart report {'cannot load',asn1rt_nif,get_files} and can not start

Question: Environment
Mac OS X 10.10.5
Erlang/OTP: 17.5
rebar 2.6.0 17 20150818_094957 git 2.6.0-16-g3239e74-dirty

It is an example of application from the book Programming Erlang. I have git push to github
Steps to reproduce the error
build

$ git clone https://github.com/mingchaoyan/sellaprime.git
...
$ cd sellaprime
$ rebar prepare-deps
...
$ rebar compile
...

release

$ mkdir rel
$ cd rel
$ rebar create-node nodeid=sp
...

edit reltool.config as follow
```
%% -*- mode: erlang -*-
%% ex: ft=erlang
{sys, [
       {lib_dirs, []},
       {erts, [{mod_cond, derived}, {app_file, strip}]},
       {app_file, strip},
       {rel, "sp", "1.0.0",
        [
         kernel,
         stdlib,
         sasl,
         goldrush,
         lager,
         sp
        ]},
       {rel, "start_clean", "",
        [
         kernel,
         stdlib
        ]},
       {boot_rel, "sp"},
       {profile, embedded},
       {incl_cond, derived},
       {excl_archive_filters, [".*"]}, %% Do not archive built libs
       {excl_sys_filters, ["^bin/(?!start_clean.boot)",
                           "^erts.*/bin/(dialyzer|typer)",
                           "^erts.*/(doc|info|include|lib|man|src)"]},
       {excl_app_filters, ["\.gitignore"]},
       {app, goldrush, [{mod_cond, app}, {incl_cond, include}, {lib_dir, "../deps/goldrush"}]},
       {app, lager, [{mod_cond, app}, {incl_cond, include}, {lib_dir, "../deps/lager"}]},
       {app, sp, [{mod_cond, app}, {incl_cond, include}, {lib_dir, ".."}]}
      ]}.

{target_dir, "sp"}.

{overlay, [
           {mkdir, "log/sasl"},
           {copy, "files/erl", "\{\{erts_vsn\}\}/bin/erl"},
           {copy, "files/nodetool", "releases/\{\{rel_vsn\}\}/nodetool"},
           {copy, "sp/bin/start_clean.boot",
                  "\{\{erts_vsn\}\}/bin/start_clean.boot"},
           {copy, "files/sp", "bin/sp"},
           {copy, "files/sp.cmd", "bin/sp.cmd"},
           {copy, "files/start_erl.cmd", "bin/start_erl.cmd"},
           {copy, "files/sys.config", "releases/\{\{rel_vsn\}\}/sys.config"},
           {copy, "files/vm.args", "releases/\{\{rel_vsn\}\}/vm.args"}
          ]}.
```

then

$ rebar generate
...

start

$ cd sp
$ ./bin/sp start
$ ./bin/sp getpid
...
$ ./bin/sp attach

start an another erlang shell
erl -name 'email@example.com' -noinput -noshell -eval "rpc:call('firstname.lastname@example.com', init, restart, [])" -setcookie sp

then the first erlang shell will report
email@example.com)1> {"init terminating in do_boot",{'cannot load',asn1rt_nif,get_files}}

How this happened?
And why asn1rt will be released, actually I didn't config it in reltool.config
Thank you!
Answer: You can find an answer in this old rebar issue: you need to prevent the boot script from loading the crypto module. To do this, edit the sp/bin/sp script and remove -mode embedded from the CMD variable setting, changing this:
CMD="$BINDIR/erlexec $SLIM_ARGS -boot $RUNNER_BASE_DIR/releases/$APP_VSN/$BOOTFILE -mode embedded -config $CONFIG_PATH -args_file $VMARGS_PATH"

to this:
CMD="$BINDIR/erlexec $SLIM_ARGS -boot $RUNNER_BASE_DIR/releases/$APP_VSN/$BOOTFILE -config $CONFIG_PATH -args_file $VMARGS_PATH"


SQL server 2008 domain change

Question: In the near future, my organisation will have to change both the machine name and the Windows domain for one of our SQL servers.  The server is running SQL Server 2008 Enterprise Edition and the OS is Windows Server 2008 Standard edition.
I have found good references to handle the change of machine name, but can anyone help with what should be done to accommodate the change of domain?
Any help much appreciated.
Answer: I believe the only thing you'd need to change when you change your domain is the user account access on the server. When you installed SQL Server, the Setup process granted certain rights to the account you're using to run the SQL Service. If this was a domain account (ex. OLDDOMAIN\SQL_Proxy), then you'll need to grant those same rights to the proxy account on your new domain (ex. NEWDOMAIN\SQL_Proxy).
If, on the other hand, you're using "LOCAL SYSTEM" to run your SQL Service, you shouldn't need to make any changes at all, as this account will continue to have enough rights to run the SQL Service.
Please post back after you run this process - I'd be interested to know if you ran into any hurdles during the conversion.
Comment: Before changing the domain on the machine, make sure that you have a login that uses SQL server authentication that has full control over the databases that ISN'T a domain account (Windows Authentication), as you will no longer have access to that domain account.
Comment: @Fase - That's a good point, a SQL Account with SA rights would be helpful. Though it's one of the first things I do, I've noticed that most people don't remove "BUILTIN\Administrators" from the SQL Server, which has SA rights by default. If that group is still there, the local administrators on the servers will still have full rights on the SQL Server and can also be used to set up new domain users.

SQL server 2008 domain change


I go into Falsetto at C5?

Question: I'm not a really experienced singer, so I tried to find my vocal range and I cannot go above C5 without going into my falsetto. If i push myself hard enough I can get a really rough B4 but I literally cannot go into C5 without going into my falsetto. It's super annoying because I can't sing 95% of the songs I listen to (Also, I have a really good voice and I really want to become a singer) - It's just my dumb vocal range holding me back :/. I'm 16, male.
this causes really big problems when I sing, for example when im singing a song and the notes suddenly spike up, my transition from normal voice to falsetto voice is just so ugly and rough.
what do i do?
Comment: What to do? Change the keys of the songs. If you can't sing along with a track, you can't do it. I can't run as fast as Usain, so I don't go running with him! Changing key is what singers need to do to even get a good recording done - they find a key in which every note sounds good.
Comment: Do you mainly listen to songs sung by men or ladies? A man trying to keep singing pace with the ladies is on a futile quest, I believe. The ladies will sing too high too often for the men...
Answer: I'm no expert, but that sounds like a perfectly normal tenor range to me.  What singers are you listening to?
You could try transposing to another key, or singing in the same key but down an octave, or adjusting the melody line to avoid the high notes.
Do whatever sounds good and doesn't hurt.
There are plenty of great singers with ranges more limited than yours.
If you have the opportunity for a voice teacher, take it.  It'll be fun and you'd probably learn a lot even from only a few lessons.  Compared to any of us, they'll be able to give you much better answers to any questions about your voice.
Comment: @marcellothearcane you're asking to quantify what ought to be a personal experience, for whom results differ
Comment: How much can a voice teacher enhance the range?
Answer: B4 in the modal voice is an incredibly difficult note to reach!  Who are you listening to that goes higher than that?  The big note in Nessun Dorma is a B4 for Christ's sake!  I consider myself very lucky to have the vocal range I have, I've got a decent tenor range that covers me for everything I want to sing.  And despite that, there's no way I'm hitting a C5 in my modal voice, not even CLOSE!
Perhaps what you really need to work on is improving the quality of your falsetto register: if you don't use it all that much when you sing then it's probably quite weak: you don't use that part of your voice often when you speak, so it rarely gets used at all. You need to practice singing in your falsetto so that you feel fully in control of both of your vocal registers.  You also want to train the low end of your falsetto, so that you have as much overlap between your 2 vocal registers as possible.
You need to give yourself the physical tools to make the best performance choices about how you sing a passage that you know will at some point end up in your falsetto range: choose the point at which you transition based on what makes sense musically, rather than just going up and up until you run out of modal voice and then "making do with falsetto".  And, similarly, if you know a certain passage will bring you into your falsetto range, you need to consider how much "power" you're going to give the modal voice notes leading up to it, in order that the falsetto notes don't seem underwhelming.
This answer applies less to classically trained opera singers, who I believe rarely use falsetto, and also have a very different singing technique that functionally maximises the range physically possible from a singer.
Answer: You need to find your range, and be comfortable with it. Tenor tesituras are less common, actually, and are very desirable. Also, careful practice/warmup can allow you to "stretch" your range, but make sure you aren't straining because that could cause damage to your voice.

I go into Falsetto at C5?


oracle rownum transfer to t-sql row_number() over with error

Question: the simplified origin pl_sql is
select t.*, staff_no||'-'||rownum as pk
from (select * from hrmmgr.posting where type not in ('X','C') order by staff_no, postingdate) t;

I try to rewrite it to run in sql server as
select t.*, staff_no + '-' + t.rownum as pk
from (select row_number() over (order by staff_no, postingdate) as rownum, *
from posting where type not in ('X','C') order by staff_no, postingdate) t

but error

The ORDER BY clause is invalid in views, inline functions, derived
tables, subqueries, and common table expressions, unless TOP, OFFSET
or FOR XML is also specified.

is returned.
If I try to add OFFSET as shown in the error message as follow:
select t.*, staff_no + '-' + t.rownum as pk
from (select row_number() over (order by staff_no, postingdate OFFSET 0 ROWS) as rownum, *
from posting where type not in ('X','C') order by staff_no, postingdate) t

then the following error is shown.

Incorrect syntax near 'ROWS'.

So how to rewrite my plsql to  run in sql server?
Answer: The ORDER BY clause in the subquery appears to be the problem, and SQL Server is telling you that ORDER BY cannot appear in a subquery without also using something like TOP.  However, it should not even be necessary here, because your call to ROW_NUMBER already specifies an ORDER BY clause to be used when assigning row numbers.  Try this version:
SELECT t.*, staff_no + '-' + t.rownum AS pk
FROM
(
    SELECT ROW_NUMBER() OVER (ORDER BY staff_no, postingdate) AS rownum, *
    FROM posting
    WHERE type NOT IN ('X', 'C')
) t;

Comment: Oh, I misunderstand the order by error message is mean the order by in row_number() over.


Numa lista de checkbox, saber as que estão checked

Question: Na minha aplicação estou a imprimir uma lista de dados vinda base de dados, e em cada item da lista estou a colocar uma checkbox, como mostra a seguinte imagem:

Agora ao clicar em "Iniciar cópia" quero seleccionar os itens da lista que estão seleccionados, e o respectivo value.
A imprimir a lista na view estou a fazer:

    @foreach (var item in ViewBag.estabelecimentos)
    {
        <input type="checkbox" value="@item.IdFilial" name="filialCopia"/>@item.Nome

    }

<button type="button" class="btn btn-primary" onclick="FazerCopiaEstabs()">Iníciar cópia</button>

A ViewBag.estabelecimentos é a minha lista de dados retornados do controller.
Agora para ir buscar os valores das checkbox selecionadas estou a fazer (javascript):
function FazerCopiaEstabs() {
    var fields = $("input[name='filialCopia']").serializeArray();
    $.each(fields, function (index, itemData) {
        alert(itemData.val());
    })
}

No código acima só estou a tentar ir buscar o value de cada checkbox seleccionada, para depois enviar para o controller e iniciar a cópia de dados. Mas sem sucesso... Não estou a conseguir ir buscar as dropbox seleccionadas
Answer: Você pode fazer da seguinte forma:
function FazerCopiaEstabs() {
        $("input:checkbox[name=filialCopia]:checked").each(function () {
            alert(this.value);
        });
    }


How to remove relatively aligned view and keep other views intact?

Question: I have a problem with removing views from relative view. The code below programatically adds phone fields and then appends switches below. When adding fields it's all good, but I can't find the way to easily remove them so i.e. there are three fields and I want to delete second or third the ones below are left without view they anchored to.

Code:
private int lastCreatedView;
    private int tokensIteration;
    private int addButtonId, switch1Id, switch2Id;
    private ArrayList<Integer> editTextsIds = new ArrayList<>();
    private Contact contact;

    private void setPhoneField(String number){
        EditText editText = new EditText(new ContextThemeWrapper(this, R.style.ContactDetailsEditText));
        editText.setId(View.generateViewId());
        editText.setText(number);
        editText.setHint(R.string.contact_details_activity_hint_phone_number);
        editText.setTextColor(getResources().getColor(android.R.color.white));
        editText.setEms(10);
        editText.setInputType(InputType.TYPE_CLASS_PHONE);
        editText.setImeOptions(tokenizer != null && tokenizer.hasMoreTokens()
                ? EditorInfo.IME_ACTION_NEXT : EditorInfo.IME_ACTION_DONE);
        LinearLayout.LayoutParams editTextParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        editText.setLayoutParams(editTextParams);

        editTextsIds.add(editText.getId());

        TextInputLayout til = new TextInputLayout(new ContextThemeWrapper(this, R.style.ContactDetailsEditText));
        til.setId(View.generateViewId());
        RelativeLayout.LayoutParams textInputLayoutParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        int viewToAttach = lastCreatedView == 0 ? R.id.input_layout_company : lastCreatedView;
        textInputLayoutParams.addRule(RelativeLayout.BELOW, viewToAttach);
        textInputLayoutParams.addRule(RelativeLayout.END_OF, R.id.contact_photo);
        til.setLayoutParams(textInputLayoutParams);
        til.setTag(editTextsIds.size());

        lastCreatedView = til.getId();

        ImageView phoneButton = new ImageView(this);
        phoneButton.setImageResource(R.drawable.ic_phone_black_48dp);
        phoneButton.setPadding(5,5,5,5);
        phoneButton.setScaleType(ImageView.ScaleType.FIT_END);
        phoneButton.setColorFilter(Color.argb(255, 255, 255, 255));
        RelativeLayout.LayoutParams phoneButtonParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        phoneButtonParams.addRule(RelativeLayout.START_OF, til.getId());
        phoneButtonParams.addRule(RelativeLayout.ALIGN_TOP, til.getId());
        phoneButtonParams.addRule(RelativeLayout.ALIGN_BOTTOM, til.getId());
        phoneButton.setLayoutParams(phoneButtonParams);
        phoneButton.setTag(editTextsIds.size());
        phoneButton.setOnClickListener(view -> {
            Intent call = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + number));
            startActivity(call);
        });

        til.addView(editText);

        contactContainer.addView(til);
        contactContainer.addView(phoneButton);

        ImageView removeNumber = new ImageView(this);
        removeNumber.setId(View.generateViewId());
        removeNumber.setVisibility(tokensIteration > 0 ? View.VISIBLE : View.GONE);
        removeNumber.setImageResource(R.drawable.minus);
        RelativeLayout.LayoutParams removeNumberParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        removeNumberParams.addRule(RelativeLayout.END_OF, til.getId());
        removeNumberParams.addRule(RelativeLayout.ALIGN_TOP, til.getId());
        removeNumberParams.addRule(RelativeLayout.ALIGN_BOTTOM, til.getId());
        removeNumber.setLayoutParams(removeNumberParams);
        removeNumber.setTag(editTextsIds.size());
        removeNumber.setOnClickListener(view -> {

            for(View v : getViewsByTag(contactContainer, view.getTag()))
                contactContainer.removeView(v);

        });

        if(tokensIteration > 0) contactContainer.removeView(findViewById(addButtonId));
        ImageView addNumber = new ImageView(this);
        addNumber.setId(View.generateViewId());
        addNumber.setImageResource(R.drawable.plus);
        addNumber.setPadding(tokensIteration > 0 ? 5 : 0, 0, 0, 0);
        RelativeLayout.LayoutParams addNumberParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        addNumberParams.addRule(RelativeLayout.END_OF, removeNumber.getId());
        addNumberParams.addRule(RelativeLayout.ALIGN_TOP, removeNumber.getId());
        addNumberParams.addRule(RelativeLayout.ALIGN_BOTTOM, removeNumber.getId());
        addNumber.setLayoutParams(addNumberParams);
        addNumber.setTag(editTextsIds.size());
        addNumber.setOnClickListener(view -> {
            //Toast.makeText(this, "Function not available", Toast.LENGTH_SHORT).show();

                setPhoneField("");
                setSwitches();
            }
        );

        addButtonId = addNumber.getId();

        contactContainer.addView(removeNumber);
        contactContainer.addView(addNumber);

        setSwitches();
    }

    void setSwitches(){

        RelativeLayout.LayoutParams recordCallsParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        recordCallsParams.addRule(RelativeLayout.BELOW, lastCreatedView);
        recordCallsParams.addRule(RelativeLayout.ALIGN_START, lastCreatedView);
        recordCallsParams.addRule(RelativeLayout.ALIGN_END, lastCreatedView);

        if(switch1Id != 0 && switch2Id != 0){
            contactContainer.updateViewLayout(findViewById(switch1Id), recordCallsParams);
            return;
        }

        Switch recordCalls = new Switch(this);
        recordCalls.setText(R.string.contact_details_activity_record_calls);
        recordCalls.setTextColor(getResources().getColor(R.color.white));
        recordCalls.setSwitchPadding(5);
        recordCalls.setId(View.generateViewId());
        recordCalls.setLayoutParams(recordCallsParams);
        recordCalls.setChecked(contact != null && contact.getIsRecordCalls());
        switch1Id = recordCalls.getId();

        Switch switchPrivate = new Switch(this);
        switchPrivate.setText(R.string.contact_details_activity_private_contact);
        switchPrivate.setTextColor(getResources().getColor(R.color.white));
        switchPrivate.setSwitchPadding(5);
        switchPrivate.setId(View.generateViewId());
        RelativeLayout.LayoutParams switchPrivateParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        switchPrivateParams.addRule(RelativeLayout.BELOW, recordCalls.getId());
        switchPrivateParams.addRule(RelativeLayout.ALIGN_START, recordCalls.getId());
        switchPrivateParams.addRule(RelativeLayout.ALIGN_END, recordCalls.getId());
        switchPrivate.setLayoutParams(switchPrivateParams);
        switchPrivate.setChecked(contact != null && contact.getIsPrivateContact());
        switch2Id = switchPrivate.getId();

        contactContainer.addView(recordCalls);
        contactContainer.addView(switchPrivate);
    }

    private static ArrayList<View> getViewsByTag(ViewGroup root, Object tag){
        ArrayList<View> views = new ArrayList<>();
        final int childCount = root.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = root.getChildAt(i);
            if (child instanceof ViewGroup) {
                views.addAll(getViewsByTag((ViewGroup) child, tag));
            }

            final Object tagObj = child.getTag();
            if (tagObj != null && tagObj.equals(tag)) {
                views.add(child);
            }
        }
        return views;

Comment: I agree with reply from donfuxx below but in case that is not an option for you maybe you can organize the fields in a listview. This way it can be more dynamic.
Comment: Could You elaborate more on that, please? You mean whole `phoneField` as an object/view to put in the list?
Comment: You can have a layout within the ListView with the layout containing an edittext. So each row of the ListView will be an EditText. You can update the ListView any time you need to add/remove a field.
Answer: Do you really need to completely remove the view? If you just want to hide some view without messing with the layout you can set it to INVISIBLE:
phoneButton.setVisibility(View.INVISIBLE);

BTW: I'd recommend you use layout resource files. It is much easier to work with especially when your layouts get more complex and you get the idea to make your app compatible with multiple screen sizes, screen orientations etc.
Comment: I would love to make a phone field a layout resource view. For now, I just don't know how to implement it properly, especially when it comes to aligning


Java.time from offset to timezone name

Question: Trying to convert a various of time formats to a unified format.
One format is
"uuuu-MM-dd'T'HH:mm:ss-5000"

need to convert to the timezone format:
"uuuu-MM-dd'T'HH:mm:ss EST"

Using the following code, but it only gives the timezone as "-05:00", but not the expected "EST".
    String targetFormat = "uuuu-MM-dd'T'HH:mm:ss z";
    String origFormat = "uuuu-MM-dd'T'HH:mm:ss.SSSZ";
    String origStr = "2018-02-05T17:25:18.156-0500";
    ZonedDateTime time = ZonedDateTime.parse(origStr, DateTimeFormatter.ofPattern(origFormat));
    String targetStr = time.format(DateTimeFormatter.ofPattern(targetFormat));

Output from the above is:
2018-02-05T17:25:18 -05:00

How to get the expected:
2018-02-05T17:25:18 EST

Answer:
-05:00 is not actually a timezone. It's just an offset: a difference of 5 hours behind UTC, and you can't really map it to a single timezone.
At the date you're using (Feb 2nd 2018), there are 47 timezones using -05:00 *, including areas outside US - and lots of them don't call their timezones "EST", such as Lima, that uses "PET" (Peru Time) or Bogota, that uses "COT" (Colombia Time). Regardless of the names used in each place, they're all using -05:00 at the date and time you're using.
Anyway, when you parse an offset such as -05:00, the API can't know what timezone you are referring to, because of the reasons listed above (there's more than one and the API itself can't decide it). You must arbitraryly choose a timezone, and then you convert your parsed ZonedDateTime to that zone:
....
ZonedDateTime time = ZonedDateTime.parse(origStr, DateTimeFormatter.ofPattern(origFormat));

// convert to some arbitrary timezone
time = time.withZoneSameInstant(ZoneId.of("America/New_York"));

I choose "America/New_York" because it's one that uses "EST" in Feb 2018. With that, your targetStr will be:

2018-02-05T17:25:18 EST

Change the timezone name to the one you want. Note that for dates in June, when Daylight Saving Time is in effect in New York, it'll return "EDT".

*: I'm using JDK 8 with 2018e TZ data files, so this number might differ in your environment.

Java.time from offset to timezone name


Mainframe and frontend access

Question: So I understand mainframes process data in batches. With millions of transactions per second, how is the frontend getting the most up to date data if the next batch hasn't run?
Answer: In a very simple view: The word 'mainframe' relates to a type of computer hardware architecture, which differs from the Desktop PC design. Mainframes are usually designed for use in large organizations and it also must have an operational system and applications designed accordingly to their purpose.
In the last decades the Desktop PC architecture evolution was astonishing, substituting  and confining even more the mainframes to very specific uses.
Your question is relevant. Indeed, online transactions must somehow be stored and computed in real time, and they are.
Many companies don't need a mainframe for this, nowadays it's usual to find a powerful desktop architecture computer running ERP applications capable of online processing and batch analytical processes.  Online transactions occur in real time retrieving and storing data in matter seconds.
The batch processes aims different purposes, running usually on a overnight basis in order to produce Analytical data,for business support, reports, data consolidation, etc.  If needed, of course mainframes also could do the same.
Comment: Thank you. So to be clear, it's not common for banks and other financial companies yo do rtp on mainframes?
Comment: If you're talking about "thin clients", and RDP remote access, then generally they'll go with a "server farm" of multiple servers that are desktop architecture but in a data center somewhere. So many programs are written for the desktop architecture now that it makes a lot more sense to run them on that architecture directly. But large financial institutions may also have a mainframe for large batch processing of data sets generated by those RDP farms.
Comment: Mainframes are quite capable of interactive operations and, with NUMA and virtualization, PCs are starting to look and behave more like mainframes. The nomenclature is increasingly becoming a marketing differentiator rather than a technical one.
Comment: Yes, sure @MattMorrow,  big companies do have mainframes. I meant that desktop architecture is expanding and taking place where only mainframes used to be.

Mainframe and frontend access


Custom error message + hide generic message

Question: I'm working with the Brightcove Drupal module, and want to override generic error messages for users when an upload fails. I've added a custom error - but the generic message is still displaying before the custom message as follows:

Notice: Undefined index: widget in brightcove_field_browser_validate() (line 296 of /path/to/sites/all/modules/my_module/my_module/my_module.module).
This video is currently unavailable. Please note, it may take several minutes for large files to finish processing after being uploaded.

I can post code from the module if needed, but wasn't sure if this could be updated globally to always hide this type of message for users while still keeping custom 'user-friendly' messages.
Thanks!
Answer: you can use the theme_status_messages function to do search and suppress certain messages.
The String Overrides module lets you do global text replacements which should work in your case.
Comment: Looking into the [String Overrides](http://drupal.org/project/stringoverrides) module, still trying to identify the original string I need to replace. Will also read up on theme_status_messages function.

Thanks for the tip


How do I set up a .pem login for my servers?

Question: I have a couple of ubuntu droplets on digital ocean
I have set up a username password based login. But I am not comfortable with the idea.
What i would ideally like is a amazon like login where I have a identity.pem sort of file. I will share this file with the people in the team. They login by saying ssh webuser@website_ip after doing an ssh-add
How do I set up a login like this?
I do not want to add ssh-keygen on each developers machine and then add the contents of the public key to .ssh/authorised_keys. For one thing, this seems like too much work for each developer.
Let me know if it is possible. Thanks
Comment: Giving people a shared login really is a bad idea. You really should just get them all to generate ssh keys it takes a couple of minutes.
Comment: Sometimes, it is not viable to have the SSH keys for each specific user. I work for a law firm, and we use shared PEM keys all the time.
Answer: This is a straightforward enough process, though as has already been commented, a shared login is an extremely bad idea. In this situation, all users have equal access and you won't be able to track what work is carried out as which user. With that in mind however, the following process will give you what you want. On the machine in question, while logged in as the shared user:
Lets keep everything in one place:

cd .ssh/

Generate the file id_dsa from which we will create the PEM file:

ssh-keygen -t dsa -b 2048

Generate the private key PEM file:

openssl dsa -in id_dsa -outform pem > pk_dsa.pem

Generate the public key PEM file for distribution to the users:

openssl dsa -in pk_dsa.pem -pubout -out pub_dsa.pem

The final pub_dsa.pem is the file you're looking for.
Comment: This is not working for me, Still asking for password as well passphrase.
I am using ubuntu 14.04
Comment: Hello! My server tells me that DSA has to be 1024 bytes. The final pem file that I have distrivuted asks me for a passphrase. Trying to remove passphrase by `openssl rsa -in  -out ` tells me unable to load Private key. `openssl rsa -in  -check` tells `139688383772488:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY`


Javascript carousel css transition not working

Question: hi im wondering why my css transition is not working. the carousel does the loop and and all, but my transition only works when i open dev tools and point at the element with my mouse.
heres the code : https://codepen.io/anon/pen/zXQpNo
thanks for your help
var slides = Array.from(document.querySelectorAll(".slide_element"));
    var i = 0;
    function test(){
        if(i === slides.length - 1){
        slides[slides.length - 1].classList.remove("displaying");
        i = 0;
        slides[i].classList.add("displaying");
         }
        else{
            slides[i].classList.remove("displaying");
            slides[i+1].classList.add("displaying");
            i++;
        }
    }
    setInterval(() => {
        test();
    }, 3000);

Comment: Looks like it works for me without having to open dev tools, https://jsbin.com/sufejewuxe/1/edit?html,css,js,output does that work?
Comment: Nah it doesnt its really weird! but i tried the css offered by Josef and it works like a charm now :) thanks for the help tough.
Answer: in "slide_element" remove display: none; and the transition add to it (all) so it will become like this transition: all .3s;
and set it to absolute positioning, so your css would look like this:
.slide_element{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    transition: all 0.3s;
    transform: translateX(1000px);
}

Comment: sweet! that works, i was gonna go crazy there for a sec. thanks.
Comment: I'm glad it helps, actually I ran into the same problem a couple weeks ago
Comment: oh glad to see that im not the only one that runs into problems then, and here i tought i was some kinda future bad developper or something. again thanks for the help.


Why does soloing over the pentatonic minor of the fifth of a major scale sound so good?

Question: If I play a pentatonic minor scale a fifth above the root, it sounds really good. Why?
As an example, if the band is playing a vamp on A major, I can solo on an E minor pentatonic scale for days.
Is there a theoretical reason for this or is it just a happy accident?
Answer: There are different ways to see it. Your E minor pentatonic fits there, because the notes of the E minor pentatonic added to an A major chord either support the A major, or add to it creating more complex chords. Additionally the G note does something that's not found in plain A major scale, making it a dominant chord (A7). When vamped over instead of resolving (to e.g. a D chord), you can think of a dominant chord as sounding bluesy or jazzy.
Let's see which chord is created as a result of adding each of the notes of the E minor pentatonic scale:

(1) A major + E : A major
(2) A major + G : A7
(3) A major + A : A major
(4) A major + B : Aadd9
(5) A major + D : Aadd11, or if the others are just playing an A "power chord" without C#, then D added to it is an Asus4.

Or if you think that you're playing all of the notes at the same time, arpeggiating a chord, or actually playing them as a chord, and leaving out the notes that are already in A major (E and B), you create
- A major + G + B + D = A11. An A11 chord is: A, C#, E, G, B, D.
... and G+B+D is G major - so depending on how you play the notes, you might be making it sound a bit like the chords A major and G major are alternating. The combined notes from A major and E minor pentatonic (A, B, C#, D, E, G) are the same as a combination of A major and G major triads.
Or you can think that you're (almost) creating the sound of the A mixolydian mode, if the backing chords stay in A major all the time, keeping the tonic fixed to A. (The feeling of a tonic i.e. home note is required in modes) The A major chord has the notes: A, C#, E. Add the notes from E minor pentatonic, and you get A, B, C#, D, E, G. The only thing missing form A mixolydian is F#.
Why does it sound good? Maybe you like the sound of the A mixolydian mode or the A11 chord. Maybe you like being able to create a harmony that's a bit more interesting than plain vanilla pop songs, and you can do it without playing any wrong notes? Who knows. I tried it, and I got tired of playing E minor pentatonic on an A major vamp after about two minutes. :) ... edit: it became more interesting again after awhile, when I forced myself to just keep playing and find different things to do with the notes. ;)
Comment: +1 for "almost creating the sound of the A mixolydian..."  I was just about to add that answer.
Answer: Perhaps you like the sound of the 9th. Why wouldn't you? The scale has the root, the fifth and the seventh, and then you add the ninth. Leaving out the third probably has a big effect---it doesn't tie you down to a particular sound (major or minor). It's more rock than blues.
Answer: The answers so far provide a lot of good info.  Have you tried any other mixtures of modes or degrees?  Like D min penta on A, or E Phrygian, E Major?  The reason I ask is that there are "compatible keys" in western music theory and no surprise they fall on the circle of 5ths (or 4ths depending on which direction you go).  You can see this from the tetrachords that make up the major scale.  (Do, Re, Mi, Fa) has the same structure as (Sol, La, Ti, Do).  For any key you are in there is a compatible key a 5th above you and one below you.  For example in the key of C, the keys of G and F are compatible.  They differ by only one note from the original key, very important notes to be sure but they are almost identical.  It is common to modulate key to one that is in this group and to use these groupings and some other devices to walk to other keys that are not compatible. The transition from C to F (or G) is easy on the ear and one can play around with these transitions without sacrificing musicality.  If you were to play the G major scale over C in the key of C this would be the same thing as raising the 4th of the Key of C.  The 4th is typically viewed as an avoid note (especially in Jazz) and the raised 4th essentially means you are playing C Lydian.  Many Jazz musicians default to Lydian on the 1 for solo ideas.  They like that augmented 4th.  I think you are experiencing a similar idea with playing E min pent over an A vamp.  E and A are compatible.  It might fun to explore other modes in this way.
Another point relevant to answering your question is that a one chord vamp doesn't really force one into a particular key.  This can be a great opportunity to explore more than the blues.  On tunes like this you can basically solo in any key that has A as a chord in the key (at least as a starter).  But in fact you can solo "out of key".  The Minor pentatonic and blues scale work over major chords even though they have a minor 3rd (I'm referring to A min pent over A maj or A7).  In my opinion this is a cultural trait of "The Blues" and the thing that makes it sound so cool.  You are adding the b3 (or #2 if you want to think of it that way) over the 3 and this creates dissonance, a sad feeling that is "blue".  The b5 does the same.  As others have said you are almost in A mixolydian and that works well over A.  I would say that you are in several possible keys at once and you could toggle back and forth with many musical ideas in this case.
Answer: It's the same idea as a lot of beginner players use for a 12 bar 'blues'. If they know the pentatonic minor scale notes in, say, A, then they'll play those over all three chords in a 12 bar in A. That includes over the other two chords - D and E. So particularly over the D chord, it's exactly what you do. But it works (by and large) over all three.
There are always going to be a couple of 'avoid' notes when doing this, and in your case, the D note although it doesn't have to be avoided, is best used on a non-emphasised part of a bar - your ears will often make that happen.
As piiperi has explained, it works because it adds extra notes which happen to fit well with the chord. The Am pent. notes are A C D E G. Your Em pent. notes are E G A B D. So the common ones are A D E G. Leaving only the B instead of C. As a 9th (of A) it's going to fit well over A.
Let's take it a little further. That 12 bar in A. Add the notes from Dm pent. into the mix. D F G A C. Again, plenty of common notes - D G A in all of them! No wonder just using Am pent. fits (nearly) all! The only note standing on its own here is F. So an 'avoid note' for A and E bars. But, lots of players still use it, anywhere they like in a 12 bar. In fact, I go as far as to tell students that any note can be made to fit anywhere in any chord sequence - providing they put it in musically, and that fact gets proved over and over in many great pieces. And I'm not just considering jazz here!
Answer: Lots of good answers here.  For those who are visually inclined, here's an example of why the minor 5th pentatonic sounds so good, especially over a mixolydian scale.

Source: https://www.guitarscientist.com/generator/index.php?frb=227yeUThPvNDTt4
(I'm not affiliated with Guitar Scientist in any way, I just like to use them to draw fretboard diagrams.)
Answer: It's not so much that a pentatonic sounds good, more that it doesn't sound bad!   Self-taught pianists often play 'on the black keys' in Gb major, because mistakenly-hit 6ths and 9ths are a lot better than 7ths and 4ths.
You can noodle inoffensively on a pentatonic.  It doesn't have as many wrong notes!
Comment: The OP was playing E minor pentatonic over A major, that's what the question was about. Your answer implies that any pentatonic scale could be played on top of anything.
Comment: Yes, it does, doesn't it!


Stylesheets not loading

Question: Has anyone successfully dealt with this kind of error? [Error] Did not parse stylesheet at 'https://*****.***/core/assets/vendor/jquery.ui/themes/base/core.css?s2pf9q' because non CSS MIME types are not allowed in strict mode. This shows up in the console.
The site works fine with aggregation enabled, but none of the style sheets load when it is turned off. I get 56 errors like the one above. If I go directly to the URL mentioned in the error message, the css shows up.
This only happens on the production server, running Apache 2.4 on Ubuntu 20.04.6 LTS. The server is overprovisioned, and has plenty of resources. It works fine locally (ddev). This is a Drupal 9 site, with a theme based on ZURB Foundation 6 9.0.0-beta1. There are lots of references to this error on various support sites, but none of them are applicable to my situation.
Comment: What does `curl -I ""` say its MIME type is? You can also get this information on the "network" tab of your browser's dev tools by clicking on that CSS resource. Most dev tools will show the response headers there.
Comment: What do you see when you access the path directly? This often is a result when the CSS file does not actually exist, as an HTML 'page not found' page with an HTML mime type is returned.
Comment: @ Jaypan The question reads "If I go directly to the URL mentioned in the error message, the css shows up." The web server is serving the file but probably with the wrong MIME type.
Comment: `curl -I ""` returns text/html from the server, and text/css locally. Can I change that somehow?
Comment: The /etc/mime.types file on the server does contain `text/css                                        css`, so it should be returning text/css, no?
Comment: The presence of a config file doesn't automatically mean the web server is set up to set mime types.
Answer: Library declaration
First of all be sure to load your custom assets in the right way like describe in the Drupal documentation : Adding assets (CSS, JS) to a Drupal module via *.libraries.yml
Assets preprocessing
Fox fixing the problem you can try to disable the assets preprocessing from this page /admin/config/development/performance or with this commands and then clear cache :
drush -y config-set system.performance css.preprocess 0
drush -y config-set system.performance js.preprocess 0
drush cr

File permissions
Another reason to this error might be a file permission problem.
To be sure to have correct permissions you should run following commands (assuming you SSH user is user) :
cd /var/www/drupal/web
chown -R user:www-data .
find . -type d -exec chmod u=rwx,g=rx,o= '{}' \;
find . -type f -exec chmod u=rw,g=r,o= '{}' \;

cd /var/www/drupal/web/sites
find . -type d -name files -exec chmod ug=rwx,o= '{}' \;
find ./*/files -type d -exec chmod ug=rwx,o= '{}' \;
find ./*/files -type f -exec chmod ug=rw,o= '{}' \;

Go check the docs about that : Securing file permissions and ownership
Apache configuration
Check Administrator -> Configuration -> Media -> File System to personalize your tmp path (assuming /tmp). Make sure to use relative paths and have the right privileges for the Apache user (assuming user).
chown -R user:www-data /tmp
chmod 777 /tmp

In your Apache configuration be sure to disable mod_userdir and in your VirtualHost configuration or your HtAccess file set AllowOverride All.
Comment: This is the opposite of our problem. The aggregated css loads fine. All site assets are contributed modules and themes that work fine on other servers, so it is doubtful that your second comment would apply.
Comment: Have to try to disable assets preprocess at least ? If it's working it means that you have a script mode enabled in your Apache configuration. If not working it means that you have a file permission problem (chmod 755 sites/default/files)

Stylesheets not loading


What do you use for collaboration and code review?

Question: What project management solution can you use for grouping together related commits? Lets say you have a few hunderd modules and you need to make changes which affect 5 or 10 of these. Is there a solution that lets you open a ticket and track your subversion commits while keeping a group of people in the loop?
Comment: Use Git and tag the commits.
Comment: More thinking of a collaboration platform. A place where changes can be discussed too.
Answer: This would depend on the size of your team.
A small team can settle for just using GIT/SVN (or any CVS really) and make sure that everyone pulls/fetches from the integration branch frequently as a habit. If needed, use email to inform everyone about code changes or do scheduled commits to integration branch. This way, instead of letting people know that you did a commit, you can tell people when to expect a commit.
If we are talking about a big team/s, Project Management tools like JIRA should have the flexibility to send an email to a watchlist once a task is done (effectively, a code was pushed) and provide other information about the finished task (such as Affected versions/modules)
Actually, there are different ways to answer your questions depending on the need and workflow of the team but hopefully I've provided some ideas for you here.


The closure of $(a;b)$ in an order topology

Question: Consider a linearly ordered set $(X; \prec)$ with its order topology.

Show that closure of $(a;b)$ is a subset of $[a;b]$. Under what conditions does equality hold?
Give an example of a strict inclusion.

I  solved part 1:
$$[a,b]=X \setminus((−\infty,a)∪(b,+\infty))$$
is closed and contains $(a,b)$ , so it contains the closure of $(a,b)$.
Furthermore, it equals the closure iff both endpoints are limit points of the interval.
But I cannot find example for strict inclusion.
Comment: Why isn't the answer accepted?
Answer: HINT: Consider the canonical strict linear order on the natural numbers $(\mathbb{N}; <)$.

What is $(2;4)$?
What is the closure of $(2;4)$?
What is $[2;4]$?


Select Condicional com outro Select

Question: Estou usando SQL Oracle. Eu preciso retornar um Select que dependendo do valor da coluna GRUPO_ECONOMICO_ID (precisa ser igual a 87) ele deve executar um Select, senão ele deve executar outro select... Acredito que estou próximo do que eu preciso, mas dispara um erro que que uma palavra-chave nao foi encontrada... O que estou fazendo de errado??
select CASE GRUPO_ECONOMICO_ID
       WHEN ((select GRUPO_ECONOMICO_ID from empresa where codigo = :TOKEN) = 87)
           THEN
               (SELECT emp.id
                from empresa emp
                where emp.grupo_economico_id = 87
                union
                SELECT emp.id
                from empresa emp
                WHERE codigo = (vou chumbar um token aqui ainda a ser criado, mas ele e diferente dos outros TOKENs aqui descritos)
           ELSE
               (SELECT emp.id
                FROM empresa emp
                WHERE emp.grupo_economico_id = (
                    SELECT grupo_economico_id
                    FROM empresa
                    WHERE codigo = :TOKEN
                ))
           END as total from empresa;

Comment: `where codigo = :TOKEN) = 87` este `where` não deveria ser `where GRUPO_ECONOMICO_ID  = 87`?
Comment: Creio que não por que esse cara faz uma pesquisa na tabela empresa pelo token que foi passado pelo usuário e ai poderá retornar 87... Então a condicional vem do (select GRUPO_ECONOMICO_ID from empresa where codigo = :TOKEN)
Comment: Confuso , ao menos para mim , poderia dar um exemplo com dados ?
Comment: Claro a ideia é que ao pesquisar sobre uma empresa X, o usuário recebe a informação de todas as empresas que pertencem ao mesmo grupo econômico dessa empresa X, certo? O que acontece e que existe um regra de select especifica para quando especificamente o grupo econômico for 87, então eu preciso de algum tipo de condicional (IF.. ELSE serve tambem) dentro do sql oracle para executar um select ou outro dependendo do grupo econômico (especificamente o 87).
Answer: No caso acho que o que está lhe atrapalhando seria indicar um campo na frente do CASE, o oracle permite fazer um case sem indicar essa chave.
select CASE
       WHEN ((select GRUPO_ECONOMICO_ID from empresa where codigo = :TOKEN) = 87)
           THEN
               (SELECT emp.id
                from empresa emp
                where emp.grupo_economico_id = 87
                union
                SELECT emp.id
                from empresa emp
                WHERE codigo = (vou chumbar um token aqui ainda a ser criado, mas ele e diferente dos outros TOKENs aqui descritos)
           ELSE
               (SELECT emp.id
                FROM empresa emp
                WHERE emp.grupo_economico_id = (
                    SELECT grupo_economico_id
                    FROM empresa
                    WHERE codigo = :TOKEN
                ))
           END as total from empresa;

Como está indicando o campo na frente do CASE, o oracle espera que seja uma comparação simples com essa chave, não consegui simular por preguiça de criar uma base de dados parecida.
Espero que ajude!

Select Condicional com outro Select


Showing that an algebraic set is not isomorphic to $\mathbb{A}^1$

Question: (For convenience, I'm assuming $\mathbb{K} = \mathbb {C}$.)

I'm trying to show that the algebraic set $\mathbb{V}(xz-y^2,x^3-yz,z^2-x^2y) \subseteq \mathbb{A}^3$ is not isomorphic to $\mathbb{A}^1$.

I already know that $X = \{(t^3,t^4,t^5) \in \mathbb{A}^3 \;|\; t \in \mathbb{A}^1 \} $, and that $\mathbb{I}(X) = \langle xz-y^2,x^3-yz,z^2-x^2y \rangle$.
If there were an isomorphism between the $\mathbb{A}^1$ and $X$, then $\mathbb{K}[\mathbb{A}^1] \cong \mathbb{K}[X]$. But $\mathbb{K}[\mathbb{A}^1] \cong \mathbb{K}[t]$, whereas $\mathbb{K}[X] \cong \mathbb{K}[t^3,t^4,t^5]$ by considering the homomorphism
$$\mathbb{K}[x,y,z] \rightarrow \mathbb{K}[t], \; x\rightarrow t^3, \; y\rightarrow t^4, \; z\rightarrow t^5$$
which has kernel $\mathbb{I}(X)$ and image $\mathbb{K}[t^3,t^4,t^5]$, so
$$\mathbb{K}[X] \cong \mathbb{K}[x,y,z]/\mathbb{I}(X) \cong \mathbb{K}[t^3,t^4,t^5]$$
Thus we would have that $\mathbb{K}[t] \cong \mathbb{K}[t^3,t^4,t^5]$, but this is not the case since the former is a UFD, whilst the latter is not, since for example $t^8 = t^3t^5 = (t^4)^2$ has two factorisations. Hence, $\mathbb{A}^1 \ncong X$.
Is this line of reasoning correct? Is there an easier way I could have gone about it?
Comment: That works fine. I wouldn't expect to simplify this significantly.
Comment: Dear Simon, your reasoning is quite correct but the hard part is the calculation of $I(X)$, which you chose not to reproduce, a perfectly legitimate choice. A more direct proof would be to show that $X$ is not smooth at the origin by using the jacobian criterion:  a calculation at the level of advanced calculus.
Comment: abdrido has now computed the jacobian in his  answer.
Answer: Alternative way is to observe that $X$ is not smooth at the origin. In other words, localization of $\mathbb{C}[x,y,z]/I$ at $\mathfrak{m}_0=\langle x,y,z\rangle$ is not regular, where $I=\langle xz−y^2,x^3−yz,z^2−x^2y\rangle$. But $\mathbb{C}[t]$ is smooth everywhere.
Let us verify the above claim. We can use the Jacobian criteria to test regularity (see for instance Eisenbud's Commutative Algebra, Chapter 16):
Suppose $k$ has char. $0$, and $I=(f_1,\dots,f_m)$ is an ideal in $S:=k[x_1,\dots,x_n]$. Suppose $\mathfrak{p}\supset I$ is prime and $I_\mathfrak{p}$ has codimension $r$ in $S_\mathfrak{p}$. Define the Jacobian matrix as
$$
J_{ij}=\frac{\partial{f_i}}{\partial x_j}
$$
Then $(S/I)_\mathfrak{p}$ is a regular local ring if and only if $J$ has rank $r$ in $S/\mathfrak{p}$.
(This is saying that regularity and smoothness are the same things in char. $0.)
Now in our case, we note that $I_{\mathfrak{m}_0}$ has codimension $>0$ in $\mathbb{C}[x,y,z]_{\mathfrak{m}_0}$ (in fact it has codimension $3$, but we don't need this). But the Jacobian
$$
J=\left(\begin{array}{ccc}z& -2y&x\\3x^2&-z&-y\\ -2xy&-x^2&2z\end{array}\right)
$$
has rank zero in $\mathbb{C}[x,y,z]/\mathfrak{m}_0$. Thus the origin is not a smooth point of $X$.
Comment: Thanks for the alternative explanation. I'll make sure to read into this a bit more.


Dial number with Name from iOS app

Question: I have found the answer on how to dial a number programmatically from an app.
<code>@IBOutlet weak var phoneNumberTextField: UITextField!
</code>
...
<code>@IBAction func phoneDialButton(sender: UIButton) {

    let phoneNumberToCall = phoneNumberTextField.text

    let url: NSURL = NSURL(string: "tel://\(phoneNumberToCall)")!
    UIApplication.sharedApplication().openURL(url)

}
</code>
What I am curious about is if I introduce a new field
<code>@IBOutlet weak var phoneNameTextField: UITextField!
</code>
How would I go about putting that string as the name you are dialing when you make the call? Is it even possible?
Comment: What does it mean to dial a "name"?
Comment: for example if i called 555 555 5555 and the name was john it would say John up top then and the number underneath
Answer: What you're asking for is not possible.  The name that comes up when you dial a number is either the contact name associated with that number, or a suggested contact from your email.  You would have to create a contact programmatically and associated the desired name with the number you want to dial, or update an existing contact if one for that phone number already exists.
Comment: Thank you for the answer

Dial number with Name from iOS app


Why do the chords of one song work with the melody of the other perfectly

Question: Specifically, these 2 songs:
Redbone:

 (Chords are B, C#, D#m in original key)
Snooze:

 (Chords are G#m7, A#m7, Bmaj7 transposed + 6 from original key to match)
What relation do these chords have and why do either chords fit both song so well?
I don't know much theory so please let me know if I haven't provided essential info.
Comment: Likely written in the same key or a key, not the only reason, the chord progression as mentioned below would also need to be similar but being in the same key is the starting point in my opinion.
Comment: There are many songs with simillar chord progressions. I used to play in a church choir and we had some songs with almost the same chords. I had fun playing the other songs as counter melodies when the choir did one song.
Answer: The first video is not available, but the two sets of chords are very similar: each chord of the first set is contained in the corresponding chord of the second set. So a melody that fits one set will also fit the other one.
Song1     B-D#-F#      C#-E#-G#     D#-F#-A#
Song2  G#-B-D#-F#   A#-C#-E#-G#   B-D#-F#-A#
Answer: Nice connection!
The simple answer is that chords come from scales, and after transposing, all these chords are in the same scale.  The last chord of song 2 is the same as the first chord of song 1.
In the first song B-C#-D#m are the IV-V-vi of the F# Major key (scale).
The second song's chords are Dm-Em-F, which would be ii-iii-IV of C major, (or transposing, G#m-A#m-B in the key of F#.)
If you put them in the same key it would be G#m-A#m-B-C#-D#m.  I think you'll hear the connection if you play them together in that sequence.  This is the idea of "diatonic chords".
Also, the chords of G#m and B share two notes (G#-B-D# & B-D#-F#), as do each of the other chords when paired (A#m and C#, B and D#m), because chords are built in thirds.  (This is what PiedPiper was pointing out in their diagram.)
The terms "relative minor" and "relative major" are helpful.
G#m is the relative minor of B Maj.
The melody is also coming from the same key (same 7 notes in the scale) and is usually going to match one of the chord tones.  So it's going to work with either G#m or B because the chords share two notes.
Finally, this song should put all the ideas together for you:  My Favorite Things.  (check out the original version from Sound of Music)
The first part of the melody repeats itself over two different chords related in the same way as in your example.  First over D#m then over B.  Then it even substitutes D#min with D#Major and the other minor chords with their relative Major chords appropriately.  Listen to how that song's harmony shifts underneath the repeated melody and how that gives it a different flavor each time.  Enjoy!
Comment: The chords in the second example are explicitly seventh chords.