How to group sentences by groups of 500 characters without breaking a sentence with PHP?

Question: I have been scratching my head on this but cannot work out a solution.
Let's say you have a text of 5000 characters, I would like to split it into blocks of less than 500 characters, but, without breaking a single sentence. eg: if a paragraph is let's say 550 words and the last sentence stops at 550 characters but start at 450 characters, I would like to save this particular block to a maximum of 450 characters(this way no sentences are broken).
Any idea how to achieve this please?
My goal is to save each block into an array so I can work on them separately.
I was thinking about using preg_split, sum the outputs, and if the sum is above 500 characters, remove the last sum. But.....I find it difficult to separate the sentences without mistakes.
Any idea what preg_split rules I should use to make sure that every single sentences are well separated?
I tried to use this tool but cannot get it to give me the right output:
https://www.phpliveregex.com/#tab-preg-split
Thanks
Comment: Have you figured out how to split sentences in general? If so, please update that into your post. (There are quite a few edge cases with abbreviations etc. that will produce incorrect splits.)
Comment: Clearly, regex or a direct string approach are not the way to split a text into sentences: `intlBreakIterator` is the class you need.
Answer: First of all: Thank you for the nice question!
The solution is not really stable and you have to adjust in the future. But it will shows you the possible way to archive this.
Split your text into the individual sentences and save each sentence as an element in an array. This way you can determine the length of the sentences when iterating the array. As long as the sentence and the previous sentence are smaller than the maximum block length, put the string into a temporary variable. As soon as the length of the text of the temporary variable + the length of the current record are greater than the maximum block length, the record is stored in a new array as a block.
<?php
$txt = "111. 222 222. 333 333 333. 444 444 444 444. 555 555 555 555 555. 333 333 333. 222 222. 111.";

$length = 30;
$arr = explode(". ", $txt);
$b = [];
$tmp = '';

foreach($arr as $k => $s) {
    if (strlen($s) + strlen($tmp) <= ($length) ) {
        $tmp = $tmp . $s .'. ';
    } else {
        $b[] = $tmp;
        $tmp = '';
        $tmp = $s . '. ';
    }

    if((count($arr)-1) === $k) {
        $b[] = substr($tmp, 0, -2);
    }
}

print_r($arr);
print_r($b);

Output
// Sentence Array
Array
(
    [0] => 111
    [1] => 222 222
    [2] => 333 333 333
    [3] => 444 444 444 444
    [4] => 555 555 555 555 555
    [5] => 333 333 333
    [6] => 222 222
    [7] => 111.
)

// Your new Block Array
Array
(
    [0] => 111. 222 222. 333 333 333.
    [1] => 444 444 444 444.
    [2] => 555 555 555 555 555.
    [3] => 333 333 333. 222 222. 111.
)

Comment: Thank you so much for your effort, I will try your idea in the mid of the week(sick at the moment). But what I initially thought would be simple gave me some problems :-) I really did not think it would be so tricky!
Comment: @Benny Yes it is definitely not easy. The weak point will be to find an exact delimitation of the sentence. Here, a regex is definitely better than a simple explode. Because sentences can also end with `?`, `!` , `.` and `...`. That's why I noted in my answer that it doesn't run stably. Please keep me informed. I am also very interested :-) But first: Get well soon!
Answer: Seems easier to split by sentence, then you should be able to loop on it and concatenate if you are over your boundary
$data = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Id cursus metus aliquam eleifend mi in nulla posuere. Hac habitasse platea dictumst vestibulum rhoncus. Elementum facilisis leo vel fringilla est. Sem et tortor consequat id. Eleifend donec pretium vulputate sapien nec. Elit pellentesque habitant morbi tristique. Dictumst vestibulum rhoncus est pellentesque elit. Quis commodo odio aenean sed adipiscing. Id volutpat lacus laoreet non curabitur gravida arcu. Sit amet massa vitae tortor condimentum. Morbi blandit cursus risus at ultrices mi tempus.

Tortor consequat id porta nibh venenatis cras sed. Urna et pharetra pharetra massa massa. Ut consequat semper viverra nam. Hac habitasse platea dictumst quisque sagittis. Commodo odio aenean sed adipiscing diam donec. Imperdiet proin fermentum leo vel orci porta. Quisque non tellus orci ac auctor augue. In cursus turpis massa tincidunt dui. Purus faucibus ornare suspendisse sed. Tristique senectus et netus et malesuada fames ac turpis.';

$splited = preg_split('/([^.]+\.)/mU', $data, -1, PREG_SPLIT_DELIM_CAPTURE);
// Basically here, I try to find everything before a `.`

$cleaned = array_filter(array_map('trim', $splited));

var_dump($cleaned);

I have that
array(22) {
  [1]=>
  string(123) "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
  [3]=>
  string(53) "Id cursus metus aliquam eleifend mi in nulla posuere."
  [5]=>
  string(49) "Hac habitasse platea dictumst vestibulum rhoncus."
  [7]=>
  string(42) "Elementum facilisis leo vel fringilla est."
  [9]=>
  string(27) "Sem et tortor consequat id."
  [11]=>
  string(44) "Eleifend donec pretium vulputate sapien nec."
  [13]=>
  string(43) "Elit pellentesque habitant morbi tristique."
  [15]=>
  string(50) "Dictumst vestibulum rhoncus est pellentesque elit."
  [17]=>
  string(40) "Quis commodo odio aenean sed adipiscing."
  [19]=>
  string(53) "Id volutpat lacus laoreet non curabitur gravida arcu."
  [21]=>
  string(40) "Sit amet massa vitae tortor condimentum."
  [23]=>
  string(49) "Morbi blandit cursus risus at ultrices mi tempus."
  [25]=>
  string(50) "Tortor consequat id porta nibh venenatis cras sed."
  [27]=>
  string(38) "Urna et pharetra pharetra massa massa."
  [29]=>
  string(32) "Ut consequat semper viverra nam."
  [31]=>
  string(47) "Hac habitasse platea dictumst quisque sagittis."
  [33]=>
  string(46) "Commodo odio aenean sed adipiscing diam donec."
  [35]=>
  string(45) "Imperdiet proin fermentum leo vel orci porta."
  [37]=>
  string(40) "Quisque non tellus orci ac auctor augue."
  [39]=>
  string(37) "In cursus turpis massa tincidunt dui."
  [41]=>
  string(38) "Purus faucibus ornare suspendisse sed."
  [43]=>
  string(57) "Tristique senectus et netus et malesuada fames ac turpis."
}

Quick update for Maik ;)
$data = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Id cursus metus aliquam eleifend mi in nulla posuere. Hac habitasse platea dictumst vestibulum rhoncus. Elementum facilisis leo vel fringilla est. Sem et tortor consequat id. Eleifend donec pretium vulputate sapien nec. Elit pellentesque habitant morbi tristique. Dictumst vestibulum rhoncus est pellentesque elit. Quis commodo odio aenean sed adipiscing. Id volutpat lacus laoreet non curabitur gravida arcu. Sit amet massa vitae tortor condimentum. Morbi blandit cursus risus at ultrices mi tempus.

Tortor consequat id porta nibh venenatis cras sed. Urna et pharetra pharetra massa massa. Ut consequat semper viverra nam. Hac habitasse platea dictumst quisque sagittis. Commodo odio aenean sed adipiscing diam donec. Imperdiet proin fermentum leo vel orci porta. Quisque non tellus orci ac auctor augue. In cursus turpis massa tincidunt dui. Purus faucibus ornare suspendisse sed. Tristique senectus et netus et malesuada fames ac turpis.';

$splited = preg_split('/([^.]+\.)/mU', $data, -1, PREG_SPLIT_DELIM_CAPTURE);
// Basically here, I try to find everything before a `.`

$cleaned = array_filter(array_map('trim', $splited));

$lines = [];
$current = '';
$min = 50;

foreach ($cleaned as $sentence) {
  $current .= $sentence . ' '; // Mandatory to allow to add an other sentence
  $len_current = strlen($current);

  if ($len_current >= $min) {
    array_push($lines, trim($current)); // As we add an extra space, we remove it when adding to the lines

    $current = '';
  }
}

Looks like this
array(14) {
  [0]=>
  string(123) "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
  [1]=>
  string(53) "Id cursus metus aliquam eleifend mi in nulla posuere."
  [2]=>
  string(49) "Hac habitasse platea dictumst vestibulum rhoncus."
  [3]=>
  string(70) "Elementum facilisis leo vel fringilla est. Sem et tortor consequat id."
  [4]=>
  string(88) "Eleifend donec pretium vulputate sapien nec. Elit pellentesque habitant morbi tristique."
  [5]=>
  string(50) "Dictumst vestibulum rhoncus est pellentesque elit."
  [6]=>
  string(94) "Quis commodo odio aenean sed adipiscing. Id volutpat lacus laoreet non curabitur gravida arcu."
  [7]=>
  string(90) "Sit amet massa vitae tortor condimentum. Morbi blandit cursus risus at ultrices mi tempus."
  [8]=>
  string(50) "Tortor consequat id porta nibh venenatis cras sed."
  [9]=>
  string(71) "Urna et pharetra pharetra massa massa. Ut consequat semper viverra nam."
  [10]=>
  string(94) "Hac habitasse platea dictumst quisque sagittis. Commodo odio aenean sed adipiscing diam donec."
  [11]=>
  string(86) "Imperdiet proin fermentum leo vel orci porta. Quisque non tellus orci ac auctor augue."
  [12]=>
  string(76) "In cursus turpis massa tincidunt dui. Purus faucibus ornare suspendisse sed."
  [13]=>
  string(57) "Tristique senectus et netus et malesuada fames ac turpis."
}

Comment:  I was too lazy to go further
Comment: In my opinion, the challenge starts exactly where you left off.
Comment: Updated ;) (quick and dirty but works)
Comment: If the SO wants a minimum of characters per block, I would agree with : "It works"  But he wants it the other way round.
Comment: Sorry for not replying earlier, sick at the moment, I will try your solution in the mid of he week, than you so much for your effort :-)
Answer: I Think you need this
$string = "Hello world php is fun";
$array = explode(" ", $string);

OutPut is
Array ( [0] => Hello [1] => world [2] => php [3] => is [4] => fun )

Comment: Can you explain how this answers the OP's question?
Comment: Now that is a good question, and that should be added in the comment section under the question. There you might also ask other questions like for example updating the question with some code that the OP tried to improve the quality of the question.
Comment: What is OP'S I don't Understand you?
Comment: OP is the Original Poster. The question is about splitting text into blocks of less than 500 characters with unbroken sentences. Your code splits on a space, which does not answer the question right?
Comment: ok got it. Can OP's provide an example, please?


C++ static variable and function errors

Question:
Possible Duplicate:
What does it mean to have an undefined reference to a static member?

I have a static class as follows:
.h file
class c1 {
    public:
    static int disconnect();
    private:
    static bool isConnected;
    };

.cpp file
#include c1.h

int c1::disconnect()
{
    c1::isConnected = false;
    return 0;
}

However when I compile, there is an error
undefined reference to `c1::m_isConnected'

Please help!
Comment: So is it c1::m_isConnected or c1::isConnected ?
Comment: @c-smile that is probably caused by name mangling if this is an linker error.
Answer: You have to provide an actual object instance for the static class members. Add the following to your .cpp file:
 bool c1::isConnected;

To initialize it to a specific value, add an initializer:
 bool c1::isConnected = false;

(By the way, classes in C++ cannot be static. Classes are just types. Only class members can be static.)
Comment: Isn't the "m_" caused by name mangling?
Comment: sweet thx...im coming form C#/C so yeah..
Comment: Not sure about C#, but Java has static classes... in C++, any class that's defined inside another class is called a "nested class". But there's no analogue of a "static (nesterd) class" in C++, i.e. a class that only static member functions can use -- the concept doesn't make sense in C++, where classes are just types.
Answer: isConnected is a (non-static) member variable and you can't use it without an instance that it's a part of. While static variables exist independently of any object, non-static member variables only exist as part of an instance of that class.
You need to either make isConnected static or accept an instance of c1 on which to set isConnected to false. You probably want the former.
Answer: What you have in header file is declaration. However, you also need a definition of the variable. The correct code will look like this:
class c1 {
public:
    static int disconnect();
private:
    static bool isConnected;
};

bool c1::isConnected = false;

int c1::disconnect()
{
    isConnected = false;
    return 0;
}

Comment: It's important to get the separation of header file and source file right, though, otherwise you might end up with multiple definitions.

C++ static variable and function errors


Is it possible for a distribution to have infinite variance but finite covariance or vice versa?

Question: Is it possible to have distributions s.t. one/both have infinite variance, but finite covariance? What about finite variance but infinite covariance?
If so, what are example distributions/what is the constraint on the pdf that makes this true?
Comment: Closely related, but not a duplicate: https://stats.stackexchange.com/questions/91512/how-can-a-distribution-have-infinite-mean-and-variance/91515#91515
Answer: The $t_2$-distribution has infinite variance but finite first moment. If you use a constant (which technically is a one-point distribution) as second distribution/random variable, the covariance will be zero, so finite. In general, if one variance is finite and the other one infinite, both finite and infinite covariances can happen.
For two independent $t_2$-distributions, both obviously with infinite variance,
$$
Cov(X,Y)=E(X-EX)(Y-EY)=E(X-EX)E(Y-EY)=0,
$$
not involving any degenerate integrals.
Finite variances and infinite covariance is impossible due to the Cauchy-Schwarz inequality,
$$
Var(X)Var(Y)\ge Cov(X,Y)^2.
$$
Comment: (+1) Your first example relies on overlooking that the covariance is the full matrix of central second moments in a multivariate distribution. It is not finite in your example: it has $+\infty$ and $0$ on the diagonal even though it has finite off-diagonal entries. Ordinarily we are unconcerned about the technical distinction between the matrix and its off-diagonal entries in the bivariate case, where it is implicitly assumed that the diagonal entries are finite. It might be better to say that a conventional *formula* for a "covariance" gives a finite value--but its interpretation is doubtful.
Comment: @DilipSarwate You're right, I didn't mean to put the "multiply" there, I meant to "correlate" it wirh a constant. Corrected it.
Comment: Yeah, I had the correct example in mind when writing it down in the beginning but confused myself when at the same time thinking about the next case, so messed things up when writing. Corrected now. @Hasse1987 (Amazingly the mess was still picking up votes.)
Comment: @whuber That's a fair enough comment. I was interpreting the question as asking explicitly for the off-diagonal entry, because it's clear that if a variance is infinity, one diagonal entry has to be infinity as well; the question wouldn't make much sense if that would count as "not finite".
Comment: @Dilip re "is infinite:" there is one exception that is crucial for the argument.  When $a=0,$ $\operatorname{Cov}(aX,X)=\operatorname{Cov}(0,X)=E[0X]-E[0]E[X]=0$ is not infinite.  Christian: please note that $\operatorname{Cov}(a,X)=E[aX]-E[a]E[X]=0$ is not necessarily equal to $E[X]$ as you currently claim.  But it is indeed finite!


python - iterate list of column names and access to column

Question: I have a DataFrame called df want to iterate the columns_to_encode list and get the value of df.column but I'm getting the following error (as expected). Any idea about how cancould I do it?
columns_to_encode = ['column1','column2','column3']

for column in columns_to_encode:
    df.column

AttributeError: 'DataFrame' object has no attribute 'column'

Comment: slight chagne to your code - do `df[column]` `.dot` notation is discouraged for selecting columns
Comment: ohh true!! How can I miss that! thanks! @Umar.H
Answer: Try this code, this will solve your issue:
columns_to_encode = ['column1','column2','column3']

for column in columns_to_encode:
    df[column]


Will the club finishing 4th in the EPL go to any European competition if clubs from 5 to 8 win corresponding titles granting European qualification?

Question: Starting the 2018/19 season there will be a new distribution rules in the Champions League (CL) and Europa League (EL). CL and EL winners will get automatic spot in group stages.
The new rule states that no country can have more than 5 teams in CL. I am wondering what will be the outcome for the following case in England:
1) CL and EL winners are both from England and finish 5th and 6th in EPL.
2) FA Cup and League Cup winners finish, let's say 7th and 8th in the EPL.
In that case, will the club finishing 4th in the EPL go to any European competition?
Comment: The title holders go first, so the club ranked 4th would drop out of the CL and play EL instead.. When I find a credible source I'll turn this into an answer.
Answer: Regulations of the UEFA Champions League 2018-21 Cycle:

https://www.uefa.com/MultimediaFiles/Download/Regulations/uefaorg/Regulations/02/55/82/79/2558279_DOWNLOAD.pdf

1) If UEFA Champions League and UEFA Europa League title holders are both from England and they both finish outside of the top four in Premier League, then the 4th placed Premier League team will not qualify for a place in the UEFA Champions League, but instead qualify for a place in the UEFA Europa League.

Ref to 3.07 a.

2) The 4th placed Premier League team is always guaranteed a place in either the UEFA Champions League or the UEFA Europa League.

Ref to 3.07 a, b, c.

Other sources:

https://www.thesun.co.uk/sport/football/3097329/champions-league-english-teams-fourth-place-premier-league/)


JS Event delegation with the same function reference

Question: I'm learning about event delegation, and I understand that if I am creating something like the following, it could be expensive for memory.
bigElementsArray.addEventListener("click", e => {

});

But, what if I am pointing to the same function in memory, this will create only one handler.
const sameFunctionRef = e => {};
bigElementsArray.addEventListener("click", sameFunctionRef);

So, why this is a problem, too?
Answer: Aside: In your first code snippet I assume you're iterating over an array and adding event listeners (I'm happy to be corrected, but I'm not aware of a way without some JS trickery of adding event listeners to an array of elements).
The issue here isn't creating a bunch of new functions (that is an issue), but creating a bunch of event listeners. Having a bunch of event listeners is expensive because as the browser needs to maintain them all and you need to be sure to remove the event listeners if elements get deleted to avoid memory leaks.
A better approach is to use event delegation. The basic idea is take advantage of event bubbling and have a single event handler on a parent element which then takes action depending on the event target.
Related is this answer which demonstrates the performance tradeoffs well: Does adding too many event listeners affect performance?


Spring Boot -> Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; For input string: "create"

Question: Estou fazendo uma aplicação em Spring Boot para gerenciamento de biblioteca.
E no momento que eu tento fazer uma nova criação de usuário usando a anotação @PostMapping, está me retornando o seguinte erro:
2023-03-09T16:24:18.454-03:00  WARN 11844 --- [nio-8080-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; For input string: "create"]

Abaixo está as classes de User e UserController:
User.class
package com.github.nibiroo.library_management.entity;

import jakarta.persistence.*;

@Entity
@Table(name = "tb_user")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@Column(name = "name")
private String name;

@Column(name = "email")
private String email;

@Column(name = "phone_number")
private String phoneNumber;

@Column(name = "CPF")
private String CPF;

public User() {
}
public User(String name, String email, String phoneNumber, String CPF) {
    this.name = name;
    this.email = email;
    this.phoneNumber = phoneNumber;
    this.CPF = CPF;
}

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getEmail() {
    return email;
}
public void setEmail(String email) {
    this.email = email;
}
public String getPhoneNumber() {
    return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
}
public String getCPF() {
    return CPF;
}
public void setCPF(String CPF) {
    this.CPF = CPF;
}
}

UserControler.class
package com.github.nibiroo.library_management.controller;

import com.github.nibiroo.library_management.entity.User;
import com.github.nibiroo.library_management.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping(value = "/users")
public class UserController {

@Autowired
private UserRepository userRepository;

@GetMapping
public ResponseEntity<List<User>> findAllUsers() {
    return ResponseEntity.ok(userRepository.findAll());
}

@GetMapping(value = "/{id}")
public ResponseEntity<User> findUserById(@PathVariable Long id) {

    Optional<User> optionalUser = userRepository.findById(id);

    return optionalUser.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
}

@PutMapping(value = "/edit/{id}",  consumes = {"application/json"})
public ResponseEntity<User> updateUserById(@PathVariable(value = "id") Long idParam, @RequestBody User userRequestBody) {

    Optional<User> optionalUser = userRepository.findById(idParam);

    if (optionalUser.isEmpty()){
        return ResponseEntity.notFound().build();
    }

    User existingUser = optionalUser.get();
    existingUser.setName(userRequestBody.getName());
    existingUser.setEmail(userRequestBody.getEmail());
    existingUser.setPhoneNumber(userRequestBody.getPhoneNumber());

    userRepository.save(existingUser);

    return ResponseEntity.ok(existingUser);
}

@PostMapping("/create")
public User postUser(@RequestBody User userRequestBody){
    return userRepository.save(userRequestBody);
}
}

Não consigo entender o que ele está tentando converter de String para Long, sendo que até olhando os mappings anteriores, o Long é um parâmetro que faz referência ao id, porém, no insert o banco irá fazer este auto_increment. Podem me ajudar, por gentileza?
Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Comment: **RESOLVIDO**

Ao fazer a requisição da API via Postman, por padrão o Content-Type: text/plain, e por isso ele reclama sobre a conversão!

Para sua devida correção, foi necessário forçar que o Content-Type: application/json
Answer: RESOLVIDO
Ao fazer a requisição da API via Postman, por padrão o Content-Type: text/plain, e por isso ele reclama sobre a conversão!
Content-Type: text/plain
Para sua devida correção, foi necessário forçar que o Content-Type: application/json
Content-Type: application/json


O que é Prisma?

Question: Que raio de Prisma é essa? É de comer? Ou de programar? Nunca ouvi falar. Tag: prisma
Não quero saber tudo, mas uma informação básica sobre o que é isso.
Comment: Acho que é isso: http://linguagemprisma.br4.biz/
Comment: Link interessante: https://linguagemprismablog.wordpress.com/
Comment: Com certeza não é algo popular ou deve ter algum erro nessa tag, pois não encontrei no SOen: https://stackoverflow.com/questions/tagged/prisma
Comment: Prisma: Seu Primeiro Grande Carro!
Answer: Prisma é uma linguagem de programação baseada em Lua e também um interpretador para esta linguagem. É bom salientar que a linguagem está em fase inicial e não encontrei informações relevantes sobre a quantas anda o desenvolvimento atualmente.
A linguagem conta com uma biblioteca gráfica nativa (chamada IG) com versões para Windows e Linux. Esta biblioteca gráfica tem a mesma licença de uso da GTK. A licença de uso do interpretador é a mesma licença de uso de Lua.
Segundo o site oficial a linguagem possui uma versão com statements em português e outra em inglês.
Ainda com base no site oficial, algumas características da linguagem são (destaque e itálico por mim):

Interpretada em bytecodes;
Tipagem dinâmica;
Simplicidade de tipos;
Portabilidade. O programa feito em Prisma não terá dificuldades em rodar nos mais populares sistemas operacionais;
Própria para script (se preferir) ou usando o prisma compiler para "esconder o código";
Muito rápida;
Muito leve, não consome muitos recursos da máquina;
Possui poderosos recursos para manipulação de dados: as tabelas;
Recursos indiretos para aplicar a orientação a objetos: classes;
Fácil de ser aprendida.
Comment: E para quem não sabe o que é Bytecode, recomendo que dê uma lida na Wiki da tag: https://pt.stackoverflow.com/tags/bytecode/info (é um começo apenas).
Comment: A alfinetada que eu vou dar aqui é pro autor da linguagem, não para o da resposta, ok? (btw +1). O que torna um programa rápido e leve ou não é uma combinação do que ele tem que fazer, o ambiente em que roda e principalmente a habilidade do programador.
Answer: O que é Prisma?  https://linguagemprismablog.wordpress.com/about/
Prisma é um interpretador para a linguagem de programação que leva o mesmo nome.
Ela possui diversas características, tais como:

interpretada em byte codes;
tipagem dinâmica;
simplicidade de tipos;
portabilidade, o programa feito em Prisma não terá dificuldades em rodar nos mais populares sistemas operacionais;
própria para script (se preferir) ou usando o prisma compiler para esconder o código;
muito rápida;
muito leve, não consome muitos recursos da máquina;
possui poderosos recursos para manipulação de dados: as Tabelas;
recursos indiretos para aplicar a orientação a objetos: classes;
fácil de ser aprendida;
Comment: Essas características são verdades, ou é meramente opinião do autor da linguagem? Creio que coisas como "muito rápida" e "muito leve" deva ser algo bem relativo, não? Acho que sua resposta ainda pode ser aprimorada ;)
Comment: Eu só disse que a resposta pode ser aprimorada, deixando claro que essas características são opiniões do autor da linguagem ;) ... De resto a resposta esta boa
Comment: Eu copiei a informação dada pelo autor mas já faço uso em ambiente de produção há pelo menos um ano e posso afirmar com certeza que é bem leve, realmente consome poucos recursos comparada a um java da vida!

O que é Prisma?


Number of days it took to climb the mountain (BdMO 2012 National Primary/Junior question)

Question: From the Bangladesh Mathematical Olympiad 2012 National Secondary (Question 7, or ৭).

When Tanvir climbed the Tajingdong mountain, on his way to the top he saw it was raining $11$ times. At Tajindong, on a rainy day, it rains either in the morning or in the afternoon; but it never rains twice in the
  same day. On his way, Tanvir spent $16$ mornings and $13$ afternoons without rain. How many days did it
  take for Tanvir to climb the Tajindong mountain in total?

I tried to solve it using sets but it has not worked out too well. I asked people who did it but most of them gave different answers ,often having a difference of $1$ or $2$. Any help will be appreciated.
Comment: Contradictory tags?
Comment: @Jp McCarthy,I was not exactly sure what to tag it with.
Comment: @JpMcCarthy: I find elementary set theory quite recreational. ;-)  (Oh, you meant...)
Comment: Well, wouldn't it be 3x it rained in the afternoon, leaving 8 rainy days, for each you see a morning or an afternoon, so its 9 sunshine days. 9 afternoons, 9 mornings, 4 rainy afternoons, 4 shiny mornings, 4 rainy mornings, 4 shiny afternoons, 3 rainy afternoons, 3 shiny afternoons. Thats 11 rainy days, and 9 sunshine days, resulting in a 20 day journey.
Comment: @Arthur Fischer,I got it from the junior section of the nationals.Did not know it came in the primary section as well.
Comment: I've formatted your question, as well as provided what I am almost certain is the original source.
Comment: Honestly, I just Googled "When Tanvir climbed the Tajingdong" and this was the first thing that popped up.  Feel free to give a different source.
Comment: @Arthur Fischer,I am not saying this came from a different source.I am just saying I got it from the Junior section,not the primary one.
Answer: I'll approach it up front:
Every day is divided in 2 sections:

morning or rain
afternoon or rain

Since it says that it can only rain once in a day, it doesn't even need to be accounted for a full day rain, so the number of days is
mornings$ +$ afternoons $+$ rainy times  $ = $ 2 $\times$ amount of days
Thus $16 + 13 + 11 = 2$ $\times$  days -> days = 20
And it fits: 9 sunshine days, 7 morning sunshine, 4 afternoon sunshines.
Comment: Thanks for the answer.I was getting answers like 23,24 from others .


New Jackson Rhoads RRXMG control knob confusion

Question: I just bought a New Jackson Rhoads RRXMG with EMG 85 Neck and EMG 81 Bridge pickups. I am having trouble with the control knobs. In theory I should have one master volume, one neck p/u tone and one bridge p/u tone control. There is no markings indicating what each one controls unlike my fender.
The problem is when I switch to the neck p/u, the knob nearest the neck seems to be the volume, middle nob does nothing and the "tail" knob Slightly tweaks the sound.
When I switch to the bridge p/u, the knob near neck does nothing. The middle knob seems to become the volume,and the tail knob again seems to change tone a little. I would think a master volume knob wouldn't change! The only one that stays the same is the tail knob that only slightly changes sound. How can I figure this thing out?
Bonus question, if I have the switch to Neck pickup, when I turn the knob nearest the neck pickup to adjust "Volume". I have a highly irritating "scrubbing/grinding" sound from the amp. Same when I switch to Bridge P/U. Is that just my setup or something to learn to deal with?
Comment: Do any of the knobs have a centre indent (you can feel a slight click when it's exactly central)?
Answer: It's not unheard of to have NO master volume, and instead to have separate volume knobs for each pickup. When your P/U selector is in the middle position, this then allows you to dial in the exact mix that you want.
The third knob, then, sounds like it's a master tone for both pickups.
The grinding sound when you turn one of the knobs could just be a low-quality or dirty potentiometer (the part inside the knob that scrubs a wiper across a resistor). If you purchased the guitar at a local shop, this would be a good reason to bring it back to them--they may replace the pot for you.
Comment: After looking at some of the online resources, it really seems like the consistency isn't very high with this model -- Jackson's own website shows a picture with three knobs, but only claims to have a master tone and master volume. Another site claims one master volume and two tone knobs. If you do bring the guitar to a shop, they should be able to rewire it to your preferences.
Answer: From the direct neck to bridge the default for the 3 RR model knobs is:

Neck PU Volume
Bridge PU Volume
Master Tone

For your bonus question:

I have a highly irritating "scrubbing/grinding" sound from the amp

Just cheap electronics.  The Jackson X series are made in indonesia and they are trying to keep the cost low, so they skimp where they can to achieve that goal.  You can try cleaning the pots, maybe just dust/debris is causing the issue, or replace them with higher quality controls.
Some history I'm aware of still doesn't explain why the layout is like this for this model. From what I've read:

Randy's original Jackson prototype was the "Concorde" nicknamed model (the white and gold pinstripe), which had the same 2 volume/2 tone control layout of Randy's earlier guitars (gibson les paul and his polka dot V)
The second prototype (black and gold one) lost one of the control knobs, my understanding it was a 3 control: Master volume and 2 tone controls setup
There were 2 other prototypes, but don't know more about them as he died before they came out--that's why the first 2 are the ones you always see Randy with in picture and generally only playing the white one.
The future RR models that came out after his death based on the 2nd black protoype.

There are so many variants and models, but generally

RR1 has Master/Tone/Tone
Brief RR2 had single  master volume, no tone
The RRX24 end up with Volume/Volume/Tone
RR3 had a bunch:

1996-1997:1 Volume, 3-Way Toggle Switch
1998-2011: 2 Volume + 1 Tone, 3-Way Toggle Switch
2016-2017: 1 Volume + 1 Tone, 3-Way Toggle Switch

and on and on...


Show that $G/H\cong S_3$

Question:
If $G:=S_4$ and $H:=\{id,(12)(34),(13)(24),(14)(23)\}$ Show that $G/H$ has order $6$ and all of its elements have order less than or equal to $3$ (so by the classification of the groups of order 6 up to isomorphism, $G/H\cong S_3$)

$H$ is normal, since left- and right cosets are equal, There are $6$ cosets:
$\{id,(12)(34),(13)(24),(14)(23)\},\ \{(12),(34),(1423),(1324)\},\ \{(13),(24),(1234),(1423)\}$
$\{(123),(134),(243),(142)\},\ \{(14),(23),(1243),(1342)\},\ \{(132),(143),(234),(124)\}$
What does it mean: All elements of $G/H$ have order less than or equal to $3$?  Each element is a set of 4 permutations, what is the order here ?
$G/H\cong S_3$: How can I construct an isomorphism, since the cosets are disjoint, can I just pick an element from each group and compare them with $S_3$ ?
Thanks in advance.
Comment: Since $H$ is normal, $G/H$ is a group, and for each $\sigma\in S_4$, $\sigma H$ is an element of $G/H$. The order of $\sigmaH$ is the least $k$ for which $\sigma^k\in H$.
Comment: It's possible to construct a specific isomorphism, but it would not be easy. They want you to show that it's isomorphic to $S_3$ in an easier way. If the group had an element of order greater than $3$, then the group would be $\mathbb{Z}/6\mathbb{Z}$, but if the order of every element is $\leq 3$ then it must be $S_3$.
Comment: A representative may have order six in $G$, but the order of its coset could still be less in $G/H$, if a lower power would belong to the subgroup $H$. When we pass to the quotient group $G/H$ the elements of $G$ lose their identity to the extent that any two belonging to the same coset of $H$ become equal.
Comment: @Pedro Tamaroff Thanks but there are $24$ $\sigma$'s, so it is possible that $\sigma H=\sigma' H$ for $\sigma\neq\sigma'$ but must they have the same exponent to belong to $H$ ?
Comment: @Matt S Why it cannot be $\mathbb Z/6\mathbb Z$ ? I mean how can I show that no element has order $6$ ? Since $G/H$ has order $6$, any element, say $\sigma_1$ of a coset exponented with $6$ gives identity, but $id=((12)(34))^2$ for example and hence $\sigma_1^3=(12)(34)$ etc. Am I on the right track ?
Comment: @Pedro's explanation is what you apparently looking for. Take your second coset for example. No matter which element from it you select, its square will be in $H$. Therefore that coset is an element of order two in the quotient group. The same thing happens with others. BUT! The fact that we have a well-defined operation in the quotient group means that we only need to check this for one representative from each coset.
Comment: This is somewhat close to being a duplicate of either [this](http://math.stackexchange.com/q/106777/11619) or [this](http://math.stackexchange.com/q/302654/11619). But it seems to me that the question here is more about understanding the quotient group, so marking this a dup of either doesn't feel right.
Comment: @Jyrki Lahtonen, yes I think this is due to the fact that $H$ is normal; $\sigma_1 H=\sigma_2 H$ and $\sigma_1^k\in H$ implies $H=\sigma_1^k H=(\sigma_1 H)^k=(\sigma_2 H)^k=\sigma_2^k H$ Hence $\sigma_2^k\in H$, so I can check it for 6 elements, but I mean, for general case, what would happen if any representative had order $6$ ?
Answer: Here is a way to construct an homomorphism from $S_4$ to $S_3$, which has kernel $H$. Consider the three possible partitions of the set $\{1,2,3,4\}$ into two sets:
$$A=\{1,2\}\cup\{3,4\}; \quad B=\{1,3\}\cup \{2,4\}; \quad C=\{1,4\} \cup \{2,3\}.$$
Now you can see what does an element $p\in S_4$ to those partitions. For instance the element $p := (1234)$ does the following:
\begin{align*}
\{1,2\} &\overset{p}{\leadsto} \{2,3\}; &\{1,3\}\overset{p}{\leadsto}\{2,4\};\\\{1,4\}&\overset{p}{\leadsto} \{2,1\}; &\{2,3\}\overset{p}{\leadsto}\{3,4\}; \\
\{2,4\} &\overset{p}{\leadsto}\{3,1\}; &\{3,4\}\overset{p}{\leadsto}\{4,1\},
\end{align*}
so $$A \overset{p}{\leadsto}\{2,3\}\cup \{4,1\}; \quad B \overset{p}{\leadsto} \{2,4\}\cup \{1,3\}; \quad C \overset{p}{\leadsto} \{2,1\}\cup \{3,4\}.$$
This corresponds to the transposition $[ABC]\overset{p}{\leadsto}[CBA]$. Which is like the transposition $(13)$ in $S_3$. Now define the map $$\varphi:S_4\to S_3,$$
which sends an element of $S_4$ to the action on the partitions $A,B,C$. If $q,r \in S_4$ then the product $qr$ corresponds to the composition of the action of $q$ and of $r$, so the action of $qr$ is the result of the two actions, that is $\varphi(qr)=\varphi(q)\varphi(r)$ and so you have an homomorphism. Moreover you can see that the only elements which sends $[ABC]$ to $[ABC]$ (written in one line notation) are exactly the elements of $H$, so $H$ is the kernel of $\varphi$ and therefore $S_4/H\approx S_3$
Answer: $H$ is a conjugacy class. If a conjugacy class is a subgroup, then it is a normal subgroup. So, $H$ is normal in $S_4$.
There is no need to find an isomorphism. You can do it as follows which is easier.
$S_3 \cap H = \{ e \}$. Also, $|S_3H|=\frac{|H||S_3|}{|S_3 \cap H|}$. So $S_3H=G$.
According to the second isomorphism theorem:
$G/H \cong S_3H/H \cong S_3/ H\cap S_3 \cong S_3 $

Show that $G/H\cong S_3$


Add Gesture recognizer

Question: I have two viewController :  FirstViewController and SecondViewController
I make an animation that make a view come from right to left.
I want when a make a sweep to right the SecondViewController hide and show the FirstViewController
the animation work there is the code
<code>SecondViewController *secondViewController = [[SecondViewController alloc]      initWithNibName:@"PlayListController" bundle:nil];
// Set up view2
secondViewController.view.frame = self.view.frame;
secondViewController.view.center = CGPointMake(self.view.center.x +   CGRectGetWidth(self.view.frame), self.view.center.y);
[self.view.superview addSubview:secondViewController.view];
// Animate the push
[UIView beginAnimations: nil context: NULL];
[UIView setAnimationDelegate: self];
[UIView setAnimationDidStopSelector: @selector(pushAnimationDidStop:finished:context:)];
secondViewController.view.center = self.view.center;
self.view.center = CGPointMake(self.view.center.x - CGRectGetWidth(self.view.frame), self.view.center.y);
[UIView commitAnimations];
</code>
I added a buttons to hide the view with an animation but it doesn't work  ??
Comment: Why did you give us the code that works but not give us the code you are struggling with?
Comment: Your attempts to transition this way are problematic (view hierarchy is out of sync with controller hierarchy, you won't receive certain events, memory management issues, etc.). You should just use navigation controller, and if you don't want to see the nav bar, then [hide it](http://developer.apple.com/library/ios/documentation/uikit/reference/UINavigationController_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006934-CH3-SW9). You're doing a lot of work to replicate standard behavior that implemented much more robustly than your own attempt.
Answer:
Add a gesture recogniser to your view.
In the callback, pop the view controller.

Caveat: this is non standard UI. Better go with a standard navigation bar and a back button.

Add Gesture recognizer


Filter nodes by currently logged-in user

Question: I want a view which shows nodes authored by the currently logged-in user. I can't figure out how to do this in Drupal 7.
Answer: just add a view for all your nodes. Then add a "relationship" for "Content: Author".
Now add a "contextual filter" for the field "user: uid" with a default argument for "userid of logged in user" to filter the view.
Answer: Ok I finally figured it out. Had to add a contextual filter of "Content: User posted or commented" with the default value of "user ID from logged in user".
Comment: I know this is old but Google brought me here. Be carefull with this one, since adding an arbitrary user ID to the url allows you to load the list for another user. This should not be used for security reasons!
Take a look at this alternative solution: http://stackoverflow.com/questions/7420031/drupal-7-views-3-usercurrent-filter-is-missing
Answer: I believe it should be the same as in Drupal 6.  Add a filter of User: Current to the view
Answer: Adding the Content:Author relationship or contextual filter didn't work in for me because it joins the node's author field to the user table.  In my case I created a field called "active" and I only wanted to display it on a view if it was active or if the current user's role is admin or custom admin.
The Current user has roles filter provided by the Views Published or Roles module solved this issue for me.


Azure VM and Web App in VNET VPN, changing IP and automatic start of vpn

Question: To connect Web App to VM I created a Vnet (point 2 site). Web app can see VM now, but:

it can access it just through an IP and not the host name. To use host name, I found info that I have to setup my DNS server. There are two problems with that: 1) i don't want to setup and maintain DNS 2) i don't know how to setup a
DNS, so think that option is out then
IP which I get after VPN is established changes every time. How to specify static IP for Vnet VPN? I saw instructions how to setup static internal IP, but that's not an IP I get with VPN
I need to RDP into VM and start VPN manually. I don't want to do that. How to start VPN when OS boots? When VPN starts it shows some dialog waiting me to press "connect", can that be a problem in automatic vpn connection through some script?

Anyway, vnets are so far too difficult (at least for a developer like me), hope they will simplify it for commons scenarios. Please feel free to suggest some other approach for connecting PaaS (web apps) with IaaS (VM with background services, database, etc).
thanks all for answers in advance ...
Answer:
To access the server using a name instead of IP, you indeed need to
use DNS, don't worry though, it's not that hard, here's an exact
step-by-step article on how to do it:
http://blogs.msdn.com/b/mcsuksoldev/archive/2014/03/04/creating-a-dns-server-in-azure-iaas.aspx
The IP address the client gets after connecting to VPN changes every time and there is no way to set that to a static IP, however the IP address that the VM get inside the Vnet doesn't change unless the VM was turned off/on, you don't need to worry about the IP address the client is getting, worry about the IP address the VM is getting, set that to a static IP address and you'll be able to access the same VM with the same IP address all the time. here's how to set an IP for an existing VM: https://azure.microsoft.com/en-us/documentation/articles/virtual-networks-reserved-private-ip/
Microsoft have yet to add the ability to Auto-Dial for Point-To-Site VPN connections, the idea has been floating for a long time now, but it seems that the teach people of Microsoft are busy with Windows 10 :), there's a well known work around though, you may use that until Microsoft finally decides to address the problem, the work around though is a bit long, give it a try and hope it works: http://www.diaryofaninja.com/blog/2013/11/27/deconstructing-the-azure-point-to-site-vpn-for-command-line-usage
Comment: Thanks for detailed answer! About the second point; I can access VM from WebApp only through VPN IP, not the internal IP, so why setting internal IP as static then?
Third bullet; will try to follow this tutorial, but if VPN can't start automatically it makes VM totally unusable in scenario when WebApp needs to talk to VM. MS restarts my VM at least once per month, I need to prepare for this since I don't have internet access 24/7 to RDP in.
Comment: "I can access VM from WebApp only through VPN IP, not the internal IP" you lost me here my friend, when you create a Vnet, lets say with the subnet of 10.0.0.x. and you add a VM to that Vnet, lets say 10.0.0.10, and you then add Site-to-VPN gateway to the same Vnet, you will be able to connect to that Vnet using a VPN client, and communicate with the internal resources of that Vnet using the IPs assigned to them, so in this scenario, you connect using a VPN client and get a random IP address, but you would still be able to connect to the VM using the IP 10.0.0.10, which is the internal IP.


Multiple Image upload in drupal 7

Question: I want to upload mulitple image at a time , for more clarification i have mention below link
http://www.olx.com.pk/posting.php?categ_id=378
when you click on add photos , you can upload 20 picture at a time.
Comment: Drupal version 6 or 7?
Answer: This has been answered before, but I can't mark it as a duplicate or flag.
You can use the the Plupload module to allow multiple uploads and even set limits by going into the code.
Comment: I believe Plupload cannot work on its own. It's designed to work with other modules. If someone can please confirm this.
Answer: http://drupal.org/project/swfupload is a widely-used multiple image upload module. There are installation instructions here and if you run into issues be sure to read through the issue queue before posting a support ticket!
How to install SWFUpload for Drupal 7:

Download the FileField module.
Download the jQuery Plugin Handler (jQp) module. This module is required for
loading the SWFUpload javascript library.
Place both modules, as well as the SWFUpload module, in your module
directory.
 (sites/all/modules)
If you do not have created a 'libraries' directory yet, create one.
 (sites/all/libraries)
Create a new directory called 'swfupload' inside the 'libraries' folder.
 (sites/all/libraries)
Download the SWFUpload 184.108.40.206 release.
Copy the files 'swfupload.swf' and 'swfupload.js' to the swfupload folder
inside the libraries folder. The end result will read:
 sites/all/libraries/swfupload/swfupload.js and
 sites/all/libraries/swfupload/swfupload.swf
Enable this module by navigating to:
 admin/build/modules
Ensure the library is available by visiting:
 admin/build/jqp/swfupload/
Answer: You may also want to consider http://drupal.org/project/multiupload_filefield_widget.
Used with his little brother
http://drupal.org/project/multiupload_imagefield_widget, it should do the trick.
Really easy to install.
Comment: This should be the ideal choice for multiple image/file option. This module is as close to core as it gets, but lets you hold ctrl + select files to upload multiple.
Answer: go for module plupload
[relationship]
(http://drupal.org/project/plupload
kindly go through readme.txt for more information regarding module.

Multiple Image upload in drupal 7


Deletar arquivo no php com frequência determinada

Question: Estive tentando fazer uma função que pudesse excluir arquivos de dentro de um determinado diretório de acordo com uma data informada. Nesse exemplo abaixo ainda não criei a função porque ainda estou tentando entender como se faz.
echo "
";
$arquivo = 'documento.pdf';
if(date("November 05 2016 19:19:24.", fileatime($arquivo))){
    echo "Excluiu!";
    unlink($arquivo);
} else {
    echo "Não excluiu!";
}

Um exemplo bem básico do que estou tentando fazer, é excluir arquivos de uma pasta de que tenham mais de 3 meses na mesma. Não consigo entender como consigo passar esse tempo e o utilizá-lo como parâmetro numa função (porque posso mudar o tempo caso eu precise)
Comment: servidor Linux ou Windows?
Comment: Se na hora do upload você puder guarda a data de quando foi feito, é mais confiavel que `fileatime()`. Para rodar isso periodicamente pode usar o [cronjob](http://pt.stackoverflow.com/q/44313/91) ou agendador de tarefas do windows
Comment: 3 meses desde a criação?
Comment: Isso. Será feito um upload para uma determinada pasta. Esse script apenas verificaria a partir da data do upload daquele arquivo para a pasta. Se tivesse mais que 3 meses na pasta, ele excluiria o arquivo, caso contrário, não faria nada.
Comment: servidor Windows
Comment: Eu já ouvi falar no cronjob, mas nunca o usei ainda. Vou procurar aprender a usá-lo.
Answer: Você pode usar strtotime() para definir o tempo a partir de um período e comparar com o resultado de filectime(), que retorna a data de criação em servidores Windows (fonte).
No seu exemplo você utilizou fileatime(), que obtém a data do último acesso, mas pela descrição do problema o correto é utilizar filectime(), mas pode ser alterado de acordo com o comportamento desejado.
// a data de criação é anterior à 3 meses atrás
if (filectime($arquivo) < strtotime('-3 month')) {
  // apagar
}

Comment: Bom, no fim o AP vai ter que testar o que é melhor no caso dele, depende muito de como os arquivos são gerados. De qq forma, o caminho pra resolver vc já passou.
Comment: Sançao, até esqueci de colocar a seguinte observação na pegunta: Existe uma forma de isso ser feito automaticamente? Testei seu código aqui e deu certinho!!!
Comment: Bom galera, obrigado, já me ajudaram bastante!
Answer: complementando a resposta do Sanção, segue código PHP para listar todos arquivos do diretório:
//diretório que deseja listar os arquivos
$path = "arquivos/";

//le os arquivos do diretorio
$diretorio = dir($path);

//loop para listar os arquivos do diretório, guardando na variável $arquivo
while( $arquivo = $diretorio -> read() ){

  //gera um link para o arquivo
  echo "".$arquivo."
";
}
$diretorio -> close();


Can we prove $BA=E$ from $AB=E$?

Question: I was wondering if $AB=E$ ($E$ is identity) is enough to claim $A^{-1} = B$ or if we also need $BA=E$. All my textbooks define the inverse $B$ of $A$ such that $AB=BA=E$. But I can't see why $AB=E$ isn't enough. I can't come up with an example for which $AB = E$ holds but $BA\ne E$.
I tried some stuff but I can only proof that $BA = (BA)^2$.
Edit: For $A,B \in \mathbb{R}^{n \times n}$ and $n \in \mathbb{N}$.
Comment: Is the space finite-dimensional? If not, then it is not true in general.
Comment: Yes. I didn't try to come up with an counterexample of infinite-dimensional spaces since I can't even see why it's true for finite-dimensional spaces.
Comment: (I can't comment...so):
[Please look this question:][1]

  [1]: http://math.stackexchange.com/questions/3852/if-ab-i-then-ba-i
Comment: Ah thanks. I should have searched with $I$ instead of $E$.
Comment: This is even true if $A$ and $B$ are matrices over a commutative [semiring](https://en.wikipedia.org/wiki/Semiring), but it is more difficult to prove. See Reutenauer and Straubing, Inversion of matrices over a commutative semiring. *J. Algebra* **88** (1984), no. 2, 350--360.
Answer: If $AB = E$, then (the linear application associated to) $A$ has a right inverse, so it's surjective, and as the dimension is finite, surjectivity and injectivity are equivalent, so $A$ is bijective, and has an inverse. And the inverse is also a right inverse, so it's $B$
Answer: Are A,B both square matrices?  Then AB=E and the fact that the determinant is multiplicative (i.e., det(AB)=det(A)det(B)) tells you that both A,B must have nonzero determinant and hence both be invertible.  In that case, you can readily multiply on the left by A^{-1} and obtain B=A^{-1}.
If A is nxr and B is rxm, where n and m don't match, it is actually impossible to obtain AB=E, since E is square (i.e., n=m).
If n=m but n is not equal to r, then you can get AB=E (the nxn identity matrix), and BA will be defined as well, but it is possible that BA might not equal the rxr identity matrix.  Such A,B to illustrate this fact can easily be found.
Answer: Use Crammer's Rule any square matrix $A\in\mathbb{R}^{n\times n}$ with nonzero determinant has a right inverse $B$ ($AB=E$).
Since $AB=E$, $|A||B|=|AB|=|E|=1$. Hence $|B|\neq 0$ which implies that $B$ has a right inverse $C$ such that $BC=E$.
Now you just need to prove that $A=C$ which you should try yourself.

Can we prove $BA=E$ from $AB=E$?


Machine-translate a node by menu link

Question: I have an "About us" main-navigation menu link.
I want to create several other main-navigation menu links, in languages other than English, which will link to that very webpage, for example:

เกี่ยวกับเรา (about us in Thai)

If the user clicked that link, the destination would be the same "About us" webpage, but the content would be machine-translated to Thai.

The English content of "About us" is generally small (up to 1000 characters), well formatted, accessible and names and slang are avoided (unless some escaping is utilized).

I didn't find data about "machine" or "auto(matic)" in the Content Translation module documentation1,2 but it might be worth to still ask if there any way inside Drupal itself to achieve that?
Answer: Drupal core (a standard Drupal install) does not have support for machine translation out-of-the-box.
However, you can add it easily by installing a contributed module.
TMGMT is a reliable module that will enable you to do machine translation with the following services:

Google Translate
Microsoft Translator
Deepl

If you later decide to have professionals translate the site, TMGMT will support that too, which makes it better in my opinion than a module that only does machine translation.
Comment: It was written in the module's page `All Drupal text elements can be used as source for translation: Nodes Entities I18n Strings (Menu, Terms etc.)`, but does that includes translating by menu link?
Comment: @Alkalix Yes, the text you are quoting even says it supports menus ;)
Comment: yes, it just clear to me if that is the meaning in "supports menus" or something else (such as automatic translation of menu links under some browser state, instead of what I personally meant --- translating a node by menu link access).
Comment: it just wasn't*

Machine-translate a node by menu link


How do I center an error message inside an html table?

Question: I have html code that prints all of the posts inside an html table.
However, if there are no posts then I need to print an error No posts found.
Now focus on the error message
I am trying to print the error message in the center of the table.

POST ID	POST TITLE

No posts found

Here is an example: http://jsfiddle.net/9UhTd/
The error message is shown in the begin of the table, but I am trying to center it!
Answer: To start with, you're missing a colspan attribute on your second row's only cell

POST ID	POST TITLE

No user found

Without it, that cell will only take up the space of the cell above it. With that resolved you can go on to center it how ever you please

POST ID	POST TITLE

No user found

or

POST ID	POST TITLE

No user found

Your jsfiddle with this implemented
Answer: you were missing colspan
the code below should do

POST ID	POST TITLE

No user found

Comment: this answer also is very useful, and it same of Josh's Answer, Thank you very much
Answer: Few comments:
1)  If you make it so your  element spans 2 columns since your table has 2 columns using:
colspan="2"
2) you can add a class to the  element something like class="error" and add this style to your css:
.error{
    text-align:center;
}

Comment: Yup, i do this already, but the problem was in the colspan, this is first time i hear about colspan, i always see it.. but it first time i know it is very important


Como, usando java, deixar em negrito determinadas partes de uma TextView?

Question: Gostaria de saber como fazer para que uma determinada parte de um texto que será exibido em uma TEXTVIEW ficasse em negrito:

Gostaria que o texto exibido ficasse assim: Valor total => R$ 1100.
Activity:

package genesysgeneration.stackall;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView tvValor;
    private Button btnMais100;
    int valor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvValor=(TextView)findViewById(R.id.tvValor);
        btnMais100=(Button)findViewById(R.id.btnMais100);
        valor=0;

        btnMais100.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                valor+=100;
                tvValor.setText(String.valueOf("Valor total => R$ " + valor + "."));

            }
        });

    }
}

Sei que poderia criar uma outra TextView, mas não me serve. Sei também que poderia fazer isso no .xml da TextView, mas é inviável, pois o texto é dinâmico (não tanto no exemplo, mas no meu real projeto onde quero usar isso).
Answer: Use a classe SpannableString, ela permite anexar objectos de markup a partes especificas de um texto.
TextView textView = (TextView)findViewById(R.id.textView);
String label = "Valor total => ";
String valor = "R$ 1100";

SpannableString textoNegrito = new SpannableString(label + valor);
textoNegrito.setSpan(new StyleSpan(Typeface.BOLD), label.length(), textoNegrito.length(), 0);
textView.setText(textoNegrito);

Comment: no caso de um texto, tal coisa fica inviável
Comment: Não entendi. Pode explicar?


Efeito de paginação

Question: Observe sites e blogs com paginação no cabeçalho ou rodapé. Quando acionado o Botão Anterior ou Próximo, é realçado em negrito o link númerico, sinalizando a página onde o usuário está no momento.
Bem, em meio a visualização desta funcionalidade, surgiu a dúvida:
Como conseguir este efeito sinalizar link de paginação a cada clique em um dos botões de controle(Anterior/Próximo), ou seja, destacar o link da página no qual o usuário está no momento.
Exemplo
O usuário visita a Página Home, e a mesma esta setada como [1] na barra de paginação.
Em seguida, o Usuário desliza o ponteiro do mouse até a barra de paginação ..
<< Voltar [1] 2 3 4 5 6 7 8 9 Avançar >>
.. e clica no botão Avançar .. logo é redirecionado outra página, e na barra de paginação é sinalizado [2] ..
<< Voltar 1 [2] 3 4 5 6 7 8 9 Avançar >>
.. ele prossegue e clica no botão Avançar novamente .. e tão logo é direcionado outra página e agora é sinalizado o link [3] ..
<< Voltar 1 2 [3] 4 5 6 7 8 9 Avançar >>

Isso mesmo ir alternando de número da paginação a cada clique nos botões de controle Voltar/Avançar.
Comment: Os dados da próxima página estão no servidor ou os dados de todas as páginas já foram baixados para o cliente?
Answer: Existem muitas formas de fazer isso, a forma mais conveniente depende do seu ambiente. Isso geralmente é feito server-side, mas como você marcou javascript e css vou apresentar uma maneira de fazer com essas tecnologias.
Quando a pessoa clicar em próximo, basta verificar qual o número da página atualmente está selecionado, de-selecionar essa número, incrementá-lo e selecionar o número incrementado. Quando a pessoa clicar em anterior o raciocínio é semelhante, basta decrementar ao invés de incrementar.
Um exemplo rápido disso seria esse código:

document.getElementById('avancar').onclick = function() { mudaPagina(1) };
document.getElementById('voltar').onclick = function() { mudaPagina(-1) };

function mudaPagina(cont) {
  // Obtém elemento da página atual
  var pagAtual = document.getElementsByClassName('selecionado')[0];

  // Deseleciona a nova página
  pagAtual.className = '';

  // Obtém o número da nova página
  var numNovaPagina = parseInt(pagAtual.innerText) + cont;

  // Seleciona a nova página
  var novaPagina = document.getElementById('p' + numNovaPagina);
  novaPagina.className = 'selecionado';

  // Desabilita voltar/avançar se estiver nos limites
  var limiteEsquerda = document.getElementById('p' + (numNovaPagina - 1)) == null;
  document.getElementById('voltar').disabled = limiteEsquerda;

  var limiteDireita = document.getElementById('p' + (numNovaPagina + 1)) == null;
    document.getElementById('avancar').disabled = limiteDireita;
}
span {
  text-decoration: underline; color: blue; cursor: pointer; padding: 3px;
}
span.selecionado {
  font-weight: bolder;
  background-color: #333;
  color: #fff;
}
<input type="button" id="voltar" value="<< Voltar">
1
2
3
4
<button id="avancar">Avançar >></button>

Apesar de ser simples fazer isso, existem muitas bibliotecas prontas que já vem com vários recursos adicionais. O nome desse tipo de componente é paginator, você pode conferir uma lista com 10 deles em JQuery ou buscar outras alternativas.
Comment: Originalmente usava classList e querySelector, que são APIs elegantes mas não funcionam em navegadores obsoletos. Substituí por métodos mais amplamente compatíveis.
Comment: boa resposta @rodorgas mas a pessoa usar um framework so para fazer isso ai ja e demais +1
Comment: @Assanges a minha implementação é só o básico, falta controle dos elementos a serem exibidos em cada página, elipsar o controle quando há mais páginas que o viewport, suporte a mobile... Programação tem tudo a ver com reusabilidade: faz mais sentido gastar energia em ideias novas, não em problemas que todo mundo continua resolvendo de novo e de novo nos últimos 10 anos.
Answer: Ainda com a resposta de @rodorgas tive uma certa decepção num determinado navegador(não funcionou), então resolvi pesquisar mais um pouco, à saber como poderia desenvolver um script flexível, para todos navegadores.
Como @rodorgas mencionou:
"Existem muitas formas de fazer isso, a forma mais conveniente depende do seu ambiente".
A solução encontrada foi, recriar este Efeito Paginação. Confira:
#Código

/* Rotina Do Botão Próximo */

document.getElementById('menos').disabled=true;

el = document.getElementsByTagName('span');

var contar = 0;

var element_2 = document.getElementById('mais');

element_2.onclick = function() {

contar++;

if (contar == 1) {
    el[0].className = '';
    el[contar].className = 'selecionado';
    document.getElementById('menos').disabled = false;
}
else if (contar == 2) {
    el[1].className = '';
    el[contar].className = 'selecionado';
}
else if (contar == 3) {
    el[2].className = '';
    el[contar].className = 'selecionado';
}
else{
    document.getElementById('mais').disabled=true;
    document.getElementById('menos').disabled=false;
}
};

/* Rotina Do Botão Anterior */

var element_1 = document.getElementById('menos');

element_1.onclick = function() {

contar--;

if (contar == 1) {
    el[0].className = 'selecionado';
    el[contar].className = '';
    document.getElementById('mais').disabled = false;
}
else if (contar == 2) {
   el[1].className = 'selecionado';
   el[contar].className = '';
}
else if (contar == 3) {
   el[2].className = 'selecionado';
   el[contar].className = '';
}
else{
    document.getElementById('menos').disabled=true;
    document.getElementById('mais').disabled=false;
}
};
span {
   cursor: pointer; padding: 3px;
}
span.selecionado {
   font-weight: bolder;
   background-color: #333;
   color: #fff;
}

<input type="button" id="menos" value="&#171 Anterior"/>

1
2
3
4

<input type="button" id="mais" value="Próximo &#187"/>

DICAS
Este Efeito Paginação cai muito bem, com: Ancoras, Array, Strings, Iframe, Table, links, etc...
Outra coisa é, você mesmo pode definir um diretório para conter todas as páginas a serem redirecionados, via paginação, vale dizer que para melhor organização deverão estar nomeadas de A - Z ou ordenadas por números, assim fica mais fácil fazer a programação manual.
IMPORTANTE!
As Dicas bem como Efeito Paginação dada aqui, aplica-se somente para o uso com Javascript, não havendo vínculo algum com linguagem PHP, não tem nada haver em deixar o controle da paginação por conta do Servidor, mas sim criar uma programação obstrusivo(Quando ha Javascript Habilitado no Navegador).
Agora, é só deixar a criatividade solta.

Para dar um visual profissional basta substituir o CSS do código acima pelo do tutorial [Paginação estilo Digg com CSS](http://www.pinceladasdaweb.com.br/blog/2007/03/07/paginacao-estilo-digg-com-css/) que ilustra de modo simples, a criação da barra de paginação.

Ha também um bom tutorial de [Efeito Paginação em CSS3](http://www.betomarques.com/artigos/artigo_011.php)

Efeito de paginação


Python string interpretation and parse

Question: I'm trying to learn how to interpret and parse a string in python. I want to make a "string command" (don't know if is the right expression). But to explain better I will take an example: I want a command like in SQL, where there is a string with keywords that will make a process do what is asking for. Like this: cursor.execute("UPDATE Cars SET Price=? WHERE Id=?", (50000, 1)). But I want to create a format for my project like this (it is not necessary to be with sql): mydef("U={Cars[Price=50000], Id=1}")
Syntax table: <command>={
[<value name>=<value (int/str/float/bool)>], <id>=<value to id>}
Where command is: U=update, C=create, S=select, I=insert, D=delete

Well, I really want to learn how can I do it in Python. If is possible.
Comment: You probably wanna read up on lexing and parsing first. Check out their Wikipedia articles.
Comment: see [Python parsing tools](http://nedbatchelder.com/text/python-parsers.html).
Answer: Pyparsing is a simple pure-Python, small-footprint, liberally-licensed module for creating parsers like the one you describe. Here are a couple of presentations I gave at PyCon'06 (updated for the Texas Python UnConference, 2008), one an intro to pyparsing itself, and one a demo of using pyparsing for parsing and executing a simple command language (a text adventure game).
Intro to Pyparsing - http://www.ptmcg.com/geo/python/confs/TxUnconf2008Pyparsing.html
A Simple Adventure Game Command Parser - http://www.ptmcg.com/geo/python/confs/pyCon2006_pres2.html
Both presentations are written using S5, so if you mouse into the lower right hand corner, you'll see << and >> buttons, a Ø button to see the entire presentation as a single printable web page, and a combo box to jump to a particular page.
You can find out more about pyparsing at http://pyparsing.wikispaces.com.
Comment: This pyparsing does the samething as the .split but simplify the process. Correct if I'm wrong.
Comment: Pyparsing is no longer hosted on wikispaces.com. Go to https://github.com/pyparsing/pyparsing
Answer: Just to be clear, are you aware that Python2.5+ includes sqlite?
import sqlite3
conn = sqlite3.connect(dbname.db)
curs = conn.cursor()
curs.execute("""CREATE TABLE Cars (UID INTEGER PRIMARY KEY, \
        "Id" VARCHAR(42), \
        "Price" VARCHAR(42))""")
curs.execute("UPDATE Cars SET Price=? WHERE Id=?", (50000, 1))

Edit to add: I didn't actually test this; you'll at least need an insert statement to make this work.
Comment: I know, but I really need this way of database process.
Answer: I did this code, I don't know if this will work. Just want the opinion.
>>> s = '<command>={
[<value name>=<value>], <id>=<value id>}'
>>> s1 = s.split('=', 1)
>>> s2 = s1[1].split(',', 1)
>>> s2 = s1[1].replace('{', '').replace('}', '').split(',', 1)
>>> s3 = s2[0].replace(']', '').split('[')
>>> s4 = s3[1].split('=')
>>> s1
['<command>', '{
[<value name>=<value>], <id>=<value id>}']
>>> s2
['
[<value name>=<value>]', ' <id>=<value id>']
>>> s3
['
', '<value name>=<value>']
>>> s4
['<value name>', '<value>']
>>> s5 = s2[1].split('=')

to split the entire command and get the args:
<command>={
[<value name>=<value>],<id>=<value id>}
["<command>", "{
[<value name>=<value>],<id>=<value id>}"]
["
[<value name>=<value>]", "<id>=<value id>"]
["
", "<value name>=<value>"]
["<value name>", "<value>"]
["<id>", "<value id>"]

Python string interpretation and parse


ipad/iphone droppable implementation - detecting element being touched

Question: I am trying to develop a drag/drop functionality that works on both desktop and touch devices such as ipad/iphone.
I have no issues implementing the 'dragging' by simply binding the touchstart, touchmove and touchend events on a given DOM element.
What I am struggling with is how to implement the 'droppable' part. So in other words, how do I figure out on what DOM element was my draggable dropped 'over'??
You can assume the use of jQuery. However, I am NOT using jQueryUI - which currently doesn't work for touch events.
Comment: +1 great question, used it track users movement over pages mobile safari.
Answer: Obviously, you're page is going to have a lot of DOM elements. So I would suggest marking those that may have something dropped on them by using an HTML5 data attribute, i.e. . Then, in your touchend event handler, get the dropped element's position in the document using a combination of jQuery's .offset() and .height() and .width(). Once you have that, cycle through the marked "dropReceiver" divs to get their position. You're then ready to test whether the position of the dropped element intersects with the position of one of the dropReceiver elements.
For example:
draggedElement.addEventListener("touchend", function(){
    var draggedX1 = $(this).offset().left;
    var draggedX2 = $(this).width() + draggedX1;
    var draggedY1 = $(this).offset().top;
    var draggedY2 = $(this).height() + draggedY1;
$('div[data-dropReceiver=true]').each(function(){
    var droppedX1 = $(this).offset().left;
    var droppedX2 = $(this).width() + droppedX1;
    var droppedY1 = $(this).offset().top;
    var droppedY2 = $(this).height() + droppedY1;

    if((draggedX1 > droppedX1 && draggedX1 < droppedX2 && draggedY1 > droppedY1 && draggedY1 < draggedY2) || (draggedX2 > droppedX1 && draggedX2 < droppedX2 && draggedY2 > droppedY1 && draggedY2 < draggedY2)){

        var dropReceiver = $(this);
        //do stuff with the dragged element and the element it was dropped on
        break;
    }
});

I'm pretty sure my lengthy if statement there is correct, but I might have made a typo or two so make sure you re-examine it if you find that this code isn't working.
Also, it's quite likely that the final solution you'll need to implement will be a bit more complex. If it's possible that the dragged element will overlap more than one possible dropReceiver, you can't simply break out of the .each() loop once you find an intersection. Instead, you're going to need to actually calculate how much of the elements are intersecting, and ultimately designate the true dropReceiver to be the one that has the greatest amount of intersection with the dragged element. However, the code I've provided above already gives you the tools you'll need to do this since it essentially provides the coordinates of the bounding rectangles of each element.
EDIT - in response to OP's first comment on this answer
It doesn't seem possible to have the dropReceivers fire a touch event. Even if you bind a touchstart event to them, it won't fire because the dragged element is not a child element of a dropReceiver (I assume), and it must have absolute positioning in order to be dragged. That means it will always be layered (like a higher z-index) above the dropReceivers. Thus, it will always be blocking the user's finger from actually touching the dropReceiver. And therefore the touchstart event will never fire on the dropReceiver.
HOWEVER, I do think there is an easier solution than what I came up with. A touch event on Mobile Safari includes the x and y coordinates of that touch. So rather than testing for the intersection of the dragged element and the dropReceiver, all you need to do is test if the touch point falls within the bounds of the dropReceiver, i.e.
if(touchpoint.x > droppedX1 && touchpoint.x < droppedX2 && touchpoint.y > droppedY1 && touchpoint.y < droppedY2){
   //you've found the dropped element
}

This is definitely a better solution, since it eliminates the more complex situation where the dragged element could be intersecting with two dropReceivers. Since you're testing the single touch point instead, that will always fall within the bounds of only a single dropReceiver, so no intersection area comparisons would need to be made.
Comment: Thanks for the idea Max. You are right, I am expecting to have a very few droppable targets. Your idea of testing if a point intersects with dom element would work; I would use it as a last resort though. My ideal solution would be for the droppable targets to fire out an event when a user's touch is on top of it. If this is not feasible, I will accept your answer :)
Answer: I urge you to consider using jQueryUI for this, so that you don't have to reinvent the wheel.  You can resolve the touch event issue with using jQueryUI by using the jQuery.ui.touch-punch plug-in, which maps mouse events to touch events.
Comment: I haven't used this plugin, and I generally don't user jQueryUI. But my understanding is that jQueryUI tends to be a fairly heavy library. While this doesn't matter on powerful, non-mobile browsers, mobile Safari's javascript engine is much slower. So it's possible that the aesthetics of the dragging wouldn't be nearly as smooth as a custom-made solution like the one I provided.
Comment: It's true - speed becomes an issue when you go from a powerful desktop to an old iPhone.  However, that's an issue with any web application.  Also, keep in mind that you don't have to include every piece of functionality in jQueryUI - just build the .js with the components you need and that will considerably cut it down to size and improve performance.  I've done this and have released web apps with heavy use of jQueryUI's draggable, droppable features and HTML5 animation..  slowness is noticable, but acceptable.
Comment: I am using knockoutJS and my application is designed be driven by making changes to my backend model, which in turn notifies the view that goes off an updates DOM elements. Because jQueryUI will always update the location of an element when being dragged directly (there is no way to disable that), it doesn't play well with what I have. Also my drag/drop requirements are very minimal and a custom solution should do. I am almost there anyway!
Comment: oh well, perhaps this is a better solution for others.


Wordpress não consigo baixar plugin UpdraftPlus

Question: Eu estava baixando os plugins do wordpress mas quando fui baixar o UpdraftPlus deu o sequinte erro:
https://downloads.wordpress.org/plugin/updraftplus.1.16.23.zip…
Descompactando o pacote…
Fatal error: Maximum execution time of 120 seconds exceeded in C:\xampp\htdocs\wp\wp-admin\includes\class-wp-filesystem-direct.php on line 81
Há um erro crítico no seu site. Verifique seu e-mail para instruções.>
Eu olhei o email mas não chegou, alquem sabe qual o problema ?
Comment: Isto resolve o seu problema: [Aumentar timeout de uma página](https://pt.stackoverflow.com/questions/74738/aumentar-timeout-de-uma-p%c3%a1gina)
Comment: Pelo Wordpress diretamente não sei se é possivel fazer, mas pelo php.ini no Xampp você pode aumentar o tempo setando `max_execution_time`, talvez 360 segundos ou mais `max_execution_time = 360`
Answer: Baixa direto pelo navegador, de forma normal, depois sobe para o local que você necessita.
Se ainda assim não conseguir, tente também usando uma VPN. E em último caso, reinicie seu modem.
Abraços
Comment: vlw cara vou tentar
Comment: Depois me diga se conseguiu resolver, e encerre o caso, caso tenha conseguido.
Comment: consequi sim vlw


Why are the Side-Angle-Side and Hypotenuse-Leg similarity rules for triangles true?

Question: My math book tells me that two triangles are similar if all angles are equal to each other ("Angle-Angle-Angle (AAA) Similarity"). There are 4 rules summed up for similarity, I summarised them:

Angle-Angle (AA) Similarity. 2 pairs of angles are equal, so the third pair is equal too.
Side-Side-Side (SSS) Similarity. The ratio between all corresponding sides is constant.

And now the last two, of which I want to know why these rules are true. The two above are obvious for me, but these ones not.

Side-Angle-Side (SAS) Similarity. One angle is the same in both triangles, and the ratio between the sides around the angle is the same.
Hypotenuse-Leg (HL) Similarity. In a right triangle, the ratio between the hypotenuses and between two other are equal.

Can anyone explain 3 and 4?

Lastly, if you have 2 rectangular triangles, and the ratio between the sides around the right angle is the same, they must be similar, correct? Because the third rule applies on this.
Comment: Did you mean right angular triangles ?
Comment: For 4, consider Pythagorean theorem. For 3, Thales.
Comment: Yep, with one angle of 90 degrees.
Comment: @TheDemonix_Hermit *Rectangular* is correct, and idiomatically better, I think.
Comment: @Allawonder https://en.wikipedia.org/wiki/Right_triangle
Comment: @Jean-ClaudeArbaut That bears no relevant relationship to my point.
Comment: Thank you all, I have understood it now.
Answer: For (3), you could use the sine rule for the two triangles to show that the other two angles are equal, respectively, as well. Thus, they are similar.
As you pointed out, (4) comes from (3).
Answer: 3 and 4 are just SAS and HL except that the corresponding sides need to be proportional instead of congruent.  You've already accepted the similarity version of SSS, and AAS and ASA are not on the list because they are covered by AA.
Answer: To see why (3) is true, note that two sides and the angle between them determine a triangle up to congruence. Thus, if in two triangles the angles are equal and the sides around the equal angle severally bear the same ratio to each other, then it means that you have scaled up one triangle by some constant factor to get the other. Since these three elements determine a triangle, it follows that the third sides must also bear the same ratio to each other, and thus be similar.
As for (4), this is just a special case of (3) where the included angle is right.


Strange chord notations in piano sheet: Twisted by Annie Ross

Question: I have to play Twisted with a jazz singer and I came found this lead sheet where the chords are written strangely. Is this the standard notation? Eg., is B'6 = Bbmaj7?
Does anyone know where I can get better B major notes? I found the sheet music here: https://pdfcoffee.com/twisted-lead-sheet-annie-ross-1-pdf-free.html.
Answer: I've seen this sort of thing before - the font used to display the guitar chord symbols doesn't contain the musical flat symbol, and defaulted to apostrophe instead.
The key signature (on the five line musical stave) contains two flats, so that first chord is definitely a B flat chord, not a B natural chord. The tune contains the two notes A flat and F, so the accompanying chord is B flat 7.
Comment: Yes, a misprint,  probably a font issue. Heck, DEFINITELY a font issue. End of.
Answer: Since the piece is written in B♭, it's safe to assume the commas (or no.6) is a misprint, and the chords called B'7 will in fact be B♭7 in reality. Same would go for the E' - should be E♭. B♭maj7 could also have been written with a triangle - B♭▵.
Comment: @JohnBelzaguy - exactly. Can't remember ever seeing them labelled any other way. I put 'maj' in for clarity! C6, F#6 are just as I would expect. Min 6, though, would be Cm6, F#m6 etc. Agreed?
Comment: @JohnBelzaguy - aahh - I meant that the comma/apostrophe looked like an upside down 6, (or even a badly printed 9) not referring to the 6th chord.
Comment: The 6's are actually sixth chords, I confirmed that with the Sher version in The New Real Book. Also Sher uses "ma" and "mi" in chord symbols for major and minor respectively, something I don't care for because they are small and can be hard to tell apart at a glance. Apart from that the Sher books are very good and accurate.
Comment: @JohnBelzaguy - I'd have expected the 6ths to be maj6. With you on 'ma' and 'mi', also using '-' for minors. No real need for *anything* on majors, surely.
Comment: In my experience 6th chords are not preceded by "maj", just: C6 or F#6 for example.
Comment: Oh, that explains it!


XMLHttpRequest not sent

Question: We are three developers working on a web-app project with Django.
Some communications client-server use an API. One particular request is not sending on one of the developer's computer. We use the same Browser (Firefox quantum 64.0 (64 bits)), same OS (Ubuntu 18.04).
Here is the JS snippet:
function requestHandler(url){
    let xhttp = new XMLHttpRequest();
    xhttp.open('POST', url, true);
    xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhttp.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));

    xhttp.onreadystatechange = function(){
        if (this.readyState == 4 && this.status == 200) {
            drawLogTable();
        }
        else if (this.readyState == 4){
            console.log(this);
            new PNotify({
                title: 'Échec!',
                text: "Opération impossible: " + this.statusText,
                type: 'error'
            });
        }
    }
    xhttp.send();
}

Note that url is '../../api/log?action=accept&id=1'
On all the working computers and browsers, the request posts and does a 404 since server-side has no implementation yet. On the non-working computer, chromium works, but under Firefox, the request is not even sent (server log is empty) and the request object is completely empty (no status, no text).
We have other AJAX requests in the same type that are working fine.
Answer: Can you try this:
 xhttp.onload = function(){
        if (this.status == 200) {
            drawLogTable();
}

XMLHttpRequest not sent


Evaluating $\int e^{4x}\sin(6x)\,dx$

Question: I use a $u$-substitution and set $u$ equal to $e^{4x}$ and $dv$ equal to $\sin(6x)\,dx$. Any advice is greatly appreciated.
$$\int e^{4x}\sin(6x)\,dx$$
Comment: That's not $u$-substitution, that's integration by parts...
Comment: Welcome to MSE. Please type your questions rather than posting images. Images can't be browsed, and are not accessible to those using screen readers. If you need help formatting math on this site, [here's](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) a tutorial.  To begin with, surround all math expressions (including numbers,) with `$` signs. Use ^ for exponents and _ for subscripts. `$x_1^{2/3}$` shows up as $x_1^{2/3}$.
Comment: @HansLundmark Re your 1st comment - agreed.  I think that this is what the OP intended.  In IBP, you set $u$ equal to part of the integrand and $dv$ equal to the other part (at least that is what I was taught 50 years ago).
Comment: Note : I believe Hans' duplicate does the job well, a change of constants can easily be handled.
Answer: Let $I = \displaystyle\int e^{4x}\sin(6x)\mathrm{d}x$ . Integrate by parts twice instead of once.
You should find that $I = a(x) + bI$ (where $a(x)$ is some function of $x$ you determine by integrating by parts). From which you can compute what $I$ is.
Answer: $$I=\int e^{4x}\sin(6x)\,dx$$
$\displaystyle u=e^{4x}\Rightarrow u'=4e^{4x}\qquad v'=\sin(6x)\Rightarrow v=-\cos(6x)/6$
$$I=-\frac{e^{4x}\cos(6x)}{6}+\frac46\int e^{4x}\cos(6x)\,dx$$
$\displaystyle u=e^{4x}\Rightarrow u'=4e^{4x}\qquad v'=\cos(6x)\Rightarrow v=\sin(6x)/6$
I'll let you finish it off from here
Answer: If you integrate by parts, then integrate by parts again, you get
$$
\int e^{4x}\sin(6x)\,dx = \Big(\text{something}_1\Big) - \left(\big(\text{something}_2\big) \times \int e^{4x}\sin(6x)\,dx \right)
$$
Therefore
$$
\int e^{4x}\sin(6x)\,dx + \left(\big(\text{something}_2\big) \times \int e^{4x}\sin(6x)\,dx \right) = \Big(\text{something}_1\Big)
$$
And then
$$
\Big(\big(\text{something}_2 \big)+1\Big) \int e^{4x}\sin(6x)\,dx = \Big(\text{something}_1\Big)
$$
Then divide both sides by $\Big(\big(\text{something}_2\big)+1\Big).$
Alternatively, you can write $e^{4x}\sin(6x) = e^{4x}\cdot\dfrac{e^{6ix}-e^{-6ix}} {2i}$ and go on from there.
Answer: $$\int e^{4x}\sin(6x)\,dx=\Im \left(\int e^{4x}e^{6ix}\,dx\right)=\Im \left(\int e^{(4+6i)x}\,dx\right)=\Im \left(\frac{e^{(4+6i)x} }{4+6i }\right)$$ Working the complex numbers
$$\frac{e^{(4+6i)x} }{4+6i }=\left(\frac{1}{13}-\frac{3 i}{26}\right) e^{4x}\left(\cos(6x)+i\sin(6x)\right)$$ and for the same price, you have the integral with the cosine.

Evaluating $\int e^{4x}\sin(6x)\,dx$


Multiple Linear regression - comparing standardized coefficients

Question: When performing multiple regression, can standardized regression coefficients (beta's) be used to rank predictors in terms of their predictive importance. That is, do beta's tell you which predictors are the "best" in the model.
Answer: In OLS, squaring each standardised beta coefficient can inform you of the proportion of variance that each variable explains in the dependent variable. You can then rank order each variable in terms of their respective $R^2$ values, thus determining which variable explains the highest and the lowest proportion of variance in your DV. In social sciences, it is common to assess the importance of predictor variables in this way.