Mensagem enquanto formulário está sendo enviado

Question: Boa noite galera,
Tenho um formulário em php que com a opção de anexar arquivo e depois será enviado para um email, sou iniciante nessa parte de ajax e javascript mas gostaria de saber se tem como exibir uma mensagem enquanto o formulário é "enviado" se é javascript ou só com ajax, se alguém tiver exemplos agradeço
 <form method="post" action="script/trab_send.php" id="form_trab" onsubmit="return validar(this)" autocomplete="off" enctype="multipart/form-data">
                        <input type="text" class="box" placeholder="NOME*" id="nome" name="nome" pattern="[A-Za-zÀ-úÂ-ûÃ-õ]+$" required>
                        <input type="email" class="box" placeholder="E-MAIL*" name="email" required>
                        <input type="tel" class="box" placeholder="TELEFONE*" name="fone" required pattern="\([0-9]{2}\) [0-9]{4}-[0-9]{4,5}$" OnKeyPress="mascara(this)" maxlength="15">
                        <input id="fakeupload" name="fakeupload" class="fakeupload" type="text" placeholder="ANEXAR ARQUIVO" />
                        <input id="realupload" name="realupload" class="realupload" type="file" progress onchange="this.form.fakeupload.value = this.value;" />
                        <input type="submit" value="Enviar" class="btn-ajuda">

                </form>

 `=$_FILES['realupload'];

$mail = new PHPMailer();

$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPDebug = 0;
$mail->Port = 587;
$mail->CharSet = 'UTF-8';
$mail->Host = '';
$mail->Username = '';
$mail->Password = '';
$mail->SetFrom('');
$mail->AddAddress('');
$mail->Subject = '';
$mail->IsHTML(true);
$mail->Body=$body;
$body = "Arquivo: {$arquivo['name']}";

$mail->MsgHTML($body);
$mail->AddAttachment($arquivo['tmp_name'], $arquivo['name']);

 if($mail->Send()){
echo "
Formulário enviado com sucesso! Em breve entraremos em contato!
";

$(document).ready(function(){
        $(".resposta").hide();
        $("#form_trab").ajaxForm({
            target: '.resposta',
            success: function(retorno){
                $(".resposta").html(retorno);
                $(".resposta").show();
            }
    });`

Answer: Adicione uma div com o id de "mensagem"
$("#form_trab").on("subimit", function(){
  $("#mensagem").html("O Form está sendo enviado.");
})
Comment: Fiz um teste aqui, funcionou legal, valeu irmão


Can I truncate users table?

Question: For some reason, I need to truncate the users table, but I don't want to remove the user with ID equal to 1.
Is there any way to do it?
Answer: No, you can't truncate a table and leave data in it at the same time. That would be a contradiction in terms.
You'll need to do a standard delete
DELETE FROM users WHERE uid NOT IN (0, 1)

(it's important to make sure the anonymous user, ID 0, remains there too).
If you use the direct approach, be 100% sure that you know what you're doing. Unless you know different, there will probably be related data that doesn't get cleared out by simply removing an entry from the users table.
The best way to delete users is through the API: user_delete_multiple()
Comment: `drush user-cancel` would also be good, wouldn't it?
Comment: For individual accounts definitely @Mołot, but you'd need to script something to delete all and exclude the important ones

Can I truncate users table?


Sharing and Transposing Trad Jazz songs between Key/Clef

Question: If this should be moved to a different forum, please advise and I will do so.
I just started using MuseScore, which is a free software though they probably have a pro version, and was able to score "Between the Devil and the Deep Blue Sea" in about an hour as a newbie.
I play Bb Tenor Sax, and have the "Dixieland Real Book" in Bb, but I was scoring this in Bass Clef, in concert C, for a trombonist in our band.  The fact is that I don't think that there is even a bass clef version of the Dixieland book, in any key.
For the songs we are rehearsing, I can probably do this in a reasonable amount of time, but since the song is now digital I can transpose or change clef at will - which is cool.  Is it legal to share this file with others, as well as receive MuseScore format files from others in the community?  And if so, are there any resources for this?  I have only found a forum on MuseScore so far and it doesn't appear to deal with this.
Answer: If the material is copyright, it remains copyright despite you illegally copying and/or modifing it.
In the case of the Dixieland book, though the book format may be copyright, the tunes aren't.
There's only one version of MuseScore, and you seem to have it.
Your trombonist would be well advised to come to terms with reading treble clef, both 'In C' and 'In Bb'.   Otherwise he's going to spend mush of his life 'writing stuff out'.


Colliding bodies, tangents and turmoil.

Question: So I have two colliding bodies, body A (radius 40) and body B (radius 10). I'm determining if the bodies will merge or deflect by using tangents to the velocity vector of the colliding body (assuming body A is stationary). If all the tangents intersect body A then the objects will merge.
To visualise this, I'm using desmos (my graphs here).
Note: Body A is red and Body B is green in desmos.
So far i've managed to create a tangent parallel to the velocity vector using the equation:
$y=\left(c_y+c_r\sin\left(1.5708+\theta_c\right)\right)-\left(\tan\left(\theta_c\right)\left(c_x+c_r\cos\left(1.5708+\theta_c\right)\right)+c_y-\tan\left(\theta_c\right)c_x\right)$
Where $\theta_c$ is the angle of the velocity vector, $c_y$ is the $y$ co-ordinate of Body B, $c_x$ is the $x$ co-ordinate of Body B and $c_r$ is the radius of Body B.
The velocity vector is given by:
$y=\tan\left(\theta_c\right)x+c_y-\tan\left(\theta_c\right)c_x$
The problem here is that when i change the angle, the tangent is no longer tangent to Body B and although is still parallel to the velocity vector, it moves in a way I don't intend. I believe with my limited mathematical knowledge that using $tan$ is probably not the best way to go about this and that I should rather use $sin$ and $cos$ in place of $tan$.
Any educated advice would be very helpful as I'm excited to finish the project I'm working on as soon as a I can.
Answer: First note, what you have called velocity vector is really a line, not a vector. All you need from that equation is the slope, which is just $\tan(\theta_c)$. If you wanted to give a vector, you could use
$$ \vec v = \langle v_x, v_y\rangle = \langle \cos(\theta_c), \sin(\theta_c)\rangle $$
Now your tangent has the right slope, but it doesn't pass through the point as intended. This means the problem is not your using $\tan$ at all, but that you are not using the correct values in your equation of the tangent. The equation of a line of slope $m$ through point $(x_0, y_0)$ is
$$
\frac{y-y_0}{x-x_0} = m \;\; \Leftrightarrow \;\; y = y_0 + m(x - x_0)
$$
All you have to do is put $m = \tan(\theta_c)$, $y_0 = c_y+c_r\sin\left(1.5708+\theta_c\right)$ and $x_0 = c_x+c_r\cos\left(1.5708+\theta_c\right)$. Theoretically, for some angles $\tan(\theta_c)$ is undefined, so if that's a problem on your graph, you would be better off using $\sin$ and $\cos$ in a proper direction vector instead of slope, but then you have to input the equation of the tangent not as a Cartesian, $y = mx + b$, but as parametric: $(x,y) = (x_0 + v_xt, y_0 + v_yt)$; I'm not personally too familiar with Desmos, but I'm sure it has a way of doing that.
Note also that what you typed in the question as your tangent is not what you meant, because there's no $x$ variable in it at all.
Personally, I don't get why your velocity vector is what it is, or why your condition for merging is what it is, but I guess that's the physics of your project, so it's not what you were asking about.

Colliding bodies, tangents and turmoil.


Walking a DocumentFile tree

Question: I'm trying to walk an Android DocumentFile tree recursively but I cannot get a list of files to be returned for a subfolder. When I attempt listFiles() on the folder URI, I get the list of root files returned each time.
Why is this not working?
package com.example.usbfoldertest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "USBFolderTest";
    private static final int RQS_OPEN_DOCUMENT_TREE = 2;

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

        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        startActivityForResult(intent, RQS_OPEN_DOCUMENT_TREE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == RESULT_OK && requestCode == RQS_OPEN_DOCUMENT_TREE){
            Uri uriTree = data.getData();
            Log.d(TAG, "WalkTree: " + uriTree.toString() );

            WalkTree( uriTree );
        }
        super.onActivityResult(requestCode,resultCode,data);
    }

    private void WalkTree( Uri uriTop ) {

        Log.d( TAG, "LoadFileList: " + uriTop.toString() );

        DocumentFile documentFile = DocumentFile.fromTreeUri(this, uriTop);
        DocumentFile files[]      = documentFile.listFiles();

        if( files == null ) {
            Log.d( TAG, "files is null in LoadFileList()" );
        } else {
            for( DocumentFile f : files ) {

                if( f.isDirectory() ) {

                    Log.d( TAG, "FOLDER: " + f.getName());

                    if( f.getName().toLowerCase().contains("lost.dir") ) {
                        Log.d( TAG, "IGNORE LOST.DIR");
                    } else {
                        // Recurse into the folder..
                        WalkTree( f.getUri() );
                    }

                } else {
                    Log.d( TAG, "FILE: " + f.getName());
                }
            }
        }
    }
}

Comment: @blackapps: I noticed you responding to a similar question that didn't have a code example. Can you please help?
Comment: You already solved this. Other wise i would have advised to change to WalkTree(DocumentFile docFile).
Comment: @blackapps Is there any way to persist the access allowance to USB/storage drives after reboot? I'm finding that I have to do the ACTION_OPEN_DOCUMENT_TREE intent after each reboot in order to access my USB drive.
Comment: Take persistable uri permission.
Answer: It looks as though upgrading the documentfile library fixes the problem. I add this to my build.gradle and it works as expected now:
implementation 'androidx.documentfile:documentfile:1.0.1'

Answer: I encountered the same issue as you did. I resolved it by changing the function definition to WalkTree(DocumentFile docFile). I discovered that the function documentFile.fromTreeUri consistently returns a DocumentFile object of the main folder, regardless of the Uri inputted for any file within the main folder.

Walking a DocumentFile tree


Jaspersoft: Change textfield borders depending on params

Question: I'm working with jasperStudio 6.3.1 and Java 8.
I have a report and a subreport, and shipping status (received, sent, new, requested, cancelled).
The subreport has a textField with full square borders, and I want to have just the bottom line border, but without doing another subreport just for it.
I was wondering if there's any way to change the style (related to the textfield border) or change directly the border, depending on a parameter that I can get from Java.
(It already takes the shipping status as a parameter).
(edit: jaspersoft crashes everytime I create a new style (it's a bug not resolved yet), so creating a new style in not an option)
Answer: There's an option called "PrintWhenExpression" you can use for it. Or link a style to a parameter.
Using printWhenExpression for each field requires a duplicate field and less scalability.
But I think it's the only option since creating a style makes it crash in JasperStudio 6.3.1.
(Also you can update it if you need and set compatibility)


beginner question on homomorphism (introductory abstract algebra)

Question: For a group $G$ Define, $K(x) = \{g \in G : \operatorname{ord} (g) = x\}$, let $I: G \to H$ be a group homomorphism. Show that
a) if the order of $g$ is n then the $\operatorname{ord} I(g) \leq n$
I have managed to show part (i)
b) if $I$ is injective then $I(K(n)) \subset H(n)$ for $n\geq 1$
I am stuck with part (b). I have no idea how to proceed and use the fact that $I$ is injective to prove the result. Any guidance is fine as I could not find a solution online. For reference, I am using introductory to abstract by Keith Nicholson but I have no solution for the problem.
Sorry for my latex issues; I'm new to this.
Answer: HINT: Show that if there is an $x\in K(n)$ such that $I(x)\notin H(n)$, then $I$ is not injective. Remember, you know that $\operatorname{ord}I(x)\le n$, so your hypothesis here amounts to saying that $\operatorname{ord}I(x)<n$.
Comment: @sarah: You have an $x\in K(n)$, meaning that $\operatorname{ord}x=n$. You want to show that $\operatorname{ord}I(x)=n$ as well. Suppose not. In part (a) you proved that $\operatorname{ord}I(x)\le n$, so it must be that $\operatorname{ord}I(x)<n$. Use that to show that $I$ cannot be injective. HINT: If $\operatorname{ord}I(x)<n$, is it possible for $I(x),I(x^2),\ldots,I(x^n)$ all to be different elements of $H$?
Comment: Hi, thank you for the hint, however I am not able to proceed. I just don't seem to know what to do with it. You say that $ord I(x) \leq n$ means my hypothesis amounts to saying $ord I(x) < n$ How did you get that? Could you perhaps give another nudge in the right direction as I can't seem to move past this.


How do I bit flip binary numbers in python3?

Question: third_number = int(input('Enter a Number: '), 2)
bitwise_NOT = ~third_number
bitwise_NOT = f'{bitwise_NOT:01b}'
print(bitwise_NOT[0:])

I need to interchange binary bits and print out 1's compliment but for some reason it shows wrong values.
Inputs         outputs
10110101010       0110101011
011               00
10001             0010
1111111           0000000
0000              [no output]
111000011         11000100

Comment: Welcome to stackoverflow! Please share a bit more details and explain your code. It is not clear, whether this is your desired or actual output
Comment: This might help https://stackoverflow.com/questions/3920494/python-flipping-binary-1s-and-0s-in-a-string
Comment: As a new user, also take the [tour] and read [ask].
Comment: Take a look over [Here](https://www.w3resource.com/python-exercises/challenges/1/python-challenges-1-exercise-18.php).
Comment: The documentation for the Python standard library says the following about bitwise operations on integer types: *The result of bitwise operations is calculated as though carried out in two's complement with an infinite number of sign bits.* I think you are expecting one's complement. To do what you want it might be easier to accept the number as a string and replace the `0`s with `1`s and vice versa.
Answer: Python int with base 10 do not allow for leading 0's. num = 01 for example will not work. If you're okay with representing your binary string as actual strings, you could do it like this.
def binaryFlip(bitstring: str):
    res = ""
    for bit in bitstring:
        invertedBit = "0" if bit == "1" else "1"
        res += (invertedBit)
    return res

You could also represent your binary string as lists, if you so choose. As lists, you could approach it like this:
def binaryFlip(bitstring: list):
    res = []
    for bit in bitstring:
        res.append(1 - bit)
    return res


AWS Cloud watch Cronjob expression for monday to friday

Question: I am using below cronjob expression in AWS Cloud watch for starting ec2 everyday,
15 3 * * ? *
can anyone please help me with cronjob expression for monday to friday for scheduling ec2
Answer: Simply put MON-FRI in the day of week field and question mark in the day of month field.
15 3 ? * MON-FRI *

Note that the times are always in UTC. See here for docs: https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html
Hope that helps :)


Touchable Opacity Header React Native

Question: I want my header in my react navigation bar to be clickable and have a menu pop up when I click up, I am trying to first just get a log or alert to pop up, but it opens when the screen renders not when I click on it
Here is a link, where I have added a custom component to the header with an onPress but it only fires onRender
https://snack.expo.io/r10TGyieE
What am I doing wrong?
Comment: Please try the code and mark as solved if it is correct.
Answer: https://snack.expo.io/HJvXPJix4
You need to have it call onPress={() => this.someAction()} instead of onPress={this.someAction()}
Answer: just like Dadsquatch said,
This:
onPress={this.someAction()}

is considered as direct code, and it got executed once app reaches the line where it is located (that is why its executed at startup, although you didn't mention it at startup)
But when your use:
onPress={() => this.someAction()}

you telling the compiler that, this is the function to be executed when onPress occurs.
And you can see that it is an arrow function format.
Answer: your onPress event is not binding so it will trigger at first while you run your application.
when using Es6 arrow function your function is bind by default.onPress={()=>this.someFunction()}
otherwise you need to do bind manually onPress={this.someFunction.bind(this)} to invoke your function.

class LogoTitle extends React.Component {
  render() {
    return (
      <TouchableOpacity onPress={()=>alert('test')}>
        <Text style={{ color: "white", fontWeight:'bold' }}> List Layout</Text>
      </TouchableOpacity>
    );
  }
}
Answer: as Tarreq said you can use that
or else
onPress={this.someAction}

as onPress method call a function so you can direct write function name.
Answer: If you would like to avoid making a custom header component, an easy hack is to just add a HeaderLeft component, absolute position it, and then stretch it out 3 times longer than it's original width which is meant to be 1/3 of the screen.
<MyNavStack.Screen
        name="MyScreen"
        // @ts-ignore
        component={MyListScreen}
        options={({ navigation, route }) => ({
          headerLeft: () => (
            <>
            // This is the box that is a touchable opacity
              <TouchableOpacity
                style={{
                  position: "absolute",
                  height: "100%",
                  width: "300%",
                }}
                onPress={Keyboard.dismiss}
              ></TouchableOpacity>
             // This is my menu icon. The menu icon will take precedence
              <TouchableOpacity
                style={styles.headerButtonContainerLeft}
                onPress={() => {
                  navigation.openDrawer();
                  Keyboard.dismiss();
                }}
              >
                <MenuIcon/>
              </TouchableOpacity>
            </>
          ),
// ...The rest of the options

Touchable Opacity Header React Native


What should I change to get a different element name on the response XSD of an automatically generated JAX-WS?

Question: I have created a Web Service in Java with JAX-WS. It is a simple one that just returns an uppercased version of a String:
@WebService(endpointInterface = "mod2.Mod2")
public class Mod2Impl implements Mod2 {

    @Override
    public String mod2(String x) {

        return x.toUpperCase();

    }
}

and its interface:
@WebService
public interface Mod2 {

    @WebMethod
    String mod2(String x);

}

JAX generates the mod2.jaxws package for me with the relevant classes. The response is like this:
@XmlRootElement(name = "mod2Response", namespace = "http://mod2/")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "mod2Response", namespace = "http://mod2/")
public class Mod2Response {

    @XmlElement(name = "return", namespace = "")
    private String _return;

    /**
     *
     * @return
     *     returns String
     */
    public String getReturn() {
        return this._return;
    }

    /**
     *
     * @param _return
     *     the value for the _return property
     */
    public void setReturn(String _return) {
        this._return = _return;
    }

}

When deployed it generates the proper WSDL file with an import to an XSD. This is the XSD:
<xs:schema xmlns:tns="http://mod2/" xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0" targetNamespace="http://mod2/">
    <xs:element name="mod2" type="tns:mod2"/>
    <xs:element name="mod2Response" type="tns:mod2Response"/>
    <xs:complexType name="mod2">
        <xs:sequence>
            <xs:element name="arg0" type="xs:string" minOccurs="0"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="mod2Response">
        <xs:sequence>
            <xs:element name="return" type="xs:string" minOccurs="0"/>
        </xs:sequence>
    </xs:complexType>
</xs:schema>

Now, what I want is to change the element named "return" in the XSD for whatever I want. I have tried changing the @XmlElement(name = "return", namespace = "") in the Mod2Response class but this throws the following error:
GRAVE: WSSERVLET11: failed to parse runtime descriptor: javax.xml.ws.WebServiceException: class mod2.jaxws.Mod2Response do not have a property of the name return

What is it I have to change to achieve this?
Answer: I have found the answer here.
I added @WebResult(name="mod2Result") to my interface:
@WebService
public interface Mod2 {

    @WebMethod
    @WebResult(name="mod2Result")
    String mod2(String x);

}

and then run the wsgen again. Which generated the following Response:
@XmlRootElement(name = "mod2Response", namespace = "http://mod2/")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "mod2Response", namespace = "http://mod2/")
public class Mod2Response {

    @XmlElement(name = "mod2Result", namespace = "")
    private String mod2Result;

    /**
     *
     * @return
     *     returns String
     */
    public String getMod2Result() {
        return this.mod2Result;
    }

    /**
     *
     * @param mod2Result
     *     the value for the mod2Result property
     */
    public void setMod2Result(String mod2Result) {
        this.mod2Result = mod2Result;
    }

}

which also has the @XmlElement(name = "mod2Result") as stated by Joshi but it also changed the name of variable, setter and getter. I tried with the @XmlElement straight in the Response class only with no success.
Answer: @WebService
public interface Mod2 {

@WebMethod
@XMLElement(name="returnChanged")
String mod2(String x);

}

You can try this code in your web service. This is a pseudo code.


Agendamento dinamico de tarefas com spring batch + quartz

Question: Tenho um projecto em Spring Batch + quartz, que carrega um ficheiro processando em seguida os dados do ficheiro. Só que queria implementar uma view com um formulário onde tinha a opção de escolher a hora inicio e hora fim  e os dias onde poderia correr.
Consigo fazer essa funcionalidade com o quartz + Spring batch ?
Obrigado pela atenção
Answer: É possível sim, os comandos do Spring Scheduler podem ser ajustados programaticamente. Mais detalhes aqui
É só persistir os dados da sua view e criar uma nova CronTrigger com os dados de execução.
Comment: hm ok, obrigado pela dica. Vou investigar :)
Answer: Olá! As versões mais atuais do Spring, permite que você crie um método e agende a execução dele com uma anotação Cron. Para isso basta seguir algumas dicas. Vamos a elas:
@Component
class Agendador {
  //Tarefa agendada para todos os dias a 00:00
  @Scheduled(cron="0 0 0 * * *")
  public void tarefaAgendada() {
    //Codigo da sua tarefa
  }
}

Isso com certeza deve resolver seu problema!


AngularJS not working on Plunker

Question: I'm trying to go through a simple tutorial on AngularJS and can't seem to get past the first step. {{ 10 x 10}} isn't appearing as 100. Any ideas?
 <!DOCTYPE html>

        <link rel="stylesheet" href="style.css" />

Hello Plunker!

        {{ 10*10}}

Comment: I just pasted your code in a plunker and it works fine. Can you share your plunk?
Comment: my console is throwing up this error. The XSS Auditor refused to execute a script in 'http://run.plnkr.co/f4S7wzmXuCyrp326/' because its source code was found within the request. The auditor was enabled as the server sent neither an 'X-XSS-Protection' nor 'Content-Security-Policy' header. Maybe it's down to my companies firewall :(
Comment: For anyone who stumbles across this it was down to the company firewall policies.
Answer: You might have mentioned multiple versions of ng-app (probably in  tag).Otherwise your code is working fine
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css" />

Hello Plunker!

    {{ 10*10}}

Here's the demo
Comment: Please look at this [question](https://stackoverflow.com/questions/31001134/how-to-create-network-graph-or-hierarchical-tree-using-visjs-in-angularjs) in here my [plunker](http://plnkr.co/edit/SKfNdsw9g9aCG6wZsQNZ?p=preview) is not working. Please help.

AngularJS not working on Plunker


Carregando reportviewer através de um objeto

Question: Estou utilizando o Report Viewer para fazer alguns relatórios, mas não estou conseguindo acessar alguns dados do meu objeto.
ao invés de fazer conexão direta com o banco eu passo um DataTable como referencia, e já no ReportViewer eu adiciono um DataSet Object.
Essa é a seguinte estrutura utilizada:
class Produto{
    public int Codigo{get;set}
    public string NomeProduto {get;set;}
    public Categoria Cat {get;set;}
}

class Categoria{
    public int Codigo{get;set}
    public string NomeCategoria{get;set;}
}

No ReportViewer eu tenho acesso normal ao Código e NomeProduto porém não consigo acessar os itens do meu objeto Categoria ... Eu utilizo a expressão =Fields!Codigo.Value para Recuperar o código do Produto e no Fields da Expression aparece uma opção com a Categoria First(Fields!Categoria.Value, "Data") porém mesmo que eu coloque isso ele não carrega nada, queria saber como é possivel carrega o nome da Categoria, por exemplo First(Fields!(Categoria.NomeCategoria).Value, "Data")
Answer: É só você associar o DataSet ao seu Table no Report (Os atributos tem de ter o mesmo nome), e passar a lista modelList para o DataSource:
LocalReport relatorio = new LocalReport();
relatorio.DataSources.Add(new ReportDataSource("DSTituloProjetado", modelList));


Unclean hits in tennis

Question: How are "unclean hits" judged in tennis? I mean situations like a ball slipping on a racket, or unintentionally hitting the racket twice (e.g. when the player does not hold the racket firmly enough).
In the official rules, I have found rule 24 (f), stating the point is lost if "The player deliberately carries or catches the ball in play on the racket or deliberately touches it with the racket more than once" (emphasis mine). Does this mean unintentional double touches or prolonged contact are fine?
Also, my friends debated whether hits by the rim are allowed or not. As I have found no mention about that in the rules, I suppose hits by any part of the racket (not only the strings) are allowed. Is that correct?
Comment: I paid a few hundred dollars for the frame so when I use it to make a winner I am happy I am getting my moneys worth. :)
Answer: Under the official rules, it's often (like you emphasized) the intent behind the action that is judged, rather than the action itself - in terms of carrying the ball or a double-hit. Tennis rules follow a sort of "good faith" motto - that a carry or double-hit won't count against you as long as you didn't do it deliberately.
Having said that, if you feel you gained an unfair advantage from one of these actions, you can always (and should) concede the point to your opponent.
Hits by the frame are definitely allowed - so you are correct. In fact, the ball can hit any part of the racquet, including the throat or the handle as long as it hits only the racquet and not your hand or any part of your body. See Rule 24i where it says "except the racquet". Notice the wording there doesn't say "the strings of the racquet" - that wording is on purpose.

Unclean hits in tennis


what happen if i have the same route as path alias?

Question: What if I have the following route in a custom module and a path alias that is equal to the route path?
<code>mymodule.contact:
path: /contact
defaults:
    _controller: Drupal\mymodule\Controller\MyController::contact
requirements:
    _permission: 'access content'
</code>
Comment: If I recall correctly, the alias gets priority. or maybe it was the other way around. What have you found?
Comment: I searched for it i didn't find any answer ! I think you are right aliases are called first
Comment: I had this same issue yesterday - aliases get called first.
Answer: The alias gets priority over the route.
Comment: To be an answer, it lacks references. May you point out where exactly the documentation says a path alias has priority over a module route? If you understood that looking at the Drupal core code, may you show the code that is taking care of routes / path aliases resolution?
Comment: This was the question "What if I have the following route in a custom module and a path alias that is equal to the route path?"
The answer is what I said, the alias takes priority over the route. Even the comments of the OP say exactly that. I don't know how this doesn't provide an answer.
Comment: What about if neither is the case. I cannot point to the code and there is no documentation that says it. But I have done exactly this. I have created a route and a path alias with the same value and the alias takes priority. Are you saying that because I have personal experience, and not official Drupal documentation, with this that I shouldn't answer the question?


Is there a way to get the current spring application context while debugging without using dependency injection nor ApplicationContextAware interface

Question: What i am looking for is getting the spring application context somehow along the following lines :
ApplicationContext ac = SomeSpringClass.getCurrentContext()
// As you may notice, the SomeSpringClass is not real
// it's just what i am looking for as an example

other solution are welcome as long as the do not use the classic ways to get the application context (@Autowired, implementing ApplicationContextAware, Constructor injection, Setter injection...)-
Comment: You would store it on application startup. Why do you want to avoid Autowired though?
Comment: You can use the return value of `SpringApplication.run(args);`
Comment: thanks @Unmitigated, this solution could be used whenever i need the current spring context ? or i need to get it and store it somewhere when the first time the application runs ?
Comment: Sometimes i need to access the application context while debugging the code and i find it disappointing to have to inject it through @Autowired every time i need it when debugging
Answer: You could do something like this (a bean than has a static reference to the context):
@Component
public class StaticSpringApplicationContext implements ApplicationContextAware {

    private static ApplicationContext context = null;

    private static void setContext(final ApplicationContext applicationContext) {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }

    @EventListener
    public static void onApplicationEvent(final ApplicationReadyEvent event) {
        setContext(event.getApplicationContext());
    }

    @Override
    public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
        setContext(applicationContext);
    }

}

and then anywhere in your code when your app is running you can:
StaticSpringApplicationContext.getContext()
this bean will initialize the static variable as soon as the application is loaded and this is it's only purpose :)
Comment: thanks radu-sebastian-lazin, but it's not what i'm looking for. as i discussed with @Unmitigated, i need to access it during debug time so it's somehow an overkill to create this class
Comment: Well this will work in debug mode as well, and you can just copy paste it in your project and after your debug is done just remove the `@Component` and it won't be instantiated or maybe add a `@Conditional`


Is there any way to take a preexisting field with content, and generate taxonomy from it?

Question: I have a content type called 'classes' in the content type is a text field called 'instructor'. I also have a separate content type called 'instructor profile'. The two content types 'classes' and 'instructor profile' are not tied to together in anyway unfortunately (not setup by me).
I would like to tag the existing 'instructor profile' content type with their 'classes'. So for example, if you are looking at the instructor profile, you can see what classes he/she teaches. The easiest way to do this would be take the existing 'instructor' text field under 'classes' and generate the vocabulary so I can match those up with "instructor profile' under a view later on by tagging the Instructor's profile with the right vocabulary.
However, I can't seem to find a module that will take an preexisting field and generate terms from it (or convert that field into a free-tagging taxonomy term). Any idea?
Answer: It sounds like a job for an entity reference field
For example, add a "field_classes" entityreference field to "Instructor profile" referencing the class nodes that instructor teaches.
Alternatively, add a "field_instructor" entityreference field to the "Classes" content type, referencing the instructor profile(s) for that class.
Using Entity Reference, each content type can easily list the related instructors and classes.


where to import modules in flask project

Question: I have been following the flask mega tutorial form Miguel grinberg and the very first "Hello World!" program is confusing me.
More specifically it is the import of the routes module from the init.py module that is confusing me.
Below is the init.py file:
#__init__.py file:

from flask import Flask

app = Flask(__name__)

from app import routes
# above line is the source of confusion.

Below is the routes.py file
from app import app

@app.route('/')
@app.route('/index')
def index():
    return "Hello, world!"

Now if I understand correctly, app is an object of class Flask. when we do "from app import app" in routes.py, I understand that we are importing the app object created in init.py file.
The code then follows is registering a route for this object.
So my question is why do we need to import this routes module in init.py?
I mean in routes module, the app object has been imported and a route has been registered on it. So this should reflect on the app object created in init.py. So why do we need to import it?
I know that it does not work if we remove the import routes statement. But want to know why.
Edit: Though I have a programming background, I am new to python. So it might be misunderstanding on how python files are executed when projects are executed. Also I think this has to do something with python being an interpreted language.
Answer: When you import anything in python, it actually runs the entire file that you are importing. The __init__.py file does not have any information about the routes so by importing it you are essentially providing that information to the app object. In addition, this routes file is never directly ran so that is the only way the views are actually created.
Hope this helps!


Hibernate annotation mapping for java extended classes

Question: I am working on a Spring Hibernate project where I have three classes
BaseEntity, Person & Owner.
Person extends BaseEntity, Owner extends Person.
BaseEntity.java
public class BaseEntity {

    private Integer id;

        Getters & Setters

Person.java
public class Person extends BaseEntity {

    private String firstName;

    private String lastName;

       Getters & Setters

Owner.java
@Entity
@Table(name="OWNERS")
public class Owner extends Person {

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

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

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

    Getter and Setters

Now I want to map all the properties of the three classes in a single table which
is Owner. Can anyone please help me how do I map?
I have a xml based mapping for this & I want to do it in annotation
<class name="org.springframework.samples.petclinic.Owner" table="owners">
        <id name="id" column="id">
            <generator class="identity"/>
        </id>
        <property name="firstName" column="first_name"/>
        <property name="lastName" column="last_name"/>
        <property name="address" column="address"/>
        <property name="city" column="city"/>
        <property name="telephone" column="telephone"/>
    </class>

I thought of using table per class inheritance mapping but here in xml I see no
discriminator column being used.
Answer: Concrete class as a mapped superclass
Use @MappedSuperclass annotation.

JPA (...) defines a mapped superclass concept defined though the @MappedSuperclass annotation or the  element. A mapped superclass is not a persistent class, but allow common mappings to be define for its subclasses.

More: Java Persistence/Inheritance
Example
@MappedSuperclass
public class BaseEntity {
    ...
}

@MappedSuperclass
public class Person extends BaseEntity {
   ...
}

@Entity
@Table(name="OWNERS")
public class Owner extends Person {
    ...
}

Look also at this question: Hibernate : How override an attribute from mapped super class


A problem related with templates and files

Question: I have 4 files:
header.h, header.cpp, header2.h and header2.cpp, like the ones below:
header.h
# pragma once
# include "header2.h"

template<class T>
class firstClass
{
    T var;
public:
    firstClass(T v){   var = v;  }

    void output(void){     cout << var << endl;   }
};

header.cpp
// # include "header.h"

header2.h
# pragma once
# include "header.h"

class secondClass:public firstClass<char>
{
public:
    secondClass(char a):firstClass(a){}
};

header2.cpp
# include "header2.h"

The problem happens if I un-comment the line in header.h, I got an error in code::blocks:
error in file(header2.h): expected template-name before '<' token
Is anyone know why the problem, and how to fix it. Thank you very much)
Comment: firstClass does not depend on secondClass. header.h should not include header2.h. As it is in your post you have an infinite loop from mutual includes - well you would if it wasn't for your pragma once..
Comment: Not the actual problem but be aware of: https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file
Comment: True that the pragma once's break prevent the infinite loop, I overlooked that. But the result is that you are trying to define secondClass before firstClass. SInce secondClass inherits from first class, you can't do that. If firstClass depends on secondClass, well it depends how. Someways will work (possibly with a forwad declaration), others are not allowed.
Comment: If firstClass's dependence on secondClass is inside a method implementation, you can move the header .h include down to after the class definition, but before the method implementation. If its a member function parameter, you will also need a forward declaration at the beginning.
Comment: @ avi berger "firstClass does not depend on secondClass", No it depends, this is only a sample of the main problem. "you have an infinite loop from mutual includes" I do not think so thanks to #pragma once preprocessor directive
Comment: Thank avi berger, can you write a forward declaration for me, all those i write fails
Comment: This may help a little, secondClass will inherit from firstClass, then it will have its own methods, then when it is finished, firstClass will use secondClass. I know this looks like a spaghetti dish, but i am trying to find a genius here who can help me do it )
Comment: You've lost me in your explanation, but from your post, a forward declaration would simply be: `class secondClass;` I've tried it [here](https://godbolt.org/z/cr5obaznv).
Answer: header.h tries to include header2.h. That won't work, as header2.h refers to the template defined later in header.h. Suggest not depending on secondClass (and thus header2.h) in header.h.


Measurability question for càglàd process

Question: I have encounter the following question, which is probably naive for probabilists, but let me still ask it:
Let $\{X_t(\omega): t \in \mathbb{R}\}$ be a real valued càglàd process (that is ''continue à gauche et il existe limite à droite'' instead of the usual càdlàg assumption ), is the following function
$$ \limsup_{t \downarrow 0 } X_t(\omega)$$
measurable? If this is the case, would you please tell me a reference for it, if this is not the case, then what kinds of conditions on the process will such a limit function measurable ?
Thanks a lot.
Answer: If $(X_t)_{t \geq 0}$ is a càdlàg process, then it follows from the very definition of "càdlàg" that
$$\lim_{t \downarrow 0} X_t(\omega) = \limsup_{t \downarrow 0} X_t(\omega) = X_0(\omega).$$
Consequently, the $\limsup$ is measurable since $\omega \mapsto X_0(\omega)$ is measurable (as $(X_t)_{t \geq 0}$ is a stochastic process).

Edit (càglàd case) If a function $f$ is right-continuous at some point $x \in \mathbb{R}$, then we have
$$\limsup_{y \downarrow x} f(y) = \limsup_{n \to \infty} f(y_n)$$
for any sequence $y_n \downarrow x$. Since the (pointwise) $\limsup$ of a sequence of measurable functions is measurable, we conclude that
$$\limsup_{t \downarrow 0} X_t(\omega) = \limsup_{n \to \infty} X_{t_n}(\omega)$$
is measurable whenever $(X_t)_{t \geq 0}$ is a càglàd process. Here $t_n$ denotes an arbitrary sequence satisfying $t_n \downarrow 0$.
Comment: Thanks a lot. And sorry, I made a mistake in my question, the process should be something like: caglad instead of cadlag
Comment: I think one arbitrary $t_n$ does not work. But thanks to Saz's answer, now I think the right argument should be $$\limsup_{t \downarrow 0} X_t(\omega) = \lim_{n \to \infty} \sup_{\substack{0< q < 1/n\\ q \in \mathbb{Q}} } X_q(\omega).$$ The equality of course follows from the one-side continuity.
Comment: @YanqiQIU Why does an arbitrary sequence in your oppinion not work?   Sequential (right)continuity is equivalent to (right)continuity.
Comment: Dear saz, since the process in question is not right continuous but only right continuous. (I am sorry that the very first version of my question confused you.)
Comment: @YanqiQIU Well, yes, of course. But to any caglad function $g$ we can associate a cadlag function $g$ by setting $$g(t) = \lim_{s \downarrow t} f(s).$$ And this shows in particular (now using the right-continuity of $g$) that $$\limsup_{n \to \infty} g(t_n) = \limsup_{s \downarrow t} g(s) = g(t)=f(t+).$$
Comment: Yes, this of course works as well.
Comment: @YanqiQIU But this means in particular that the $\limsup$ does not depend on the chosen sequence $(t_n)_n$.
Comment: Yes, I think we can chose a sequence which will work. But probably the next example will show that an arbitrarily chosen will not suffice.
Comment: Yes, I think we can chose a sequence which will work. But probably the next example will show that an arbitrarily chosen sequence $t_n$ does not suffice. Let $f$ be the function defined on the unit interval such that for any $n \in \mathbb{N}$, the function $f$ is linear on the interval $(\frac{1}{n+1}, \frac{1}{n}]$ and $$f(\frac{1}{n}) = 0, \quad f(\frac{1}{n+1}+) =1.$$ Of course, this is a left continuous function, and $$\limsup_{t \downarrow 0} f(t) = 1,$$ but $\lim_{n \to \infty} f (\frac{1}{n}) =0$.
Comment: @YanqiQIU But in the given example the (right-hand) limit in $0$ does not exist, i.e. $$\lim_{t \downarrow 0} f(t)$$ does not exist ... and this means that $f$ is not caglad.
Comment: Now, I agree with you. I learned something for our discussion, thank you.
Comment: @YanqiQIU Great. Glad I could help you.


Which "platform-dependent" encodings does `open()` default to, on major platforms?

Question: According to the manual, the default input and output encoding of open() is "platform dependent", and usually given by locale.getpreferredencoding(). But what exactly (or approximately) are these platform-dependent defaults?
Edit: A useful answer might be in the form of a list of configurations (presumably a combination of OS and some language/localization settings) and the resulting default encoding.
I'm not expecting a complete reference, but I would like to know what to expect, and what factors to look into, when one of my students stumbles on code that I can run without incident (my box defaults to utf-8). Ideally I can say in advance "If your system is set up like X, you should do Y".
I've looked at the source of getpreferredencoding() and I can see that a number of environment variables are checked, but I don't have a menagerie of different machines to test by hand-- and I don't know what factors going into the setting of all these environment variables. My students are from a variety of nationalities (but mostly Dutch), and use PCs, Macs, and Chromebooks. Is anyone here able to offer an overview of what I can expect?
Comment: Nope, this is about code that reads files with `open()` without specifying an encoding, as the question says.
Comment: @JF, I know how to deal with files and their encodings. Please read the question, and don't explain the world to me. We've been coming across each other on this site for years, usually in Python questions.
Comment: But I'm not asking how to eliminate the behavior. My question asks about a  breakdown of what default encodings are used, for the most common "platforms" (presumably OS's and national language settings, but who knows?)
Comment: @alexis On Windows I think it's the system code page [(list)](https://msdn.microsoft.com/en-us/goglobal/bb964654.aspx). Given a text file in one of these encodings, it's hard to tell what codec was used. You should expect it to be *random* and [*impossible to guess*](https://en.wikipedia.org/wiki/Bush_hid_the_facts).
Comment: Thanks, that's the kind of info I'm after. But is it always just the system codepage? (Anyway, a human can determine the encoding if they know the language of the text; that's not the problem.)
Comment: *"on code that I can run"* -- if it is a Python source code then tell your students to use the [encoding declaration](https://www.python.org/dev/peps/pep-0263/): `# -*- coding: utf-8 -*-` if their source code uses non-ascii literals (utf-8 is the default in Python 3 and therefore the encoding declaration is optional there).
Comment: if you don't know the character encoding then read files using binary mode `'rb'`. Otherwise you can only guess the encoding (`chardet` module).
Comment: The problem you describe in your question is unsolvable. Require your students to hand in any text files as UTF-8 (which you *can* verify with reasonable accuracy).
Comment: I think this is an interesting question, but I don't perfectly understand the problem you (were, 7 years ago) encountering. For my purposes I am just using `locale.getpreferredencoding()` for academic interest, but always specifying 'utf-8' in all my code where such an option is available. I think it would be preferable if a Python app or script or conf file could be configured with a simple switch to say "always assume utf-8". Maybe it can ...
Comment: Hi Mike, the problem was that I was dealing with code written by a lot of beginner programmers who were not programming defensively, and regularly getting different results than I did. Of course anyone can avoid surprises _in their own code_ by always being careful, but sometimes we encounter code that was written in a different environment, and possibly worked correctly for the author.

I was teaching Python, but I'd expect the same in any open programming ecosystem. So I wanted to understand what was going on, and how to analyze it beyond saying "just add `"utf-8"`, that should fix it".
Answer: I think on Windows it would be the current code page, often labelled as ANSI. That's the codec you get on Windows if you specify the name 'mbcs'.
However for most practical purposes you should assume the text files will just have some random encoding. I don't think it's useful to dig into the details of locale.getpreferredencoding(). If I'm not mistaken, you can override that default in your script anyway.
I don't know what you're going to do with those text but if you're going to get files in all those different encodings, know there is no reliable way of finding out that encoding.
If you want to inspect those files one by one by trial-and-error then go ahead, but I would just avoid the problem by telling the students to submit in a set encoding, eg. UTF-8. It's easy enough to open files using open(blabla, 'w', encoding='utf-8').
Comment: What I'm going to do with this information is, I want to be able to say "under X conditions you can expect UTF-8 to be the encoding, but if your computer is like Y then you will get something else." Portability aside, the encoding parameter is optional so we should know when it needs to be used. It bugs me that I have to teach this stuff and don't know what my students can expect. (It was simple enough when the default was ascii-- why couldn't it become "utf8" for everyone?)
Comment: Also, I _think_ it's the system codepage too, but I'm not sure that's always the case; and as I mention in the question, it might be that not even `getpreferredencoding()` is always obeyed. So I was hoping for something based on references, or on extensive experience.
Comment: This boils down to "your question doesn't need answering". Even if you're right (and you might be :-)), I'd still prefer to know the answer...
Comment: Windows uses heuristics to infer the encoding, but Python uses a "default" that is independent of file contents. I am not (and the question is not) after any sort of content-based inference.
Comment: @alexis you almost always need to use the `encoding` parameter when opening a text file with non-ASCII characters. As for the default, "It's platform-dependent and you can't rely on it having a certain value" is a good enough explanation.


BAN logic notation: what does horizontal line mean?

Question: I'm learning BAN logic and trying to understand the notation. The bellow picture is an example form Security Engineering by Ross J Anderson. My question is what does the horizontal line mean? I'm guessing it can be read like and if/then statement where the top is the if condition and bottom is the then part? Also I guess the comma (,) means "and"?

the nonce-verification rule thates that if a principal once said a message, and the message is fresh, then that principal still believes it. Formally,
  $$\frac{A\mid\equiv\sharp X, \quad A\mid\equiv B\mid\sim X}{A\mid\equiv B\mid\equiv X}.$$
Comment: Your guess is correct.
Comment: This looks like someone wrote basic deductive logic in an alien language.
Comment: @MJD thanks, sometimes a simple 'yes' is better than a long winded explanation that muddles the simplicity of the answer. I would say if you post this as an answer I'd accept it but I guess it's too short to be allowed.
Comment: @Celeritas The reason why I went for the "long winded explanation" instead of just saying "yes" is because the description of a deduction as an if/then is not quite correct and confuses meta-levels. It is an if/then outside the language, from one provable assertion to another, by contrast to if-thens inside the language such as the "$P\to Q$" in my example.
Answer: This is a deduction from two statements to a third one. $A\mid\equiv B$ is read "$A$ believes $B$", $\sharp X$ is read "$X$ is fresh", and $A\mid\sim X$ is read "$A$ (once) said $X$". The operator $\mid\equiv$ is right associative, so $A\mid\equiv B\mid\equiv X$ is parsed as $A\mid\equiv (B\mid\equiv X)$ and $A\mid\equiv B\mid\sim X$ is parsed as $A\mid\equiv (B\mid\sim X)$.
The statement in question says: Suppose that in the course of a proof we have derived $A\mid\equiv\sharp X$, meaning that we have proven that $A$ believes $X$ is fresh, and we have also derived $A\mid\equiv B\mid\sim X$, meaning that we have proven that $A$ believes $B$ said $X$. Then we are allowed to deduce the statement $A\mid\equiv B\mid\equiv X$, that is, $A$ believes that $B$ believes $X$.
An inference rule like this is traditionally written with a "fraction bar" notation such as
$$\frac{A\mid\equiv\sharp X\qquad A\mid\equiv B\mid\sim X}{A\mid\equiv B\mid\equiv X}.$$
A propositional logic version that you may be more familiar with is modus ponens: If $P$ is provable and $P\to Q$ is provable, then $Q$ is provable. This rule might be written as:
$$\frac{P\quad P\to Q}{Q}.$$


The zoom function of jqplot doesn't work

Question: consider the code below
<code>xaxis: {
    min: Min,
    max:Max,
    ticks: Ticks,
    renderer:$.jqplot.DateAxisRenderer,
},
</code>
After set the xaxis like this, the zoom function doesn't work on xaxis, how can I solve the problem without removing the line 'ticks: Ticks'?
Answer: Solution (add it to your javascript file):
<code>$.jqplot.LinearAxisRenderer.prototype.createTicks=function(b){var c=this.ticks,e=this.name,a=this._dataBounds,g="x"===this.name.charAt(0)?this._plotDimensions.width:this._plotDimensions.height,f;f=this.min;var k=this.max,d=this.numberTicks,h=this.tickInterval;this._scalefact=(Math.max(g,31)-30)/300;if(c.length){for(e=0;e<c.length;e++)h=c[e],h[0]>f&&h[0]<k&&(d=new this.tickRenderer(this.tickOptions),$.isArray(h)?(d.value=h[0],this.breakPoints?h[0]==this.breakPoints[0]?(d.label=this.breakTickLabel, d._breakTick=!0,d.showGridline=!1,d.showMark=!1):(h[0]>this.breakPoints[0]&&h[0]<=this.breakPoints[1]&&(d.show=!1,d.showGridline=!1),d.label=h[1]):d.label=h[1],d.setTick(h[0],this.name)):$.isPlainObject(h)?($.extend(!0,d,h),d.axis=this.name):(d.value=h,this.breakPoints&&(h==this.breakPoints[0]?(d.label=this.breakTickLabel,d._breakTick=!0,d.showGridline=!1,d.showMark=!1):h>this.breakPoints[0]&&h<=this.breakPoints[1]&&(d.show=!1,d.showGridline=!1)),d.setTick(h,this.name)),this._ticks.push(d));this.numberTicks= c.length;this.min=f;this.max=k;this.tickInterval=(this.max-this.min)/(this.numberTicks-1)}else{g="xaxis"==e||"x2axis"==e?this._plotDimensions.width:this._plotDimensions.height;e=this.numberTicks;this.alignTicks&&("x2axis"===this.name&&b.axes.xaxis.show?e=b.axes.xaxis.numberTicks:"y"===this.name.charAt(0)&&"yaxis"!==this.name&&"yMidAxis"!==this.name&&b.axes.yaxis.show&&(e=b.axes.yaxis.numberTicks));c=null!=this.min?this.min:a.min;b=null!=this.max?this.max:a.max;a=b-c;null!=this.tickOptions&&this.tickOptions.formatString|| (this._overrideFormatString=!0);if(null==this.min||null==this.max&&null==this.tickInterval&&!this.autoscale){this.forceTickAt0&&(0<c&&(c=0),0>b&&(b=0));this.forceTickAt100&&(100<c&&(c=100),100>b&&(b=100));k=f=!1;null!=this.min?f=!0:null!=this.max&&(k=!0);d=$.jqplot.LinearTickGenerator(c,b,this._scalefact,e,f,k);h=null!=this.min?c:c+a*(this.padMin-1);g=null!=this.max?b:b-a*(this.padMax-1);if(c<h||b>g)h=null!=this.min?c:c-a*(this.padMin-1),g=null!=this.max?b:b+a*(this.padMax-1),d=$.jqplot.LinearTickGenerator(h, g,this._scalefact,e,f,k);this.min=d[0];this.max=d[1];this.numberTicks=d[2];this._autoFormatString=d[3];this.tickInterval=d[4]}else{c==b&&(e=0.05,0<c&&(e=Math.max(Math.log(c)/Math.LN10,0.05)),c-=e,b+=e);if(this.autoscale&&null==this.min&&null==this.max){for(var p=!1,s=!1,e=0;e<this._series.length;e++){var l=this._series[e];if(this.name==("x"==l.fillAxis?l._xaxis.name:l._yaxis.name)){for(var q=l._plotValues[l.fillAxis],n=q[0],r=q[0],m=1;m<q.length;m++)q[m]<n?n=q[m]:q[m]>r&&(r=q[m]);m=(r-n)/r;l.renderer.constructor== $.jqplot.BarRenderer?0<=n&&(l.fillToZero||0.1<m)?p=!0:(p=!1,s=l.fill&&l.fillToZero&&0>n&&0<r?!0:!1):l.fill?0<=n&&(l.fillToZero||0.1<m)?p=!0:0>n&&0<r&&l.fillToZero?(p=!1,s=!0):s=p=!1:0>n&&(p=!1)}}p?(this.numberTicks=2+Math.ceil((g-(this.tickSpacing-1))/this.tickSpacing),f=this.min=0,g=b/(this.numberTicks-1),b=Math.pow(10,Math.abs(Math.floor(Math.log(g)/Math.LN10))),g/b==parseInt(g/b,10)&&(g+=b),this.tickInterval=Math.ceil(g/b)*b,this.max=this.tickInterval*(this.numberTicks-1)):s?(this.numberTicks= 2+Math.ceil((g-(this.tickSpacing-1))/this.tickSpacing),a=Math.ceil(Math.abs(c)/a*(this.numberTicks-1)),e=this.numberTicks-1-a,g=Math.max(Math.abs(c/a),Math.abs(b/e)),b=Math.pow(10,Math.abs(Math.floor(Math.log(g)/Math.LN10))),this.tickInterval=Math.ceil(g/b)*b,this.max=this.tickInterval*e,this.min=-this.tickInterval*a):(null==this.numberTicks&&(this.numberTicks=this.tickInterval?3+Math.ceil(a/this.tickInterval):2+Math.ceil((g-(this.tickSpacing-1))/this.tickSpacing)),null==this.tickInterval?(g=a/(this.numberTicks- 1),b=1>g?Math.pow(10,Math.abs(Math.floor(Math.log(g)/Math.LN10))):1,this.tickInterval=Math.ceil(g*b*this.pad)/b):b=1/this.tickInterval,g=this.tickInterval*(this.numberTicks-1),a=(g-a)/2,null==this.min&&(this.min=Math.floor(b*(c-a))/b),null==this.max&&(this.max=this.min+g));a=$.jqplot.getSignificantFigures(this.tickInterval);a.digitsLeft>=a.significantDigits?a="%d":(b=Math.max(0,5-a.digitsLeft),b=Math.min(b,a.digitsRight),a="%."+b+"f");this._autoFormatString=a}else c=null!=this.min?this.min:c-a*(this.padMin- 1),e=null!=this.max?this.max:b+a*(this.padMax-1),a=e-c,null==this.numberTicks&&(this.numberTicks=null!=this.tickInterval?Math.ceil((e-c)/this.tickInterval)+1:100<g?parseInt(3+(g-100)/75,10):2),null==this.tickInterval&&(this.tickInterval=a/(this.numberTicks-1)),null==this.max&&(e=c+this.tickInterval*(this.numberTicks-1)),null==this.min&&(c=e-this.tickInterval*(this.numberTicks-1)),a=$.jqplot.getSignificantFigures(this.tickInterval),a.digitsLeft>=a.significantDigits?a="%d":(b=Math.max(0,5-a.digitsLeft), b=Math.min(b,a.digitsRight),a="%."+b+"f"),this._autoFormatString=a,this.min=c,this.max=e;this.renderer.constructor==$.jqplot.LinearAxisRenderer&&""==this._autoFormatString&&(a=(new this.tickRenderer(this.tickOptions)).formatString||$.jqplot.config.defaultTickFormatString,a=a.match($.jqplot.sprintf.regex)[0],c=0,a&&(-1<a.search(/[fFeEgGpP]/)?c=(c=a.match(/\%\.(\d{0,})?[eEfFgGpP]/))?parseInt(c[1],10):6:-1<a.search(/[di]/)&&(c=0),a=Math.pow(10,-c),this.tickInterval<a&&null==d&&null==h&&(this.tickInterval= a,null==k&&null==f?(this.min=Math.floor(this._dataBounds.min/a)*a,this.min==this._dataBounds.min&&(this.min=this._dataBounds.min-this.tickInterval),this.max=Math.ceil(this._dataBounds.max/a)*a,this.max==this._dataBounds.max&&(this.max=this._dataBounds.max+this.tickInterval),f=(this.max-this.min)/this.tickInterval,f=f.toFixed(11),f=Math.ceil(f),this.numberTicks=f+1):null==k?(f=(this._dataBounds.max-this.min)/this.tickInterval,f=f.toFixed(11),this.numberTicks=Math.ceil(f)+2,this.max=this.min+this.tickInterval* (this.numberTicks-1)):null==f?(f=(this.max-this._dataBounds.min)/this.tickInterval,f=f.toFixed(11),this.numberTicks=Math.ceil(f)+2,this.min=this.max-this.tickInterval*(this.numberTicks-1)):(this.numberTicks=Math.ceil((k-f)/this.tickInterval)+1,this.min=Math.floor(f*Math.pow(10,c))/Math.pow(10,c),this.max=Math.ceil(k*Math.pow(10,c))/Math.pow(10,c),this.numberTicks=Math.ceil((this.max-this.min)/this.tickInterval)+1))))}this._overrideFormatString&&""!=this._autoFormatString&&(this.tickOptions=this.tickOptions|| {},this.tickOptions.formatString=this._autoFormatString);for(e=0;e<this.numberTicks;e++)if(f=this.min+e*this.tickInterval,d=new this.tickRenderer(this.tickOptions),d.setTick(f,this.name),this._ticks.push(d),e<this.numberTicks-1)for(m=0;m<this.minorTicks;m++)f+=this.tickInterval/(this.minorTicks+1),k=$.extend(!0,{},this.tickOptions,{name:this.name,value:f,label:"",isMinorTick:!0}),d=new this.tickRenderer(k),this._ticks.push(d)}this.tickInset&&(this.min-=this.tickInset*this.tickInterval,this.max+=this.tickInset* this.tickInterval)};
</code>
Desription:
Hi,
I know that you asked some time before, but I need solution too so I go through jqplot code and override one function. This function creates ticks and I simply add some comparision if your ticks are in "zoom window".
This line is really long and it doesn't look pretty I know but unfortunately this function has more than 500 rows so I think that compilation is better solution.
If somebody want I can paste whole uncompiled function.


Prove that there exists a number $x_0∈(−1,1)$ such that $f''(x_0)<0$.

Question:
Let $f$ be a continuous function on $[-1,1]$ and twice differentiable on $(-1,1)$.
Suppose that,
$$\int_{-1}^{1} f(x) dx> f(1)+ f(-1)$$
Prove that there exists a number $x_0\in (-1,1)$ such that $f''(x_0)<0$.

I was told to consider $$\int_{-1}^{1} g(x) dx$$ where g is the function whose graph represents the line through $(-1 , f(-1))$ and $(1, f(1))$.
However, I'm not exactly sure how to utilise this information to the question above.
Thanks for help.
Answer: By Trapezoid rule error analysis,
$$\exists \;c \in (a,b)\;:\; \int_{a}^{b}f(x)\,dx - \frac{b - a}{2}\cdot(f(a) + f(b))= - \frac{1}{12}f''(c)(b-a)^3.$$
Now let  $a=-1$ and $b=1$. Can you take it from here?
P.S. Another reference: How prove this $\int_{a}^{b}f(x)dx=\frac{1}{2}(b-a)[f(a)+f(b)]-\frac{1}{12}(b-a)^3f''(\xi)$
Comment: I'm sorry but I haven't learn this theorem in my calculus module. Is there another way to prove this?
Comment: @Buzz Well, I gave you a couple of links for the proof of that theorem. See https://math.stackexchange.com/q/535304
Answer: Hint: if you define the function $g$ as given then
$$
\int_{-1}^1g(x)\,dx=f(1)+f(-1).
$$
Now consider $h(x)=f(x)-g(x)$. You have $h(-1)=h(1)=0$ and
$$
\int_{-1}^1 h(x)\,dx>0.
$$
Can you say anything about existence of local maxima of $h$ on $[-1,1]$?
Hint (cont'd) : the mean value theorem for definite integrals ensures that there exists $c\in(-1,1)$ where $$
h(c)=\frac12\int_{-1}^1 h(x)\,dx>0.
$$
Another application of the mean value theorem gives two points $a\in(-1,c)$ and $b\in(c,1)$ where $h'(a)>0$ and $h'(b)<0$. Can you say anything about $h''$ in $(a,b)$?
Comment: Thanks for your insight. Why is h(-1) = h(1) = 0?
Comment: @Buzz It follows from the definition of $g$ as the line that comes through the same points as the graph of $f$ at $-1$ and $1$.
Comment: Alright I understand why but I'm not exactly sure about the significance of the area between f(x) - g(x) = h(x) > 0. Could you perhaps enlighten me?
Comment: @Buzz The mean value theorem several times could be one way to finish (see the edit).
Answer: Hint: suppose $f''(x) \geq 0$ for all $x$. Then $f$ is a convex function. This implies that $f \leq g$. It is also easy to check that $\int_{-1}^{1} g(x)dx=g(1)+g(-1)$. Hence $\int_{-1}^{1} g(x)dx=f(1)+f(-1)$. Thus $\int_{-1}^{1} f(x)dx \leq \int_{-1}^{1} g(x)dx=f(1)+f(-1)$. This contradicts the hypothesis.
Proof of the fact that $f \leq g$: let $x \in [-1,1]%=$. Then we can write $x=(t)(1)+(1-t)(-1)$ for some $t \in [0,1]$. Hence $f(x) \leq t f(1)+(1-t)f(-1)=t g(1)+(1-t)g(-1)=g(x)$ since $g$ is an affine function.
Comment: Hi. The question stated f''(x) to be less than 0.
Comment: @Buzz We have to prove that $f''(x_0)<0$ for some $x_0$. I proved by contradiction. Assuming that $f''(x) \geq 0$ for all $x$  arrived at a  contradiction.
Comment: Okay but I'm not exactly sure where is the contradiction in your post. Could you perhaps highlight it to me?
Comment: @Buzz I have done that now.


Accessing logs folder of running docker container

Question: Suppose my application generate logs in a folder /app/logs/ . For convenience multiple log files are generated (based on different runtime contexts) for better monitoring. If I containerize my application using Docker, how can I access my logs generated at runtime in logs folder?
My application doesn't have a nohup type of logging and certainly
docker logs -f <container-id>

doesn't seem to work.
Answer: docker logs will only show the stderr and stdout from the process you are running.
Containers work well with a centralised logging system as it fits with their ephemeral/scalable design.  Use syslog, loggly, graylog, logstash, fluentd etc to push your docker logs over the network to a server. Access all your app and context logs in one location.
If that seems like too much...
You can access the logs directly from the host
docker exec <container-id> cat /apps/logs/context.log

You can log to a shared data volume
docker volume create logs
docker run -v logs:/apps/logs <image>

You can log to a host directory
docker run -v /apps/logs:/apps/logs <image>

Comment: Thanks for the information. Every method was quite apt and self explanatory.
Comment: I have few questions now. Does logging to shared data volume or directly on host directory involves docker exec commands. Because in that case, there are memory leak possibilities. In past it led to my machine in a complete locked up/ frozen state and required manual restart of machine.
Comment: The logging itself would be done by the process you `run`, `exec` shouldn't be involved in logging.  You can access the shared and host volumes without using `exec`.  There are ways to access data in a container without `exec` if needed, `cp` for example.


android Xposed Module

Question: I'm trying to develop Appliction that use Xposed Module.
In my project I take samples off Apps runing on the device I can choose which Apps.
In the Xposed Module I can see if one of my Apps is started by a common list, and I don't successed to start my sampling class because I don't have a context. I tried to do it through FileObserver (the Module writing to a file that the FileObserver observe) from boot service and still on the onEvent func in the FileObserver I don`t have a context too and I don't know how can I start my sample class...
Any solution Please?
Answer: If you require the context within your Xposed application check this post.
If you require the context from an application you are hooking, then a nice trick is to intercept the launching of new Activities in the application (Activities extend Context). e.g.:
<code>Class<?> instrumentation = XposedHelpers.findClass(
                "android.app.Instrumentation", lpparam.classLoader);

XposedBridge.hookAllMethods(instrumentation, "newActivity", new XC_MethodHook() {

                @Override
                protected void afterHookedMethod(MethodHookParam param) throws Throwable {

                    mCurrentActivity = (Activity) param.getResult();

                    Log.v(TAG, "Current Activity : " + mCurrentActivity.getClass().getName());

                    Context ctx = (Context) mCurrentActivity;
                }
});
</code>
Good luck!

android Xposed Module


Should CaS-WebApp-Server and Cas-Management-webapp beoverlayed in the same project

Question: I am looking into implementing single sign on functionality for my applications. I am looking into CAS and since I am new to this I wanted to ask it here since the documentation related to the CAS is not complete or accurate.
Cas version - 4.0.x
I have overlayed cas-server-webapp and bought up the login page.
1) Should Cas-server-webapp and cas-management-webapp be overlayed into a single project ?? (Please note version is 4.0.x)
2) If so, could anyone provide the correct url for the management-webapp?? Is it
https://localhost:8443/cas/services/ or  https://localhost:8443/management/. If it is the latter shouldn't there be cas/management??
3) Could you point me to a tutorial or sample project implementing both. The jasig documentation is not clear to me.
My current pom
<code> <build>
    <plugins>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <warName>cas</warName>
                <overlays>
                    <overlay>
                        <groupId>org.jasig.cas</groupId>
                        <artifactId>cas-server-webapp</artifactId>
                        <excludes>
                            <exclude>WEB-INF/spring-configuration/log4jConfiguration.xml</exclude>
                        </excludes>
                    </overlay>
                    <overlay>
                      <groupId>org.jasig.cas</groupId>
                        <artifactId>cas-management-webapp</artifactId>
                        <excludes>
                          <exclude>WEB-INF/spring-configuration/log4jConfiguration.xml</exclude>
                        </excludes>
                    </overlay>
                </overlays>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.jasig.cas</groupId>
        <artifactId>cas-server-webapp</artifactId>
        <version>${cas.version}</version>
        <type>war</type>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.jasig.cas</groupId>
        <artifactId>cas-server-support-generic</artifactId>
        <version>${cas.version}</version>
        <type>jar</type>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.jasig.cas</groupId>
        <artifactId>cas-management-webapp</artifactId>
        <version>${cas.version}</version>
        <type>war</type>
        <scope>runtime</scope>
    </dependency>
</dependencies>

<properties>
    <cas.version>4.0.1</cas.version>
</properties>

<repositories>
    <repository>
        <id>ja-sig</id>
        <url>http://oss.sonatype.org/content/repositories/releases/ </url>
    </repository>
</repositories>
</code>
Is this the correct process? Please let me know if I am going abvout this completely wrong.
Thanks in advance
Answer: Here is a current example project. https://github.com/leleuj/cas-overlay-demo
You should be able to get to the cas management app with /cas-management once your app is built.
Comment: Thanks for answer.I have managed to get the server and management webapps working.
Comment: @john-mercier Quick question, is the link you provided suggesting that the overlay demo you referenced combines both the cas and cas-mgmt app into the same project as _ananth_ is asking about? I haven't tried it yet but would definitely be interested to know if thats the case before I run to do it myself.  Thanks please advise.


Não consigo fazer upload de dois arquivos para o mesmo documento em uma relação ManyToOne

Question: Olá, galera! Boa noite.
Então, eu tenho uma entidade chamada arquivos e outra entidade chamada documento.
Um documento pode ter vários arquivos.
Eu fiz um módulo de upload dos arquivos.
O problema que tô enfrentando é q quando eu faço o upload de mais de um arquivo para o mesmo documento eu tenho um retorno 'not found'. Estou aqui sem saber p onde ir. Alguém poderia me ajudar?
MINHA ENTIDADE ARQUIVO
<code>@Data
@Entity
public class Arquivo {

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

    private @ManyToOne Documento documento;

    private String tipoArquivo;

    private @Lob byte[] data;

    public Arquivo() {}

    public Arquivo(Documento documento, String tipoArquivo, byte[] data) {
        this.documento = documento;
        this.tipoArquivo = tipoArquivo;
        this.data = data;
    }
}
</code>
MINHA ENTIDADE DOCUMENTO
<code>@Data
@Entity
public class Documento {

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

    private @ManyToOne Morador morador;

    @NotNull
    @JsonFormat(pattern = "dd/MM/yyyy")
    private LocalDate dataEntrega;

    private @Enumerated(EnumType.STRING) TipoDocumento tipoDocumento;

}
</code>
MEU CONTROLLER DE ARQUIVO COM O MÉTODO DO UPLOAD
<code>@ApiOperation(value = "Upload de uma imagem", notes = "Upload de uma nova imagem.")
    @Transactional
    @ResponseStatus(HttpStatus.CREATED)
    @PostMapping("/uploadArquivo")
    public Arquivo uploadArquivo(
            @ApiParam(name = "arquivo", value = "Arquivo que irá ser feito o upload.", required = true)
            @RequestParam("arquivo") MultipartFile arquivo,
            @ApiParam(name = "documento_id", value = "id do documento.", required = true, type = "long")
            @RequestParam("documento_id") long id) {

        Documento documento = docRepository.findById(id)
                .orElseThrow(() -> new NegocioException("Documento não encontrado."));

            Arquivo arq = null;

            try {
                arq = new Arquivo(documento, arquivo.getContentType(), arquivo.getBytes());
            } catch (Exception e) {
                throw new FileStorageException("Não foi possível criar o arquivo. Por favor, tente novamente.", e);
            }

            return repository.save(arq);
        }
</code>
O RETORNO QUE TENHO É ESSE
<code>{
    "timestamp": "2020-07-29T02:35:19.853+00:00",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/UploadArquivo"
}
</code>
Answer: Essa mensagem de erro em específico não é relacionada ao código ou lógica da sua aplicação. A mensagem "not found" é relacionada ao "path" da sua API. Você não está chamando a API certa. Você está chamando "UploadArquivo", sendo que a API é "uploadArquivo"
Comment: Putz, mano. Me passei geral kkkkk. Valeu aí!!


How can I use dygraphs in powerbi?

Question: I can not see how to interact with the powerBI dataset.
I'm using a simple chart. I can run using Rstudio but I can't run the same code using R visual in powerBI.
QCData <- cbind(QC_xts)

dygraph(QCData,ylab="Timestamp", main="´Quality Control") %>%
 # dySeries("QC_xts",label="XS") %>%
  # dySeries("..2",label="LNKD") %>%
  dyOptions(colors = "blue") %>%
  dyRangeSelector()

My cod is working in R studio
QCData <- cbind(QC_xts)

dygraph(QCData,ylab="Timestamp", main="´Quality Control") %>%
 # dySeries("QC_xts",label="XS") %>%
  # dySeries("..2",label="LNKD") %>%
  dyOptions(colors = "blue") %>%
  dyRangeSelector()

The erro is not display any chart.
PBI show this error:
An exception of type Microsoft.PowerBI.ExploreServiceCommon.ContainPIIException occured.
Comment: Welcome to SO! Please provide a [reproducible minimal example](https://stackoverflow.com/q/5963269/8107362)
Answer: I've just had the same issue in PowerBI and resolved it by simply adding in library(ggalt) at the start of my script.    In Rstudio I had accidentally removed that line but it was still working as the library had already been loaded.   When copying the code over to PowerBI you have to declare all the libraries at the start of the script, as unlike RStudio it doesn't "remember" what was initially loaded.
I'm no R expert at all but I was literally searching google for the same issue you had and fortunately figured out a solution that I hope you can use too.   In your case it might not be  library(ggalt) but could be some other library you didn't declare
Answer: I got the problem in here. The code bellow works fine.
The problem was editing pbiviz.json in the supportUrl and gitHubUrl must be HTTPS. I missed the "s" in the end and it seems that was the problem.
  source('./r_files/flatten_HTML.r')
  ############### Library Declarations ###############
  libraryRequireInstall("ggplot2");
  libraryRequireInstall("plotly")
  ####################################################
  ################### Actual code ####################
  p <- plot_ly(x = Values$Timestamp, y = Values$Eth, type='scatter', mode = 'lines');
  ####################################################
  ############# Create and save widget ###############
  internalSaveWidget(p, 'out.html');
  ####################################################

How can I use dygraphs in powerbi?


Good Introduction to Hopf Algebras with Examples

Question: I want to learn more about hopf algebras but I am having trouble finding a down to earth introduction to the subject with lots of motivation and examples. My algebra knowledge ranges from Dummit and Foote, Atiyah-Macdonald commutative algebra, and Hartshorne level algebraic geometry.
What are good places to look at for a hopf algebra beginner? My main motivation is for studying groupoid schemes from an algebraic point of view.
Comment: The book by Sweedler is really good.
Answer: The following texts provide self-consistent introductions to the topic of Hopf algebras, almost  from the scratch:

Dascalescu, Nastasescu, Raianu, "Hopf algebras, an introduction",
S. Montgomery, "Hopf algebras and their actions on rings",
Moss E. Sweedler, "Hopf algebras",
Kassel, "Quantum groups",
S.Majid, "Foundations of Quantum Group theory",
S.Majid, "A quantum groups primer",
E.Abe, "Hopf algebras",
D. Radford, "Hopf algebras"

1.,  4., and 8. are the most elementary introductions in the sense that they start from the fundamentals and drive you up to some of the very high ends. 1. emphasizes structure theory and contains an extreme wealth of examples with detailed computations and solved exercises (it would be my personal recommendation for someone to begin with), while 4. emphasizes representation theory and the braided monoidal categories point of view. (4. contains an extensive general introduction as well).
3., 7., are the oldest books on the topic. Lots of today's hopf algebraists have started studying from these books. Still authoritative today. (7. contains an extensive general introduction on various topics from abstract algebra).
2., is a relatively small and dense book, addressed to students who feel experienced with abstract algebra texts. However it covers unbelievably many examples and details and sheds light into myriads of dark corners. Very strong in the category theoretical point of view, it covers -in sufficient detail- research results until the mid 90's.
5., 6. would be useful for someone interested in the mathematical physics motivations for studying the topic: the use of quantum groups and non-commutative geometry models in physics is hiding behind each example and each computation. Might be too heavy for a first introduction. They focus on various different aspects, but i would not recomend them as starting points but rather as complements to someone already comfortable with the basic notions. However, they are unique in the sense that they contain a braided graphical calculus -developed by the author- for performing computations in braided monoidal categories.
In conclusion, if i were to teach a general introductory course to first year postgraduate students, I would be based on 1. and 2. using 4. as a supplement (in the first place) and I would recomend 3.,7.,8. for further support. 5. and 6. would be good sources for further search in the bibliography and for mathematical physics or graphical calculus related projects.
If however, i would like to be oriented towards quasitriangularity and braided monoidal categories (i.e. the more representation theoretical aspects of the topic) then I would recommend 2., 4., 5., 6., 8. (in that order).
Comment: These types of answers are my favorite because you just gave anyone a pathway towards understanding the theory. I wish answers like these existed for more topics!
Comment: Nice videos of Hopf algebra and combinatoric by Federico Ardela:.     https://www.youtube.com/playlist?list=PL-XzhVrXIVeRLeezwY9h4M68k6yB3yOo-


Remove extra column level from dataframe

Question: My dataframe looks like this.

It's the result of this code:
survival_by_position = survival_by_position.groupby("POSITION")["SURVIVED"].value_counts().rename("Count").reset_index()
survival_by_position = survival_by_position.pivot(index = "POSITION", columns = "SURVIVED", values = "Count")
survival_by_position = survival_by_position.rename(columns = {False: "DEAD", True: "SURVIVORS"})

I want it to look like this.

That is, POSITION should remain the index, but the columns DEAD and SURVIVORS should "come down", and SURVIVED should disappear. I've tried to (re)set the index, create a new dataframe and assign it the right index and columns, nothing worked. I either get all NaNs, or the default integer index, or some error. I know this has got to be some multi-index trickery, but I am not familiar with that so I don't know how to fix it.
Answer: You just have to rename the column axis:
survival_by_position = survival_by_position.rename_axis(columns=None)

Full code:
survival_by_position = (
    survival_by_position.value_counts(['POSITION', 'SURVIVED'])
                        .unstack('SURVIVED').fillna(0).astype(int)
                        .rename(columns={True: 'DEAD', False: 'SURVIVORS'})
                        .rename_axis(columns=None)
)

Some modifications:

replace groupby / value_counts by value_counts

replace pivot by unstack

remove rename('Count')

remove reset_index()
Comment: Renaming the column axis doesn't "move" down the two column names. I know the result is still functionally identical to a normal dataframe (or so it seems to me), but I wonder why there doesn't seem to be a way to make it look like one.

I didn't know about the `unstack` trick, very cool way to avoid `groupby`.
Comment: If you want your expected output, you have to append `.reset_index()` (modification 4)
Comment: That works, but then "POSITION" is no longer the index. Is there way to make it such, at that point?
Comment: No this is the default representation of a dataframe in jupyter notebook. The index is one row below. You can't change this.
Comment: That's right, I remember now.


Ordenar resultados com mês e ano

Question: tenho uma tabela com os campos mes E ano. Como posso ordenar os resultados de acordo com o mês.
Já estou ordenando de acordo com o ano
=> SELECT * FROM tabela WHERE id_cliente = '$id_cliente' ORDER BY ano DESC
Agora como posso ordenar os meses também ?
 Ex ( Janeiro, fev, mar... )
PS: mes(varchar 255), ano (varchar 255) isso séria uma má pratica?
Comment: Má prática por usar o nome? Vai depender da regra da sua aplicação. Mas que usar `varchar 255` pra isso é absurdo, é.
Comment: Como você esta armazenando o mês? Número ou escrito?
Comment: Escrito, isso seria uma má pratica?
Comment: Sim, por questão de desempenho, colocar um campo do tipo `tinyint` e número de 1 a 12, ficaria mais leve e mais simples de fazer a ordenação que você deseja
Comment: @MarcelodeAndrade pode me indicar umas docs sobre esses valores? como usa-los corretamente?.
Comment: Em geral eu não consideraria ideal. O `VARCHAR 255` usando em utf8mb4 irá custar 1020 bytes, no máximo. Em versões antigas do MySQL, não sei atualmente, seria até necessário habilitar o `innodb_large_prefix` para que pudesse definir um index nessa situação. Enquanto que usar o `TINYINT` utiliza um único byte, portanto pode armazenar 256 valores, suficientes para armazenar `1` até `12`. O ano a mesma coisa, usando `SMALLINT` iria usar 2 bytes, e poderia definir "2017" tranquilamente.
Comment: Você não acha que utilizar um campo do tipo date seria mais conveniente?
Answer: Dessa forma com o mês do tipo varchar, tem que usar o FIELD no ORDER BY
SELECT * FROM tabela
WHERE id_cliente = '$id_cliente'
ORDER BY FIELD(mes, 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'), ano DESC

Comment: Obrigada Tafarel, funcionou corretamente!

Ordenar resultados com mês e ano


Feeds: use custom field as unique field for mapping

Question: I am using D7, Feeds, XPath Parser.
For mapping, I need to use a custom field as the unique field. I am retreiving data from booking.com and the unique value their is the hotel id, so i need to save this hotel id from the user as well as retrieve data from booking.com bsed on this unique field and map to my contents based on this unique field.
In the documentation of feeds i found this -
Use field other than nid as unique node field in feeds for 7.x-2.x
It says you need to apply a patch from this comment - http://drupal.org/node/661606#comment-5921904
This patch applies to a file called field.inc in the mappers folder of feeds. However this file is not even present there.
The patch also applies to another file, however running the patch gives errors.

Is field.inc actually present in feeds/mappers?
Am I making some mistake in applying the patch?
Is there any other way of achieving  - custom field as unique field for mapping?

Any help on this would be greatly appreciated. Thank you.
Answer: This tutorial works for me:
How to configure unique fields in Drupal feeds importer ?
See also the official documentation, which states that you can either use the Field Validation module, or write a custom solution implementing hook_feeds_processor_targets_alter().
Comment: This should be the accepted answer now. Since Feeds 7.x-2.0-beta1 no patches are needed anymore.
Answer: If you will only be using one Feeds importer (i.e. only importing from a single XML source), you can do this without applying any patches. In the importer mappings, just map the hotel ID field to GUID and set it as unique. If you need to use hotel ID in your content type, map it to another field as well.
From your description, it sounds like your needs might be more complex (i.e. importing from multiple sources into the same content type)? If so, you can use Field Validation module to set your field as unique. Note that last time I used it, this also required a patch - but it may be committed now. This Field Validation issue provides some more info.
I think the method you referred to (using Unique Field module) is a little outdated now.
Comment: Thanks for the answer. However I was able to get my requirement fulfilled from another patch and using field validation module. I haven't tried your method yet though it looks like it could have worked too :) Thank a lot!
Answer: Answering my own question -
Using patch from - http://drupal.org/node/661606#comment-6481214 on the feeds module and a patch from - http://drupal.org/node/1705386#comment-6481224.
Hence using Feeds with Field Validation. First a validation for unique must be added to the required field. In the mapping for just like title can be set as unique even this field will have the setting to be set as unique.


Validate descendants of unknown XML elements via XSD?

Question: My XML file looks like :
<root>
    <template>
        <unknownTag>
            <anotherUnknownTag/>
            <anotherKnownTag/>
            <field name='price'/>
        </unknownTag>
    </template>
    <template>
        <field name='salary'/>
    </template>
    <anothorKnownTag/>
</root>

I want to apply regex restriction to the attribute name of the tag <field/> whether it's a child or a grandchild or a grand grandchild and so on.
I have tried the following code, but the regex only applied to the element field when it's a direct child of the template tag.
  <xs:element name="template">
    <xs:complexType>
        <xs:complexContent>
        <xs:sequence>
            <xs:element name="field">
                <xs:complexType>
                    <xs:simpleContent>
                        <xs:extension base="xs:string">
                            <xs:attribute name="name">
                                <xs:simpleType>
                                    <xs:restriction base="xs:string">
                                        <xs:pattern value="[a-z][a-z_]*"/>
                                    </xs:restriction>
                                </xs:simpleType>
                            </xs:attribute>
                        </xs:extension>
                    </xs:simpleContent>
                </xs:complexType>
            </xs:element>
            <xs:any processContents="lax"/>
        </xs:sequence>
    </xs:complexType>
  </xs:element>

Answer: You can actually express the requested constraints in XSD 1.0:
XSD 1.0
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="root">
    <xs:complexType>
      <xs:sequence>
        <xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="field">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:string">
          <xs:attribute name="name">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:pattern value="[a-z][a-z_]*"/>
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

Note: You can even simplify root to be just
  <xs:element name="root"/>

but the longer form is less cryptic.
Valid XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <template>
        <unknownTag>
            <anotherUnknownTag/>
            <anotherKnownTag/>
            <field name="price"/>
        </unknownTag>
    </template>
    <template>
        <field name="salary"/>
    </template>
    <anothorKnownTag/>
</root>

Invalid XML
The following XML has two validity errors due to field/@name values not matching the regex:
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <template>
        <unknownTag>
            <anotherUnknownTag/>
            <anotherKnownTag/>
            <field name="price999"/>
        </unknownTag>
    </template>
    <template>
        <field name="big salary"/>
    </template>
    <anothorKnownTag/>
</root>


Performance of Linux software raid-1 across SSD and HDD (partitions)

Question: How does Linux software raid-1 work across disks of dissimilar performance.
Would a raid-1 across ssd and hdd partitions give me a mirror of the ssd contents while not impacting the read speed?  I only need good read speed.
Or will it just distribute "reads" round-robin between the drives, giving poor read performance?
(I understand and accept that write performance will be as slow as a hdd.)
Comment: How do you create that raid1? LVM or MDADM?
Comment: I am familiar with mdadm.  Are there TRIM problems with 'nested' SSDs?
Answer: From the mdadm-developer-blog I would say - you need at least the 3.2.1 version with that policy-stuff. This sounds as if you can define one member as spare instead of using it for active reading/writing. So in your case the harddisk should be the spare.


Cálculo de sub-redes e hosts

Question: Não estou conseguindo entender como calcular isso:

Determine a quantidade máxima de sub-redes, quantidade máxima de hosts por sub-rede, e para o endereço IP informe o endereço de sub-rede, endereço de broadcast, faixa de hosts válidos para a sub-rede, do seguinte endereço IP:
10.8.7.1/16

A mascara de sub-rede é: 255.255.0.0
Comment: http://stackoverflow.com/questions/33199512/subnet-mask-how-to-segment-three-separate-networks
Answer: Eu consegui fazer, esta ai a resposta para quem quiser conferir:
Quantidade de Subredes: 2⁸ = 256 subredes
Quantidade de Hosts válidos: 2¹⁶ = 65536 - 2 (broadcast e endereço da rede) = 65534 endereços válidos
Endereço de Rede: 10.8.0.0
Hosts Válidos: 10.8.0.1 até 10.8.255.254
Broadcast: 10.8.255.255
Para  confirmar, podemos utilizar esta calculadora: http://www.gwebtools.com.br/calculadora-subrede

Cálculo de sub-redes e hosts