selecting entire table when selecting columns - How

Question: Currently i have joined together several tables. now i want to select some columns out of this joined mesh.
my question is: is it possible to select all columns of a specific table?
for example:
select col1,col4,col7,all_columns.Table1,col9 from (joined tables including Table1)

if it is possible, how to implement it
Comment: Have you heard about Table1.*  ?
Answer: this is what you want?
select col1,
       col4,
       col7,
       Table1.*,
       col9
from (joined tables including Table1)

Comment: hmm, seems easy and promising
Answer: How about this?
SELECT ... Table1.*, ... FROM ...


Cron job to detect when system power is lost returning invalid timings

Question: We are having issues with our electrics, so I wrote a simple bash script to try to log when the events were happening. I've created a cron job that runs every minute to run the script.
The idea of the script is quite simple, write the timestamp to /tmp/powerlast.tmp. If next time the script runs, the gap in time is greater than 90 seconds append an entry using the $powerlast value to the powerfailure.csv file.
I'm getting some strange results, for example at on 24th Dec @ 11:50am the electrics tripped, but the script is telling me that it occurred at 11:20am - this is wrong.
#!/bin/bash
powercsv=~/powerfailure.csv
powerlast=/tmp/powerlast.tmp
frequency=60                  # seconds
margin=$(($frequency+($frequency/2)))
if [ ! -f "$powercsv" ]; then
  echo "timestamp,weekofyear,dayofyear,day,date,month,year,hour,minute" > "$powercsv"
fi
if [ ! -f "$powerlast" ]; then
  echo "4133980799" > "$powerlast"
fi
last=$(($(cat "$powerlast"))) # seconds since epoch
now=$(($(date +%s)))          # seconds since epoch
lastdate=$(date -d @$last)
nowdate=$(date -d @$now)
if [ $now -lt $last ]; then
  # first run ever
  echo "$now" > "$powerlast"
else
  # aim is to detect gaps greater than the run frequency.
  # echo "margin $margin frequency $frequency"
  echo "$now" > "$powerlast"
  gap=$(($now-$last))
  if [ $gap -gt $margin ]; then
    echo "$nowdate: Power interruption detected at $lastdate! $gap exceeds $margin second limit."
    weekofyear=$(date -d @$last +%V)
    dayofyear=$(date -d @$last +%j)
    day=$(date -d @$last +%a)
    date=$(date -d @$last +%d)
    month=$(date -d @$last +%m)
    year=$(date -d @$last +%y)
    hour=$(date -d @$last +%H)
    minute=$(date -d @$last +%M)
    echo "$last,$weekofyear,$dayofyear,$day,$date,$month,$year,$hour,$minute" >> "$powercsv"
  fi
fi

I scheduled a task to run * * * * * /home/usr/powerfailure/powerfailure.sh via crontab -e
I've checked the file that I use to track the last uptime and it seems to be OK (I checked my clock and it's the same).
$ grep  -Eo '^[0-9]+' /tmp/powerlast.tmp | while read x; do date -d @$x; done
Tue Dec 24 12:41:02 GMT 2019

Oddly, all my entries seem to be logging approximately 20 past the hour.
$ grep -Eo '^[0-9]+' powerfailure.csv | while read x; do date -d @$x; done
Fri Dec 20 13:03:02 GMT 2019
Sat Dec 21 10:18:01 GMT 2019
Sat Dec 21 11:18:02 GMT 2019
Sat Dec 21 19:20:02 GMT 2019
Sun Dec 22 02:19:01 GMT 2019
Mon Dec 23 14:21:02 GMT 2019
Tue Dec 24 07:20:02 GMT 2019
Tue Dec 24 11:20:01 GMT 2019

I checked the /var/log/syslog and found some odd timestamp ordering in there, so I think this may be to blame, but I don't know why it's doing this.
Dec 24 11:45:01 raspberrypi CRON[9915]: (usr) CMD (/home/usr/powerfailure/powerfailure.sh)
Dec 24 11:46:02 raspberrypi CRON[9976]: (usr) CMD (/home/usr/powerfailure/powerfailure.sh)
Dec 24 11:47:01 raspberrypi CRON[10011]: (usr) CMD (/home/usr/powerfailure/powerfailure.sh)
Dec 24 11:17:46 raspberrypi cron[324]: (CRON) INFO (pidfile fd = 3)
Dec 24 11:17:46 raspberrypi cron[324]: (pi) ORPHAN (no passwd entry)
Dec 24 11:17:46 raspberrypi cron[324]: (CRON) INFO (Running @reboot jobs)
Dec 24 11:18:01 raspberrypi CRON[737]: (usr) CMD (/home/usr/powerfailure/powerfailure.sh)
Dec 24 11:19:01 raspberrypi CRON[1459]: (usr) CMD (/home/usr/powerfailure/powerfailure.sh)
Dec 24 11:20:01 raspberrypi CRON[2308]: (usr) CMD (/home/usr/powerfailure/powerfailure.sh)
Dec 24 11:20:01 raspberrypi CRON[2313]: (smmsp) CMD (test -x /etc/init.d/sendmail && test -x /usr/share/sendmail/sendmail && test -x /usr/lib/sm.bin/sendmail && /usr/share/sendmail/sendmail cron-msp)
Dec 24 11:52:35 raspberrypi CRON[3237]: (usr) CMD (/home/usr/powerfailure/powerfailure.sh)
Dec 24 11:53:01 raspberrypi CRON[3657]: (usr) CMD (/home/usr/powerfailure/powerfailure.sh)
Dec 24 11:54:01 raspberrypi CRON[4600]: (usr) CMD (/home/usr/powerfailure/powerfailure.sh)

Answer: I moved the tracking file out of /tmp and altered my script to use touch instead. The script now tracks the modified date of the file instead of the content. I'm still unclear why it wasn't working as intended, but this system is working exactly as intended.
#!/bin/bash
powerdir=~/powerfailure
mkdir -p "$powerdir"
powercsv="$powerdir/powerfailure.csv"
powertouch="$powerdir/powerlast.touch"
frequency=60                  # seconds
margin=$(($frequency+($frequency/2)))
if [ ! -f "$powercsv" ]; then
  echo "timestamp,weekofyear,dayofyear,day,date,month,year,hour,minute" > "$powercsv"
fi
if [ ! -f "$powertouch" ]; then
  touch "$powertouch"
fi
last=$(date -r "$powertouch" +%s) # seconds since epoch
now=$(($(date +%s)))              # seconds since epoch
lastdate=$(date -d "@$last")
nowdate=$(date -d "@$now")
# echo "Last: $last, Now: $now, Last Date: $lastdate, Now Date: $nowdate"
if [ $now -lt $last ]; then
  # first run ever
  echo "$now" > "last"
  echo "Reset power last variable"
  echo "Reported: $(date)"
  echo "Last: '$last' -> $(date -d "@$last")"
  echo "Current: $now' -> $(date -d "@$now")"
else
  # aim is to detect gaps greater than the run frequency.
  # echo "margin $margin frequency $frequency"
  touch "$powertouch"
  gap=$(($now-$last))
  if [ $gap -gt $margin ]; then
    echo "Reported: $(date)"
    echo "Last: '$last' -> $(date -d "@$last")"
    echo "Current: '$now' -> $(date -d "@$now")"
    echo "$nowdate: Power interruption detected at $lastdate! $gap exceeds $margin second limit."
    weekofyear=$(date -d "@$last" +%V)
    dayofyear=$(date -d "@$last" +%j)
    day=$(date -d "@$last" +%a)
    date=$(date -d "@$last" +%d)
    month=$(date -d "@$last" +%m)
    year=$(date -d "@$last" +%y)
    hour=$(date -d "@$last" +%H)
    minute=$(date -d "@$last" +%M)
    echo "$last,$weekofyear,$dayofyear,$day,$date,$month,$year,$hour,$minute" >> "$powercsv"
  fi
fi


get() method of Tkinter text widget - doesn't return the last character

Question: I'm writing some GUI program in Tkinter. I'm trying to trace the contents of the Text widget by using Text.get() method.
I heard that I can get(1.0, 'end') to get current contents written on the widget, but it doesn't give the most recent character I typed.
This is a simple example I wrote:
import Tkinter as tk

class TestApp(tk.Text, object):
    def __init__(self, parent = None, *args, **kwargs):
        self.parent = parent
        super(TestApp, self).__init__(parent, *args, **kwargs)

        self.bind('<Key>', self.print_contents)

    def print_contents(self, key):
        contents = self.get(1.0, 'end')
        print '[%s]' % contents.replace('\n', '\\n')

if __name__ == '__main__':
    root = tk.Tk()
    app = TestApp(root, width = 20, height = 5)
    app.pack()
    root.mainloop()

If I type 'abcd', it prints 'abc\n', not 'abcd\n'. ('\n' is automatically added after the last line by the Text widget.)

How can I get 'abcd\n', instead of 'abc\n'?

[Solved]
Thanks to Bryan Oakley and Yasser Elsayed, I solved the problem by replacing
self.bind('<Key>', self.print_contents)

to the following:
self.bind('<KeyRelease>', self.print_contents)

Comment: http://stackoverflow.com/a/11542200/7432
Comment: @BryanOakley Thanks for the link! That post helped me to understand how (...).bind() works in Tkinter.
Answer: This is due to the timing of your event handler, which executes as soon as the event happens, meaning there was no chance for the Text widget to actually get the key typed just yet. You have two options here, either simply append the key parameter you get in the event handler to the Text.get() result, or bind to <KeyRelease-A> for example if you're listening for a specific key (A in this case).


Instrument Switching Question: B flat to Bass Clarinet

Question: I'm writing for a classical style orchestra: flute, oboe, clarinet, bassoon, horn, trumpet, trombone, timpani, strings — two parts each, except timpani and strings.
There is one spot where I think a bass clarinet would fill out the orchestration really nicely, but I don't think I can justify having a bass clarinetist there to play all of four bars, so I was thinking that perhaps the second clarinet could switch to a bass clarinet there.  Is that even remotely reasonable?  If so, how long does the switch time there and back need to be?
Comment: Note that union rules may apply that set the additional amount that must be paid to the clarinetist who doubles on bass for those bars. Still, it's cheaper and more reasonable than hiring a separate bass clarinetist.
Comment: You can also ask any reed player that has played in the pit of a musical for their suggestions.  I've seen guys cover as many as 5 parts.
Comment: Yes, it is perfectly reasonable to have bass cl for four bars.  Be kind and allow time for this.  Maybe 15 seconds would be ample.  Even less would be ok, but it is better to err on the side of caution.
Comment: I assume, your bassoon is already busy? Because its color is quite similar to bass clarinet on the low end of the range.
Comment: @guidot   bassoon sounding like bass clarinet?  Only if one (or both) are terrible musicians!
Comment: Alternatively, you could be "nice" and give the putative full-time bass clarinetist a lot more to play, doubling bassoons or trombones elsewhere.
Answer: Reed and wind players routinely double on other reed and wind instruments, so asking a clarinetist to play a few bars of bass clarinet is fine.
There are a variety of procedural considerations in the switch itself. There's an illuminating blog post and discussion on bretpimentel.com, of which I'll paraphrase the main points.1

Allow no less than 8 seconds; 10 is sufficient.
The bass clarinet can be played by leaving it in its stand and just leaning it to the side, facilitating a faster switch.
A long enough wait before the secondary instrument is used can lead to problems in keeping the reed wet and the instrument in tune. However, doublers experienced with this issues can often mitigate them.

1 See https://bretpimentel.com/about/ for background and credentials.
Comment: Most clarinet players don't have a bass clarinet. A lot of orchestral woodwind players double on another instrument of the same type, but most don't. The only double you can rely on getting is piccolo from a flute player. B-flat/A clarinets don't count as a double.
Answer: It depends on the orchestra. A professional orchestra will have someone who can play the part. In an amateur orchestra the second clarinet player might not even own a bass clarinet. You should ask if bass clarinet is available.
In either case you are likely to annoy the player who has bring and set up the bass clarinet for just four bars, unless these four bars are an important solo. Either give the bass clarinet a substantial part or leave it out.
For the change to and from bass clarinet you should leave no less than five seconds. More is better.


Memory management creating an NSDictionary with NSMutableArrays

Question: I'm having problem understanding memory management when creating a dictionary with mutable arrays. I'm using the ios6 SDK with deployment target 5.1.
In the implementation of the class "Group" the method "namesAndEmails" builds an array "emails" that contains the emails addresses for Person objects with an email. If the Person object does not have an email the Person name is added to another array "namesWithNoEmail". The arrays are returned in a dictionary.
#import "Group.h"
@implementation Group

-(NSDictionary*) namesAndEmails {
    NSMutableArray  *emails = [[NSMutableArray alloc] initWithCapacity:0] ;
    NSMutableArray  *namesWithNoEmail = [[NSMutableArray alloc] initWithCapacity:0];
    NSString *email;
    NSString *name;
    for (Person *p in allPersons) {
        email = p.email;
        name = p.name;
        if ([email length]==0) {
            [namesWithNoEmail addObject:name];
        } else {
            [emails addObject:email];
        }
    }
    NSArray *keys = [NSArray arrayWithObjects:@"emails",@"names", nil];
    NSArray *objects = [NSArray arrayWithObjects:emails, namesWithNoEmail, nil];
    //[emails release];
    //[namesWithNoEmail release];

     return [NSDictionary dictionaryWithObjects:objects forKeys:keys];
}

Somewhere else in the code I wish to send an email to a group of people so I call the emailGroup method which gets a dictionary out by calling "namesAndEmails" on the group.
-(void) emailGroup:(Group*) g {

    NSDictionary *emailInfo = [g namesAndEmails];
    guestsWithNoEmail = [emailInfo objectForKey:@"names"];
    guestEmails = [emailInfo objectForKey:@"emails"];

   int nGuestsWithNoEmail = [guestsWithNoEmail count];

   if (nGuestsWithNoEmail > 0) {
      UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"No emails" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
      [alert show];
   }

    // some more code here

    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
    [picker setSubject:subject];
    [picker setMessageBody:@"" isHTML:NO];
    [picker setToRecipients:guestEmails];
    [[self delegate ] presentModalViewController:picker animated:YES];
    [picker release];
}

As far as I understand [NSDictionary dictionaryWithObjects:objects forKeys:keys] in "namesAndEmails" returns an autoreleased dictionary. But why does my code crash if I release the "emails" and "namesWithNoEmail" arrays? I thought that the dictionary would have ownership of the array after they are added and therefore it would be safe to release the arrays in the method. I guess that's not correct, but why?
Is the a more clean way of doing this? Thank you for any advice!
Comment: I hate to be that guy, but with iOS6 and deploying for 5.1, why would you not use ARC?
Comment: Can you post more details about the crash? Your memory management looks fine. Also, you should use `[email length]` to get the length of an NSString (what is `len()`?).
Comment: @Andrew I get a Thread 1 EXC_BAD_ACCESS when I try to access the arrays in the dictionary. But only when I use the two release lines that are commented out in the code above. len() was python - sorry about that :-)
Comment: @Paul Thanks. Probably I should but right now I just want to understand this problem.
Comment: Can you show us the code where you access the arrays? Like I said, nothing about what you've posted (other than len()) is wrong. Or, is the code in your question the *actual* code you're compiling? len() being there makes me think not. Please copy/paste the real code in question.
Comment: Jacobs, what give you [emails retainCount] at line     //[emails release]; ?
Comment: @MrBonjour The retain count is 2 as I would expect. If I create the return dictionary in a separate line ie NSDictionary *outDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys] the retain count is bumped to 3 and I can release without a crash (the retain count is then decremented to 2 before I return).
Comment: Ok, then maybe it's what you have inside the dictionary who actually do a EXC_BAD_ACCESS signal. Do a simple test: instead of "allPersons", store a simple objet inside (say a [NSNull null]), and watch if there is still bad memory crash. My other theory is [initWithCapacity: 0], if i remember i have already have issue when initializing a container with 0 capacity. Try [initWithCapacity: 1], if my first statement was wrong.
Comment: @MrBonjour [emails addObject:[NSNull null]] and [emails addObject:@"email@example.com"] both give a crash irrespective of whether I initWithCapacity:0 or 1. OK, I must be overlooking something else in my code. Thanks for your help everyone. I'll post an update when I find the problem
Comment: And you're not actually using ARC? If no, do a test: allocAndInit your array, and release it just after, whiteout nothing else instruction. If you have still having problem, i fear that you'll need to make a depth gdb session
Comment: Nope not using ARC. It turns out that I present a UIAlert in certain cases and it is only then that I get the crash. And yes in the post I did remove a lot of code that I didn't think was important such as the UIAlert... Anyway, what solves the problem is making a mutable copy of guestsWithNoEmail and guestEmails. So now that I create these arrays like guestsWithNoEmail = [[emailInfo objectForKey:@"names"] mutableCopy] all is good.
Comment: Thanks for your help by the way! I'm still not sure I understand why making a copy helps...
Comment: Please post the _real_ code: `namesAndEmails` cannot be the real code, as that will not compile!
Comment: @danyowdee No it will not compile. I didn't post the Person class that I use in the loop. Also from the Group class I only posted the namesAndEmails method from the implementation...
Answer: My first suggestion would be to use the "Product->Analyze" feature. If you leaking or over releasing somewhere, it will probably give you the exact chain of events.
Secondly, I can't see the linking between your methods nameAndEmails and emailGroup:. Because I can't see the connection, I can't tell you if the autorelease is causing the problem.
Autoreleased objects get released when the the main run loop cycles. So it's very possible your NSDictionary is getting released. You could test this by doing anything from setting the memory location as a "watch" in the debugger to putting printing something in the console lines each time the runloop your in cycles (I made the assumption your in the main run loop, so correct me if that's not true).
Other things you can do to track the problem would be to use "Zombies" in instruments or NSZombieEnable=YES in your configuration
Comment: Thanks. I'd like to start by printing something to the log when the run loop cycles but I can't figure out how to do that. Any advice?
Comment: Sadly I do not anymore (the way i used to do it wouldn't work now). I was going to try and look it up, but I just haven't had the time.


Retornar valor com XMLHttpRequest

Question:      dataPacket: function(type){
        aTurn.packet = new XMLHttpRequest();
        aTurn.packet.open('GET', 'teste.php', true);
        aTurn.packet.send();

        aTurn.packet.onreadystatechange = function(){
            if(aTurn.packet.readyState == 4 && aTurn.packet.status == 200){
                data = JSON.parse(aTurn.packet.response);
                return data.current;
            }
        }
    },

Estou usando essa função para obter valores de um arquivo json. Porém, quando acionada gostaria que retornasse o valor data, assim como fiz no exemplo, porém retorna undefined, o que posso fazer?
Seria possível usar o parâmetro type de dataPacket() para definir o valor final, por exemplo: dataPacket('teste') retornaria o data.teste.
Answer: Você não pode retornar um valor de uma funçào assincrona, você poderá utilizar uma função de callback ou uma Promise.
Ex callback:
dataPacket: function(type, callback){
        aTurn.packet = new XMLHttpRequest();
        aTurn.packet.open('GET', 'teste.php', true);

        aTurn.packet.onreadystatechange = function(){
            if(aTurn.packet.readyState == 4 && aTurn.packet.status == 200){
                data = JSON.parse(aTurn.packet.response);

                // Chamada do callback
                if( typeof callback == 'function' ) {
                    callback(data);

                    // Ou caso, queira pegar o valor de type
                    callback(data[type])
                }
            }
        }

        aTurn.packet.send();
    },

Chamada
dataPacket('teste', function(resultado){
   console.log(resultado);
})

Comment: Funcionou muito bem amigo, porém acontece conflito com algumas funções que eu estou utlizando. Seria possível retornar um valor chamando a função nesse estilo: aTurn.dataPacket('teste')? Ou algo do tipo que não utilize função no retorno.
Comment: Você pode utilizar uma Promise.  Ex: ` dataPacket: function(type){ return new Promise(function( resolve, reject ) {  `...seu código, no lugar de `callback(data);` vai `resolve(data);` ...resto do código, assim você chamaria  a função da seguinte forma:  `aTurn.dataPacket('teste').then(function(resultado){ //manipulação do resultado })`

[O que é Promise??](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Promise#Exemplos)
Comment: Mas assim continuaria chamando a o resultado com uma função, é isso que quero driblar.
Comment: Se não for possível utilizando XMLHttpRequest seria possível utilizar $.ajax ou $.post? Eu tentei utilizar ajax com o async false, funcionou, porém está em estado deprecated.
Comment: Qualquer uma destas opções não tem um retorno, só por uma função de callback ou Promise mesmo.
Comment: Tudo bem, obrigado.

Retornar valor com XMLHttpRequest


sql group by with left join

Question: fail statement:Error: ORA-00979: not a GROUP BY expression
<code> select org_division.name  , org_department.name , org_surveylog.division_code as divisionCode,org_surveylog.department_code as departmentCode , max(org_surveylog.actiondate) from org_surveylog
left join org_division on (org_surveylog.division_code= org_division.division_code and org_surveylog.SURVEY_NUM= org_division.survey_num)
left join org_department on (org_surveylog.department_code = org_department.department_code and org_surveylog.SURVEY_NUM = org_department.survey_num)
 group by org_surveylog.division_code,org_surveylog.department_code
</code>
but below is ok
<code> select org_surveylog.division_code as divisionCode,org_surveylog.department_code as departmentCode , max(org_surveylog.actiondate) from org_surveylog
left join org_division on (org_surveylog.division_code= org_division.division_code and org_surveylog.SURVEY_NUM= org_division.survey_num)
left join org_department on (org_surveylog.department_code = org_department.department_code and org_surveylog.SURVEY_NUM = org_department.survey_num)
 group by org_surveylog.division_code,org_surveylog.department_code
</code>
how to use group by with left join when i need to show value of  org_division.name  , org_department.name  ?
Answer: You need to change your GROUP BY to
<code> group by   org_division.name ,
            org_department.name
            org_surveylog.division_code,
            org_surveylog.department_code
</code>
From Oracle Select Statements : Select Statement With GROUP BY Clause
<code>SELECT <column_name>, <aggregating_operation>
FROM <table_name>
GROUP BY <column_name>;
</code>
You will notice that you need to include the non aggregated columns in the GROUP BY statement.

sql group by with left join


Queryset object

Question: How to create query set object when work with custom query.
i want to join 5 table. but there is no foreign key defined in all table (its integer field instead of Foreign key)
Example : PersonID is integer field. That store id of user . So now i want to join this both table as no foreign key defined. So how to join this two.
And if we used custom query like
 cursor.connection()
 cursor.execute()

Then its not retrieve query set object . I need query set object in anyhow. So can you please help me out from this issue.
Thanks.
Answer: Use the raw() query:
Person.objects.raw("SELECT * FROM app_person <YOUR JOINS HERE>")

UPDATE: If you want the docts with values instead of model instances then you could use direct SQL instead of QuerySet manipulation.  The recipe is described in the docs:
def dictfetchall(cursor):
    "Returns all rows from a cursor as a dict"
    desc = cursor.description
    return [dict(zip([col[0] for col in desc], row))
           for row in cursor.fetchall()]

cursor = connection.cursor()
cursor.execute("SELECT * FROM app_person <YOUR JOINS HERE>");
values =  dictfetchall(cursor)

Comment: its give me row queryset. I want values that is in Queryset object. Thanks

Queryset object


Não estou conseguindo trabalhar com localStorage

Question: Tenho o seguinte código javascript:
const player1 = "X";
const player2 = "O";
var playTime = player1;
var gameOver = false;
var pontuacaoX = 0;
var pontuacaoO = 0;
var chaveX = 'scoreX';
var chaveO = 'scoreO';
var valAcumuladoX = 0;

atualizaMostrador();
inicializarEspacos();

function atualizaMostrador(){
    if(gameOver) {return;}

    if(playTime == player1) {
        var player = document.querySelectorAll("div#mostrador img")[0];
        player.setAttribute("src", "_img/x.png");
    } else {

        var player = document.querySelectorAll("div#mostrador img")[0];
        player.setAttribute("src", "_img/o.png");
    }
}

function inicializarEspacos(){
    var espacos = document.getElementsByClassName("espaco");
    for(var i = 0; i < espacos.length; i++){

        espacos[i].addEventListener("click", function(){
            if(gameOver) {return;}

            if(this.getElementsByTagName("img").length == 0){
                if(playTime == player1){

                    this.innerHTML = "";
                    this.setAttribute("jogada", player1);
                    playTime = player2;

                } else{

                    this.innerHTML = "";
                    this.setAttribute("jogada", player2);
                    playTime = player1;
                }
                atualizaMostrador();
                verificarVencedor();
            }
        });
    }
}

async function verificarVencedor(){

    var a1 = document.getElementById("a1").getAttribute("jogada");
    var a2 = document.getElementById("a2").getAttribute("jogada");
    var a3 = document.getElementById("a3").getAttribute("jogada");

    var b1 = document.getElementById("b1").getAttribute("jogada");
    var b2 = document.getElementById("b2").getAttribute("jogada");
    var b3 = document.getElementById("b3").getAttribute("jogada");

    var c1 = document.getElementById("c1").getAttribute("jogada");
    var c2 = document.getElementById("c2").getAttribute("jogada");
    var c3 = document.getElementById("c3").getAttribute("jogada");

    var vencedor = "";

    if((a1 == b1 && a1 == c1 && a1 != "") || (a1 == a2 && a1 == a3 && a1 != "") || (a1 == b2 && a1 == c3 && a1 != "")){
        vencedor = a1;
    }else if((b2 == b1 && b2 == b3 && b2 != "") || (b2 == a2 && b2 == c2 && b2 != "") || (b2 == a3 && b2 == c1 && b2 != ""))
    {
        vencedor = b2;
    }else if(((c3 == c2 && c3 == c1) || (c3 == a3 && c3 == b3)) && c3 != "")
    {
        vencedor = c3;
    }

    if(vencedor != ""){
        gameOver = true;

    if(vencedor == "X"){
        pontuacaoX = valAcumuladoX + 1;
        localStorage.setItem(chaveX, pontuacaoX);

    }else {
        pontuacaoO += 1;
        localStorage.setItem(chaveO, pontuacaoO);
    }
        await sleep(50);

    valAcumuladoX = localStorage.getItem(chaveX);

        alert("O Player: '" + vencedor + "' foi o(a) vencedor(a) da partida! \n Player X " + pontuacaoX + " vs " + pontuacaoO + " Player O. Clique em OK! e em \n PLAY

AGAIN para jogar novamente!");

    document.getElementById('butao').style.display = "block";

    } else if(a1 != '' && a2 != '' && a3 != '' && b1 != '' && b2 != '' && b3 != '' && c1 != '' && c2 != '' && c3 != ''){

    await sleep(50);

    alert("Velha!");

    document.getElementById('butao').style.display = "block";

      }
}

function sleep(ms){
    return new Promise(resolve => setTimeout(resolve, ms));
}
/*
var resultadoScore = localStorage.getItem(chaveX);
alert(resultadoScore);
*/

Estou tentando guardar a pontuação de player1, que é o jogador X no caso. Após o play again eu não queria perder esse valor, por isso eu estive tentando utilizar sem sucesso algum o localStorage.
P.S.: não mandei o código HTML e o CSS, pois não sei se tem como carregar as imagens que estou utilizando.
Comment: E qual o problema? Dá algum erro? Já checou a compatibilidade com o navegador? [compatibilidade localstorage](https://developer.mozilla.org/pt-BR/docs/Web/API/Window/Window.localStorage#Navegadores_compat%C3%ADveis)
Comment: Experimente adicionar/imprimir esta linha no seu código `"localStorage" in window`. Ela vai verificar se o seu browser tem compatibilidade com `localstorage`. Caso seja verdadeiro, experimente a seguir `window.localStorage` para ver todo o conteudo do `localStorage`
Comment: @RicardoPontual não aparece erro nenhum no console, o problema é que eu quero guardar o ponto do jogador e ir atribuindo + 1 ponto toda vez que esse jogador mesmo jogador ganhar. Ai no exemplo eu estou tentando implementar a lógica para o player1(jogador X), depois aplicarei a mesma lógica na outra condição(else if), do player2(jogador O). Já testei no Chrome e Firefox.
Comment: @lazyFox vou tentar aqui
Comment: Prezado, vc disse que não mostra nenhum erro, então qual seria o valor mostrado quando vc chama o localStorage?
Comment: @sam Application: Key=scoreX, Value=1
Comment: Então o LS está funcionando. O que não estaria funcionando?
Comment: @sam cada vez que o `player1` ganhar ele deveria somar +1 ponto. Ex: ganhou três vezes consecutivas, `pontuacaoX` deveria ser exibida no `alert(pontuacaoX) // 3`
Answer: Para trabalhar com localStorage (LS) você precisa fazer duas coisas:

Verificar se ele existe e atribuir o valor à variável que irá usá-lo sempre que a página for recarregada ou durante o processo.
Como o valor do LS é uma string, para realizar somas é preciso converter para tipo number, onde você pode usar parseInt(). Senão irá apenas concatenar, em vez de somar.

No seu caso, a variável valAcumuladoX deverá usar o valor guardado no LS
// atribuo o valor do LS a uma variável:
var LS_x = localStorage.getItem('scoreX');

// uso um operador curto para atribuir o valor a variável
// se LS_x for verdadeiro, o valor será o guardado no LS,
// caso contrário, será 0
var valAcumuladoX = LS_x || 0;

E onde você irá somar +1, use o parseInt():
pontuacaoX = parseInt(valAcumuladoX) + 1;

Então, o código todo deveria ficar assim:
const player1 = "X";
const player2 = "O";
var playTime = player1;
var gameOver = false;
var pontuacaoX = 0;
var pontuacaoO = 0;
var chaveX = 'scoreX';
var chaveO = 'scoreO';

var LS_x = localStorage.getItem('scoreX');
var valAcumuladoX = LS_x || 0;

atualizaMostrador();
inicializarEspacos();

function atualizaMostrador(){
    if(gameOver) {return;}

    if(playTime == player1) {
        var player = document.querySelectorAll("div#mostrador img")[0];
        player.setAttribute("src", "_img/x.png");
    } else {

        var player = document.querySelectorAll("div#mostrador img")[0];
        player.setAttribute("src", "_img/o.png");
    }
}

function inicializarEspacos(){
    var espacos = document.getElementsByClassName("espaco");
    for(var i = 0; i < espacos.length; i++){

        espacos[i].addEventListener("click", function(){
            if(gameOver) {return;}

            if(this.getElementsByTagName("img").length == 0){
                if(playTime == player1){

                    this.innerHTML = "";
                    this.setAttribute("jogada", player1);
                    playTime = player2;

                } else{

                    this.innerHTML = "";
                    this.setAttribute("jogada", player2);
                    playTime = player1;
                }
                atualizaMostrador();
                verificarVencedor();
            }
        });
    }
}

async function verificarVencedor(){

    var a1 = document.getElementById("a1").getAttribute("jogada");
    var a2 = document.getElementById("a2").getAttribute("jogada");
    var a3 = document.getElementById("a3").getAttribute("jogada");

    var b1 = document.getElementById("b1").getAttribute("jogada");
    var b2 = document.getElementById("b2").getAttribute("jogada");
    var b3 = document.getElementById("b3").getAttribute("jogada");

    var c1 = document.getElementById("c1").getAttribute("jogada");
    var c2 = document.getElementById("c2").getAttribute("jogada");
    var c3 = document.getElementById("c3").getAttribute("jogada");

    var vencedor = "";

    if((a1 == b1 && a1 == c1 && a1 != "") || (a1 == a2 && a1 == a3 && a1 != "") || (a1 == b2 && a1 == c3 && a1 != "")){
        vencedor = a1;
    }else if((b2 == b1 && b2 == b3 && b2 != "") || (b2 == a2 && b2 == c2 && b2 != "") || (b2 == a3 && b2 == c1 && b2 != ""))
    {
        vencedor = b2;
    }else if(((c3 == c2 && c3 == c1) || (c3 == a3 && c3 == b3)) && c3 != "")
    {
        vencedor = c3;
    }

    if(vencedor != ""){
        gameOver = true;

    if(vencedor == "X"){
        pontuacaoX = parseInt(valAcumuladoX) + 1;
        localStorage.setItem(chaveX, pontuacaoX);

    }else {
        pontuacaoO += 1;
        localStorage.setItem(chaveO, pontuacaoO);
    }
        await sleep(50);

    valAcumuladoX = localStorage.getItem(chaveX);

        alert("O Player: '" + vencedor + "' foi o(a) vencedor(a) da partida! \n Player X " + pontuacaoX + " vs " + pontuacaoO + " Player O. Clique em OK! e em \n PLAY

AGAIN para jogar novamente!");

    document.getElementById('butao').style.display = "block";

    } else if(a1 != '' && a2 != '' && a3 != '' && b1 != '' && b2 != '' && b3 != '' && c1 != '' && c2 != '' && c3 != ''){

    await sleep(50);

    alert("Velha!");

    document.getElementById('butao').style.display = "block";

      }
}

function sleep(ms){
    return new Promise(resolve => setTimeout(resolve, ms));
}
/*
var resultadoScore = localStorage.getItem(chaveX);
alert(resultadoScore);
*/

Comment: veja se eu entendi. Aqui `var valAcumuladoX = LS_x || 0;` eu estou verificando se o _localStorage_ existe, certo? como já obtive ele logo acima aqui `var LS_x = localStorage.getItem('scoreX');` ele será verdadeiro e então `valAcumuladoX` receberá a _Key_, cujo a mesma me possibilita acessar os pontos guardados, tipo uma _query_ no bd isso? outra coisa, essa verificação se dá apenas no início, ou todo novo jogo ela é realizada, acredito ser a segunda, mas não tenho certeza e acho que falei merda acima, o acesso é dado através da _key chaveX_ correto?
Comment: O valor ficará guardado no navegador mesmo que vc feche ele. `var valAcumuladoX = LS_x || 0;` verifica se ele existe, se não existe, será 0.
Answer: Eu fiz funcionar, dá uma olhada no código abaixo:
Note que alterei para popular campos input, mas apenas para testar.
A pontuação de X é gravada corretamente através do código localStorage.setItem(chaveX, pontuacaoX) estava sendo guardada, só não estava sendo usada através da variável valAcumuladoX.

<!DOCTYPE html>

  0 x 0

  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="a1">
  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="a2">
  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="a3">

  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="b1">
  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="b2">
  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="b3">

  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="c1">
  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="c2">
  <input class="espaco" size="2" value="" onclick="javascript:clicou(this);" type="text" id="c3">

  <input id="butao" type="button" value="PLAY AGAIN" onclick="javascript:this.style.display='none';zeracampos();" style="display: none;">

Comment: não consegui entender a sua linha de raciocínio. pontuacaoX recebe valAcumuladoX.
Comment: Erro meu ali na minha mensagem, troco o texto assim que descobrir a resposta, ok?
Estou testando seu código, em breve retorno.
Comment: @LuckasFujimoto gostaria de perguntar se testou meu exemplo depois que alterei minha resposta, se sim e ficou correto, poderia alterar seu voto para positivo?


Seeking origin of variance equation

Question: In my data science textbook, it says that the variance of a variable $Y$ can be written as:
$v_y = \frac{1}{n-1} \sum_{k=1}^{n} y_k^{T} y_k$,
I have never seen variance defined like this before. Could someone provide some insights into this definition (i.e., why it is valid to define variance like this?)
Comment: This is the formula for [sample covariance](https://en.wikipedia.org/wiki/Sample_mean_and_covariance)
Comment: it's the same as the usual formula but it assumes that the mean of $y_{k} = 0$.
Answer: I think, a couple of things should be noted here:
1) This equation resembles $E[X^2]$, and it resembles the variance only if $E[X]$ is zero, since $var(X)=E[X^2]-E[X]^2$.
2) It assumes that the $y_k$'s are row vectors. So, $y_k^Ty_k$ will a matrix of $d\times d$, where $d$ is the dimension of each sample. So, we're averaging $d \times d $ matrices here, as in @Francis's sample covariance link (which assumes $y_k$'s as column vectors).
3) What you get out of this equation is a covariance matrix estimate, with entries $C_{rm}=cov(y^{r}, y^{m})$, where $y^{i}$ represents the $i$-th element of a random vector $y$.
4) $\frac{1}{n-1}$, instead of $\frac{1}{n}$ comes from unbiased estimation of sample covariance.

Seeking origin of variance equation


OpenBSD pf port forwarding multiple rules

Question: I have a few dozen servers behind OpenBSD firewall with port forwarding. Most rules are very similar and differ only in IPs or sometimes in ports forwarded, so I want to compact them to remove excessive repetition but I've found that it is impossible to use tables with rdr-to rules. Is there any way to improve this configuration? May be there is option to use pf macros to generate multiple rules at once? I can't use external preprocessor at the moment.
Example set of rules:
pass in  on $extif proto tcp from any     to 10.0.0.213   port {25,80,443} rdr-to 172.16.1.193
pass in  on $intif proto tcp from $intnet to 10.0.0.213   port {25,80,443} rdr-to 172.16.1.193
pass out on $intif proto tcp from any     to 172.16.1.193 port {25,80,443} received-on $intif nat-to $intif

pass in  on $extif proto tcp from any     to 10.0.0.214   port {25,80,443} rdr-to 172.16.1.194
pass in  on $intif proto tcp from $intnet to 10.0.0.214   port {25,80,443} rdr-to 172.16.1.194
pass out on $intif proto tcp from any     to 172.16.1.194 port {25,80,443} received-on $intif nat-to $intif

pass in  on $extif proto tcp from any     to 10.0.0.215   port {25,80,443,3389} rdr-to 172.16.1.195
pass in  on $intif proto tcp from $intnet to 10.0.0.215   port {25,80,443,3389} rdr-to 172.16.1.195
pass out on $intif proto tcp from any     to 172.16.1.195 port {25,80,443,3389} received-on $intif nat-to $intif

Answer: From the pf.conf(5) manpage:

Translation options apply only to packets that pass through the
  specified interface, and if no interface is specified, translation is
  applied to packets on all interfaces.  For instance, redirecting port
  80 on an external interface to an internal web server will only work
  for connections originating from the outside.  Connections to the
  address of the external interface from local hosts will not be
  redirected, since such packets do not actually pass through the
  external interface. Redirections cannot reflect packets back through
  the interface they arrive on, they can only be redirected to hosts
  connected to different interfaces or to the firewall itself.

You might be able to condense some of your rules by not specifying which interface you want the re-direction to take place on and allow pf to evaluate it for you.
For example:
pass in on $extif proto tcp from any to 10.0.0.213 port {25,80,443} rdr-to 172.16.1.193
pass in on $intif proto tcp from $intnet to 10.0.0.213 port {25,80,443} rdr-to 172.16.1.193

Could be re-written as:
pass in proto tcp from any to 10.0.0.213 port {25, 80, 443} rdr-to 172.16.1.193

Inbound traffic destined for 10.0.0.213 on $extif will be redirected to 172.16.1.193.
Inbound traffic destined for 10.0.0.213 on $intif will be redirected to 172.16.1.193.
This will also allow traffic that is not part of $intnet to happily be redirected as well. This may or may not desirable.

Without seeing your entire ruleset or really knowing what you're trying to accomplish I can only offer a proof-of-concept example.
One final note: I would really avoid doing this. There is a tendency (at least I have it) to want to write the fewest rules possible by having one rule do more than "one thing". This is bad. Firewalls are already frightfully complicated and seemly always misconfigured; why make it harder on yourself by crafting a byzantine ruleset? A longer ruleset with simpler rules will be easier to understand, maintenance and debug. Avoid the temptation to be overly clever.
Comment: Thanks for answer, it gave me very useful ideas. First, I released that I'm already allowing only traffic from `$intnet` on `$intif` interface by ingress rules, so I can drop this restriction from `rdr-to` rules. Second - it is possible to use *list* for interfaces too and write something like `pass in on { $extinf, $intif }` for `rdr-to` rules without need to relax restrictions.


How to get Serial Number (processor tray) with Cocoa

Question: By typing : system_profiler SPHardwareDataType | grep 'Serial Number'
I get 2 serial numbers.
The first ("Serial Number (system)") can be put in NSString by :
(NSString *)IORegistryEntryCreateCFProperty(IORegistryEntryFromPath(kIOMasterPortDefault, "IOService:/"), CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)

and I didn't find how I can get the second : Serial Number (processor tray)
Any ideas?
Thank you
Answer: In a more elegant way :)
#import <Foundation/Foundation.h>

int main()
{
    CFTypeRef aCFProperty;

    if ((aCFProperty = IORegistryEntryCreateCFProperty(IORegistryEntryFromPath(kIOMasterPortDefault, "IOService:/"), CFSTR("processor-memory-board-serial-number"), kCFAllocatorDefault, 0)) != NULL )
    {
        NSLog(@"Processor tray Serial Number : %@", aCFProperty);
        CFRelease(aCFProperty);
    }

    return 1;
}

Then : clang SnTray.m -framework IOKit -framework Foundation -o SnTray.o
Then ./SnTray.o
i cant do more :)
Answer: Answer:
(NSString *)IORegistryEntryCreateCFProperty(IORegistryEntryFromPath(kIOMasterPortDefault, "IOService:/"), CFSTR("processor-memory-board-serial-number"), kCFAllocatorDefault, 0);


how do i use reader in c# with mysql?

Question: I have a remote mysql db and want to use the reader to display a single data inside a row with the id xx? i do have a functionally select which writes me all the data into a datagrid, but that is not what I want. I want to display a specific entry from a row into a label.
this is what I have

private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                string MyConnection2 = "datasource=220.127.116.11;port=3306;username=*****;password=*******";
                //Display query
                string Query = "select * from *database*.*datatable*;";
                MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
                MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
                //  MyConn2.Open();
                //For offline connection we weill use  MySqlDataAdapter class.
                MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
                MyAdapter.SelectCommand = MyCommand2;
                DataTable dTable = new DataTable();
                MyAdapter.Fill(dTable);
                dataGridView1.DataSource = dTable; // here i have assign dTable object to the  dataGridView1 object to display data.
                MyConn2.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

can someone explain me how to use this sniplet to display a specific data aentry into a label?
I tried to use a reader section of a different code but this did not work and dont want to mix up different mysql connection aproach because it looks messy
Comment: Wouldn't `label.Text = dTable.Rows[0][1].ToString();` work? Where this would show from the first row the second field.
Comment: please refer to: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-manipulate-columns-in-the-windows-forms-datagridview-control?view=netframeworkdesktop-4.8
Comment: You need a binding source.  In following example a textbox in bind to the reader : https://www.vbforums.com/showthread.php?887313-Binding-a-Data-Reader-in-Windows-Forms
Comment: problem is solved. thank you.
Comment: seeing "button_click" and "new MySqlConnection" in the same method....means you do not have a fundamental understanding of "layers". Please see https://learn.microsoft.com/en-us/aspnet/web-forms/overview/data-access/introduction/ or internet-search "c# layers"
Answer: To display a specific entry from a row in a label, you can modify your existing code by adding a WHERE clause to your SQL query.
string MyConnection2 = "datasource=18.104.22.168;port=3306;username=*****;password=*******";
string Query = "SELECT column_name FROM database.table_name WHERE id = xx;";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);

try
{
    MyConn2.Open();
    string result = MyCommand2.ExecuteScalar().ToString();
    label1.Text = result;
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
finally
{
    MyConn2.Close();
}

Comment: i have already solved this problem with the help of an answer to this. however i have further questions but can not post new questions anymore and i have no idea why. i am being blocked. however, thank you all for your generous help. i really aprechiate it.

how do i use reader in c# with mysql?


JQuery check if the inout is required or not

Question: In my HTML template, I have required set to False for a specific input.

    <input type="text" required="false" class="product-data form-control" id="description" placeholder="Description" name="description"/>

I want to print the value of required in JQuery.
console.log("Value - " + $(this).attr("required"));

Output :

Value - required

I want it to print false. Is there any way to do this.
Answer: Try to use getAttribute() :
document.getElementById('description').getAttribute('required')

Hope this helps.

console.log("Value - " + document.getElementById('description').getAttribute('required'));

    <input type="text" required="false" class="product-data form-control" id="description" placeholder="Description" name="description"/>

Comment: No, it return `true`
Comment: Checking length. Doesn't make sense. Also prop doesn;t work.
Answer: The required attribute specifies that the input field is required, It doesn't matter what you have specified as its value. if you want to store arbitrary data then use data-* prefixed custom attribute.

console.log("Value - " + $('#description').prop("required"));

  <input type="text" required id="description" />

Answer: You can use javascript Element.getAttribute() to get value of target attribute.

var attr = $("input")[0].getAttribute("required");
console.log("Value - " + attr);

    <input type="text" required="false" class="product-data form-control" id="description" placeholder="Description" name="description"/>

Comment: There can be multiple inputs. So $("input")[0] does't make sense.
Comment: @Pattu You want to print attribute value of multiple in console?
Comment: No just that input[0] might not be description.
Comment: @Pattu ZakariaAcharki posted my answer and you marked it. So what is differece between `getElementById()` and `$("input")[0]` that both return one element?


"GET /assets/)!==t&&(e.html(e.data( HTTP/1.1" 200 3538 "-" "Java/1.7.0_25"

Question: I'm seeing GET requests like:
<code>"GET /assets/)!==t&&(e.html(e.data( HTTP/1.1" 200 3538 "-" "Java/1.7.0_25"
</code>
in my logs for a box hosting a Rails app. Looks suspiciously like someone probing the app but can't be sure.
Any suggestions?
Answer: Almost certainly a bot probing for exploits. That code looks to be part of a few generic Javascript unpackers. My guess is that they're looking for an XSS exploit that they can pile packed JS into for whatever purpose.
Check to make sure the exploits don't work (because you're safely escaping all user supplied content displayed on the page) and you can safely ignore them.


A conjecture in equational logic

Question: In an algebra with a single binary operation g, is there a single equational identity that generates the same set of identities as the set {g(x,y)=g(y,x) , g(g(x,y),z)=g(x,g(y,z))}? My conjecture is that there isn't.
Answer: I use multiplicative notation for the operation, i.e., I write $xy$ instead of $g(x,y)$.
In the language of one binary operation, there is no single identity which is equivalent to the conjunction of the associative and commutative laws.
Case I. Each side of the supposed identity contains at least two multiplications, i.e., the identity is of the form $(t_1t_2)t_3=(t_4t_5)t_6$ or $(t_1t_2)t_3=t_4(t_5t_6)$ or $t_1(t_2t_3)=t_4(t_5t_6)$ for some terms $t_1,t_2,t_3,t_4,t_5,t_6$.
The commutative law is not a consequence of such an identity, or even the set of all such identities. To see this, consider the $4$-element structure $\{a,b,c,d\}$ with multiplication defined so that $ab=c$, while $xy=d$ whenever $x\ne a$ or $y\ne b$. In this structure $ab\ne ba$, while both sides of all the identities under consideration evaluate to $d$.
Case II. One side of the supposed identity contains at most one multiplication, i.e., the identity is of the form $xy=t$ or $xx=t$ or $x=t$ for some term $t$.
We may assume that the identity is a consequence of the associative and commutative laws, and so it holds in the structure $(\mathbb Z,+)$. Therefore, each variable occurs the same number of times on either side of the equality sign. This leaves us with the identities $xy=yx$,$\ xy=xy$,$\ xx=xx$, and $x=x$, none of which implies the associative law. Namely, the $2$-element structure $\{a,b\}$, where $aa=b$ and $ab=ba=bb=a$, is commutative but not associative; in fact, for any $x\in\{a,b\}$, we have
$$(ax)b=b(xa)=a,$$
$$a(xb)=(bx)a=b.$$
This is the unique (up to isomorphism) binary operation on a $2$-element set which is commutative but not associative; it can be interpreted as either of the truth-functions NOR or NAND.

A conjecture in equational logic


What is this time signature?

Question: I am working through an exercise which has me determining the time signature of measures, and I'm stumped on this one:

In determining the value of the septuplet, I need to first determine whether the answer will be in compound time or simple time, based on this page where it was defined:

This is in the section titled Hybrid Meters, where we were introduced to
the hybrid duple times 5/2, 5/4, 5/8, and 5/16,
the hybrid triple times 7/2, 7/4, 7/8, 7/16
and the hybrid quadruple times which can be formed by taking the upper number to be 9,10, or 11, and the lower number to be 2, 4, 8, or 16.
Now I'm guessing there are infinitely many more possibilities, but these are the only ones we've covered so far, and my question is: am I wrong to say that it is impossible to classify this measure as one of the time signatures listed above, using one of the interpretations of septuplets' values stated in the second image?
Comment: Only glancing right now, so I don't feel sure enough to provide an answer, but I think I disagree with the definition of septuplets in that second image. By my understanding, a septuplet in simple time takes the place of 4 sixteenths as shown, but would take the place of *six* sixteenths in compound time, not three. At any rate, I think you're *technically* correct that you can't 100% guess the difference between this being a relatively normal 9/8 or a relatively abnormal 8/8 (3+2+3 subdivision), but the former seems far more likely absent further evidence. Has 8/8 been discussed?
Comment: @PatMuchmore This is entirely right. It is far more likely that the septuplet takes the space of *six* notes than four. Consider converting this to an answer.
Comment: I agree with Pat and Kilian here - since the measure's beaming (and therefore metric subdivision) implies compound meter, if the septuplet *did not* occur within the same metrical grouping, it would need to be specified with a ratio (e.g. 7:4)
Comment: 8/8 hasn't been discussed yet.  I'm going to take the answer to be 9/8 by treating the septuplets as 7:6.  Thanks so much for clarifying!  This one threw me for a loop.
Answer: I disagree with the definition of septuplets in that second image. By my understanding, a septuplet in simple time takes the place of 4 sixteenths as shown, but would take the place of six sixteenths in compound time, not three. At any rate, the beaming together of three eighth notes after the septuplet and the dotted-quarter before makes it clear that this septuplet comes between two compound beats. I think you're technically correct that you can't 100% guess the difference between this being a relatively normal 9/8 or a relatively abnormal 8/8 (3+2+3 subdivision), but the former seems far more likely absent further evidence. As a hybridization of 4/4 time, it seems possible that 8/8 has come up in the book, but it isn't in the list you've provided.
Comment: @Greg I wouldn't be surprised if your interpretation is the one the author intended.  But I agree the book is not as great as I thought it was.  It depends heavily on the teacher to not just elaborate on topics, but to *clarify actual problematic ambiguities* which frequently arise.  The exercises are great, but I would not recommend this book to someone for independent study.
Comment: Yes, I'd agree -- my "internal" rule, which I am pretty sure is correct, is that a triplet/quintuplet/septuplet, etc. takes up the time that a standard group of notes of the  same beaming would take to fill one beat.    <-- that's probably incomprehensible to anyone but me :-)
Comment: OK, I'll disagree with @PatMuchmore's disagreement :-)  Caveat, that I've played a lot of strange rhythms in musical theater, but don't have a strong theoretical background.

I would play this as the septuplet takes a single eighth note.  Wouldn't a 16th note Triplet take the space of a single eighth in compound time?  That would make the example 7/8 time.

And.. I think the examples in the text are poorly written.
Comment: @PatMuchmore thanks for the answer!  I was careful to list every time signature that has come up.
Comment: Actually, I'd say 7:4 **or 7:8** in simple time, and 7:6 for compound time.
Answer: The book's definition of a 7-tet is misleading. OK - more than misleading, when stated as a 'rule' it's plain wrong!  That's a '7 in the time of 6' tuplet.   So the 'hybrid' idea isn't required. It's a straightforward compound-triple 9/8.
(And it's the first time I've heard of 'hybrid' meters.  Not a bad concept, but don't assume anyone else will know what you're talking about!)
In the contest of a theory exercise, there's room for confusion.  In real music, which WILL have a time signature, it should be clear.  Though a '7:8' notation rather than just plain '7' might have been helpful.
Comment: 'Complex' perhaps.  I don't see how, foir instance, a consistent 3+2 5/8 could be called 'irregular'.
Comment: Yeah the term seems to only be used in my book.  Other places seem to call them complex or irregular time signatures.  Is this correct?
Comment: I learned it as "hybrid" meters as well, but my book also called it mixed meters.
Answer: The correct time signature...
...is 9/8.
But it's hard to figure out, because...
...the book is almost entirely wrong in defining tuplets.
Here is a better way to think about tuplets
Tuplets are always relative to the "next higher" note value within the time signature.

For simple time that means the "usual" binary relationships: whole note, half note, quarter note, eighth note, etc.

For compound time tuplets are relative to dotted half notes, dotted quarter notes, eighth notes, sixteenth notes, etc.

A look at sixteenth-note tuplets
In simple time

1 regular sixteenth = 1/4 beat
2 regular or 3-tuplet sixteenths = 1/2 beat
4 regular or 5-to-7-tuplet sixteenths = 1 beat
8 regular or 9-to-15-tuplet sixteenths = 2 beats

For x=0 to n, 2x to 2x-1 sixteenths = (2x)/4 beats = 2x-2 beats.
In compound time
Taking the eighth note as the basic pulse. (Equivalents based on the dotted quarter "large pulse" are given in parentheses.)

1 regular sixteenth = 1/2 beat (= 1/6 of a dotted quarter)
2 regular or 3-tuplet sixteenths = 1 beat (= 1/3 of a dotted quarter)
4-to-7-tuplet sixteenths = 3 beats (= 1 dotted quarter)
8-to-15-tuplet sixteenths = 6 beats (= 1 dotted half)

Note that the relationships aren't quite as consistent as in simple time, because the subdivisions of the beat are 3-based down to the eighth note but 2-based beyond that.

What is this time signature?


Save conditional split to variable

Question: I have a data flow in VS2019 that calls a list via REST than does some filtering and returns a single data point (A date formatted as string).
Is it possible to update a variable with that string? And if so how?
I tired Script Component, but couldn't find any good documentation on how to set it up.
Answer: In my case I have a combination of Conditional Split, Sort, and Aggregation that left me with one row/column. And all i needed was to assign that one row dynamically to a global variable.

Step 1 was to create a blank global variable, in my case a string.
Set source, filters and destination

Edit... the Script Component
Script Tab: select your variable as the ReadWriteVariable.
Input Columns Tab: Check the column you want to save as variable
Click the Edit Script... button
Declare a temporary variable within the ScriptMain class
Assign the row return to that variable under Input0_ProcessInputRow(Input0Buffer Row)
Set your global variable to the temp variable.

Save and close the second window.

Your row should now be save to the variable and can be used within any other step throughout the entire project.

Save conditional split to variable


Uploads de arquivos via ajax

Question: Como posso fazer vários uploads, ou seja, tenho uma tela com vários input do tipo file, como faço para passar isso via Ajax para o meu servidor?
Já tentei com XmlHttpRequest, porém, não deu certo, daria se tivesse um input com att multiple, mas não é o caso.
Obs: Estou fazendo aplicação com ASP.NET MVC
Comment: possível duplicata de [Múltiplos uploads via ajax](http://pt.stackoverflow.com/q/23204/7210)
Comment: Pergunta duplicada, favor utilizar as mesmas perguntas já criadas por você mesmo.
Comment: @Macalister26 e ai deu certo pra ti?
Answer: Já tentou usar o UpdatePanel?
Neste link tem um exemplo bem completo: http://www.codeproject.com/Articles/482800/FileplusUploadplusinplusUpdateplusPanel
Basicamente seria um código assim:
 <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                <ContentTemplate>
                    <asp:FileUpload ID="fileUploadImage" runat="server"></asp:FileUpload>
                    <asp:Button ID="btnUpload" runat="server" Text="Upload Image" OnClick="btnUpload_Click" />

                    <asp:Button ID="btnProcessData" runat="server" Text="Process Data" OnClick="btnProcessData_Click" />

                    <asp:Label ID="lblMessage" runat="server" Text="Image uploaded successfully." Visible="false"></asp:Label>

                    <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
                        <ProgressTemplate>
                            Please wait image is getting uploaded....
                        </ProgressTemplate>
                    </asp:UpdateProgress>

                    Please view the below image uploaded

                    <asp:Image ID="img" runat="server" Width="100" Height="100" ImageAlign="Middle" />
                </ContentTemplate>
    </asp:UpdatePanel>

Answer: Exemplo com MVC ASP.NET
Cshtml
@{ Layout = null; }
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>PostFiles</title>

        <form action="" method="post" enctype="multipart/form-data" onsubmit="return false;">

<input type="file" name="file1" id="file1">

<input type="file" name="file2" id="file2">

<input type="file" name="file3" id="file3">

<input type="file" name="file4" id="file4">

<input type="file" name="file5" id="file5">

            <button type="button" onclick="uploadfile();">Enviar</button>
        </form>

Código do Controler:
[HttpGet]
public ActionResult PostFiles()
{
    return View();
}

[HttpPost]
public JsonResult PostFiles(FormCollection form)
{
    HttpFileCollectionBase files = Request.Files;
    foreach (String file in files)
    {
        Request.Files[file].SaveAs(Server.MapPath("~/Arquivos/") + Request.Files[file].FileName);
    }
    return Json(new { status = true });
}

Comment: Obrigado deu certo...

Uploads de arquivos via ajax


How can you make Xcode give an audio alert when the your code is finished running?

Question: I have a source code that takes 2-3 minutes to compile/run. Is there anyway that I can make Xcode beep or give any form of an audio signal?
I don't want to modify my source code. I just want Xcode to give me an audio notification.
Answer:
Xcode > Preferences > Behaviors
Comment: I get the behavior you want by enabling "Generates output" in "Running": it beeps when the app runs and is attached to the debugger.
Comment: This works. But I assume it notifies upon *building* is finished. I was looking for something that would beep after *running* & *attaching*. Is that doable?
Comment: Oh never mind. I should just use the `Running` box from your image
Comment: Weird... I used all 3, build-succeeds & running-starts & running-completes and assuming that running complete would be the last. But instead running-complete happens first...when I hit the stop button OR exactly when I click the run/play button as if it means when the app is terminated, not finished its running. What does finished running mean?!?
Comment: I was about to say that. :) But another question. What exactly does 'generates output' mean? It confuses me about the diff between compiling, running. I mean what does it mean for `running` to have a start and then also a generate output. If there is such a distinction, I would have thought that the *start* of `running` would overlap with the `build`/`compile`. (sorry if we deviated from the original question). FYI I read [this](http://stackoverflow.com/questions/846103/runtime-vs-compile-time) question before and just read it again...
Comment: I guess that "generates output" means "the app is active and attached" (meaning, it is able to output to the debugger). I agree it's not very clear.
Comment: It actually means that something was printed/logged to the debugger. Meaning your app can be on for 5 minute and log nothing, so no sound is triggered. The moment that you log something then it will make a sound. I assume someone can use to this to be notified only upon logs.


Tag Form fecha sozinha

Question: Quando envio esse código html via ajax ele exibe corretamente, porém fecha a tag Form logo após a abertura da mesma, existe outra forma de fazer isso? ou há algum erro de sintaxe.
$FormUserCad = '

<form action="oi.php" method="post">

Nome:

<input name="nome" type="text">

Idade:

<input type="text">

Rua:

<input type="text">

...
</form> <--

$retorno = array('codigo' => 0, 'mensagem' => $FormUserCad);
            echo json_encode($retorno);
            exit();

Comment: Todo elemento HTML que é aberto será fechado pelo navegador, independente se você fechou corretamente ou não, o navegador constrói um término a partir do último elemento fechado corretamente. E sim, é um erro de sintaxe deixar seu html com a tag aberta. Inclusive ele também toma a liberdade de mover seu elemento de lugar, como por exemplo, se você colocar um script src, abaixo do navegador, fora do body, ele irá corrigir, colocando-o dentro do body.
Comment: Mas se você abre um `form`, ele tem que ser fechado mesmo pela lógica, senão seu formulário não funcionará. Não entendi sua dúvida.
Comment: ele fecha sozinho, exemplo  não ao final do código como desejado, e ele retira o  do final do código
Answer: Ajuste seu html para a forma correta da estrutura html. E depois tente usar o htmlspecialchars
$FormUserCad = '

       <form action="oi.php" method="post">

Nome:

<input name="nome" type="text">

Idade:

<input type="text">

Rua:

<input type="text">

        ...

       </form>

';

    $retorno = array('codigo' => 0, 'mensagem' => htmlspecialchars($FormUserCad,ENT_QUOTES));
    echo json_encode($retorno);
    exit();

Tag Form fecha sozinha


SQL query to find the last day of a particular formatted month - YYYY/MM

Question: I have months in the following format -
2022  /  12
2021  /  03
2020  /  02

YYYY  /  MM

I want to find out the last day of these months. i.e. 2022/12/31, 2021/03/31 , 2020/02/28
I am using the below code -
to_date(to_char(:p_month||'01/', 'yyyy / mm/dd'), 'yyyymmdd')

but it is throwing an invalid format error.
Comment: Why should he do such crazy things instead of just using the LAST_DAY function?
Comment: 30 days have September, April. June. and November. All the rest have 31 days excepting February which is 28 days long and 29 days in a leap year.  You could probably use that as part of the solution.

Another way would be to take the first day of the month following as a date and substract one day.
Comment: I think you have `to_date` and `to_char` switched around. Then as @JonasMetzler says, `last_day` gives you the last day of the month that a date falls in, so you don't need any `dd`.
Answer: There are following steps you need to take in order to get your desired result:

Remove the whitespaces within your string
Cast your string to a date
Select the last day of the month for this date.

There is likely more than one way to do this. As example you can do following:
1st part: SELECT REPLACE(datepart,' ','') FROM yourtable; to remove whitespaces...
2nd part: SELECT TO_DATE(REPLACE(datepart,' ',''),'YYYY/MM') FROM yourtable; to cast your column as date and...
3rd part: SELECT LAST_DAY (TO_DATE(REPLACE(datepart,' ',''),'YYYY/MM')) FROM yourtable; to get the last day of the month for this date.
Please see the working example here: db<>fiddle
Answer: First you need to convert the input string to a date - so the first function you apply should be to_date (you have the two conversions in the wrong order in your attempt). Oracle is tolerant of unneeded spaces in the input string; and to_date accepts incomplete formats, supplying defaults for the missing components.
So, to_date(:p_month, 'yyyy/mm') will return the first day of the month (that's the default: dd = 1, as well as hh24:mi:ss = 00:00:00).
Then you can apply last_day to this result, and if needed, convert back to a string using to_char. Like this:
    to_char(last_day(to_date(:p_month, 'yyyy/mm')), 'yyyymmdd')

Testing it:
variable p_month varchar2(10)
exec :p_month := '2022 / 03'

select :p_month as mth,
       to_char(last_day(to_date(:p_month, 'yyyy/mm')), 'yyyymmdd') as last_day
from   dual;

MTH        LAST_DAY
---------- --------
2022 / 03  20220331

By the way, the specific error you got was because you put the concatenated slash in the wrong place. You concatenated 01/ instead of /01, so your string became 2022 / 1201/ instead of 2022 / 12/01. Oracle tolerates unnecessary spaces, but it can't work with delimiters in the wrong place.


Restrict search results to only documents user can see

Question: In my application, I have a content type called resource. In the resource content type, I have an entity reference that defines which roles should be able to view that resource.
When somebody is logged in as a certain role and does a search, he is able to view documents that don't belong to his role. How can I hook to the search results and remove the ones he should not be able to see?
Thanks
Answer: I think this module will help you Access by term and don't forget to enable Node access settings in search api settings.
Comment: This might help if I started using it in the beginning. But I have an existing application that I need to come up with a solution for given the structure that is currently in place on the website. Thanks.


Classification of, Information Regarding Particular Family of Polyhedra:

Question: Let $n\ge4$. Let $n$ vertices be distributed on a spherical boundary. Let the vertices lie on this boundary as would electrons on a spherical boundary. That is, they are distributed "equally" by electron repulsion.
Let $P$ be the convex polyhedron formed by connecting the vertices to their sphere-distance nearest neighbor vertices. P is an $n$-vertex approximation to a sphere. At $n\to\infty$, P is a sphere.
Below is an example with n = 30. The faces are not drawn, but an edge between every vertex triplet is drawn. This should at least provide some visualization of the shape I am describing.

I am looking for a name and/or information for/regarding this family of polyhedra. Alternatively, any tips with regards to my problem, below, would be appreciated.
Motivation: I am working on a software project in which it has become necessary to quickly graph polyhedra of this type. I am able to generate the vertices, but the only algorithm which I am able to discover to graph these polyhedra takes $O(V^{3})$ time. But, this draws every single face possible between extra triplet of vertices. The majority of these faces are inside of the shape and so are invisible. I expect that if I could learn more about these types of polyhedra that I should be able to realize an algorithm which only draws the outer faces, resulting in a much faster software solution.
Note: I did ask about this on StackOverflow before, but my question was not answered.
Answer: Given that all your points lie on a sphere, the polyhedron you want should be convex, so you can find it by computing the convex hull of the points. There are efficient $O(n\log n)$ algorithms for doing so, and lots of software available.
This is pretty much independent of the particular scheme by which you arranged these points, which is known as the Thomson problem.
(By the way, your statement that the polyhedron is "formed by connecting the vertices to their sphere-distance nearest neighbor vertices" is incorrect: this procedure would only give you a tree, not a polyhedron.)
Comment: I see. I will look into this and report back. Thank you! In response to your by the way: I meant that for each of the `n` vertices, connect the vertex `v` to each of `k` surrounding "closest" vertices with polygons by choosing them at least two at a time. Perhaps there is a better way to say this, but this is not particularly my domain, so if you could point out a more correct way to say this, I would appreciate it.)
Comment: It turns out that a algorithm to compute the convex full was precisely what I needed. Thank you very much.


Centering small element inside another element

Question: I'm making carousel pagination, which should looks like circle with small circle inside. The problem is centring of inner circle, which is always just a little bit on the side.
I've tried a lot ways of centring via tranforms, margins, calc top & left etc..

div {
  height: 13px;
  width: 13px;
  border: 1px solid black;
  border-radius: 50%;
  position: relative;
}

div::after {
  content: "";
  width: 8px;
  height: 8px;
  background-color: red;
  position: absolute;
  top: calc(50% - (8px / 2));
  left: calc(50% - (8px / 2));
  border-radius: 50%;
}

FIDDLE
I expect fully centered inner circle.
Comment: make the width/height of the element 14px instead
Comment: you can also simplify your code like this: https://jsfiddle.net/stLrgcn3/
Comment: elegant solution! @TemaniAfif
Answer: Make your pixels a even numbers to centering correctly like this:
div {
  height: 14px;
  width: 14px;
  border: 1px solid black;
  border-radius: 50%;
  position: relative;
}

Answer: Change like this
 div {
      height: 16px;
      width: 16px;
      border: 1px solid black;
      border-radius: 100%;
      position: relative;
    }

div::after {
  content: "";
  width: 8px;
  height: 8px;
  background-color: red;
  position: absolute;
  top: calc(50% - (8px / 2));
  left: calc(50% - (8px / 2));
  border-radius: 50%;
}

Answer: Even divisible.

div {
  height: 12px;
  width: 12px;
  border: 1px solid black;
  border-radius: 50%;
  position: relative;
}

div::after {
  content: "";
  width: 6px;
  height: 6px;
  background-color: red;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 50%;
}


Delta Method Confidence Interval: Dividing by $\sqrt{n}$

Question: To compute the (approximate) limiting (asymptotic) distribution of a function of a statistic with known (asymptotically normal) variance, the delta method can be invoked:
$\sqrt{n}[g(\hat{\theta}) - g(\theta)] \rightarrow_{d} N(0, \sigma^2[g'(\theta)]^2)$
In calculating a (1-$\alpha$)100% confidence interval for $g(\theta)$, is it necessary to divide Var[$g(\theta)$] = $\sigma^2[g'(\theta)]^2$ by $\sqrt{n}$?
I see some sources that do this, along with others that do not, which leads to some confusion.
I would say yes, since for example $\bar{X} \sim N(\mu, \frac{\sigma^2}{n})$.
Answer: If
$$
\sqrt{n}[g(\hat{\theta}) - g(\theta)] \rightarrow_{d} N(0, \sigma^2[g'(\theta)]^2)
$$
(note the typo you made in the variance term) then for a "large" $n$ it is approximately true that
$$
\sqrt{n}[g(\hat{\theta}) - g(\theta)] \sim N(0, \sigma^2[g'(\theta)]^2)
$$
which is true if and only if
$$
g(\hat{\theta})\sim N\left(g(\theta), \frac{\sigma^2[g'(\theta)]^2}{n}\right).
$$
Here $\frac{\sigma^2[g'(\theta)]^2}{n}$ is the (approximate) variance of $g(\hat{\theta})$, which means its (approximate) standard deviation is $\frac{\sigma|g'(\theta)|}{\sqrt{n}}$.


Nativescript 8 Screen freeze after splash screen is loaded in release build

Question: Guys I'm working on one of my own projects, and I'm using

nativescript 8.2.1 along with angular 13.2.0

I had some weird issue that is when we run the project using the following command

"ns run android"

application getting compiled and running on emulator fine.

but if I build to production and run it on an emulator I can only see a blank screen or white screen, here is the command used for that

"ns run android --clean --release --key-store-path "PATH/my-release-key.keystore" --key-store-password myPass --key-store-alias myAlias --key-store-alias-password myPass"

this is screenshot

This is what my root route looks like, redirection to home route is not working. but I tested if I add a button to app.component.html then I can see that button on the emulator screen. but routing is not working

This issue is caused when we only build with --release command otherwise debug mode it's working fine.
need your help on this
Answer: After spending multiple days of debugging, I finally, figure out the reason why the production build screen is getting frozen.

This is happening due to Firebase

I configure the firebase to my app referring through Nativescript version 8 documentation, here is the configuration that I have did
https://docs.nativescript.org/plugins/firebase-firestore.html

npm install @nativescript/firebase-firestore

<code>//importing firebase modules
import { firebase } from "@nativescript/firebase-core";
import "@nativescript/firebase-firestore";

//Initialize firebase as per nativescript documentation
await firebase().initializeApp();
</code>
in debug mode, this is working fine without any issue, but the production release builds it's not working.
For resolve this issue. I used a different firebase package.
here is the documentation link https://github.com/EddyVerbruggen/nativescript-plugin-firebase
if you are NativeScript 7+:

tns plugin add @nativescript/firebase

for NativeScript 6:

tns plugin add nativescript-plugin-firebase

Thanks..


Problemas em acertar o layout no Xcode

Question: Estou tendo dificuldade na seguinte questão. O botão azul na imagem abaixo tem que ficar na altura da cintura da mulher como está no storyboard, mas tem que ser em todos os iPhones (4" pra cima). Como pode ser visto no preview, para cada tamanho de tela o botão fica com tamanho e posição diferente. Para acertar isso eu tenho que usar alguma constraint especifica (sendo q estou usando altura, largura, margem de baixo, horizontal) ou tenho que acertar isso no código?
Obrigado.
Answer: Como o @danielbmarques falou deve funcionar:

• leading e trailing nas bordas

• centralizado vertical:

• seleciona a constraint e ajusta o multiplier:

• resultado esperado:
Comment: Muito obrigado, muito bem explicado. =D
Answer: Pro botão ficar com um tamanho proporcional, em vez de criar constraints pro tamanho dele, cria constraints pro leading e trailing. Assim as bordas dele vão ficar à mesma distância das laterais do iPhone.
Pro alinhamento vertical ficar proporcional, em vez de escolher uma distância, coloca o botão centralizado verticalmente, seleciona a constraint e brinca com o valor do "multiplier" até o botão ficar na posição que você quer.
Edit: Agora que estou pensando não sei se o leading e o trailing vão dar certo… você também pode colocar a largura do botão igual à largura da tela, e aí mexe com o multiplier dessa constraint pra deixar o botão maior ou menor.
Comment: blz, vou tentar. vlw

Problemas em acertar o layout no Xcode


PHP checking if two dates differs at least three months

Question: In php how to check if one date (given as string) differs to another date at least three month (unable to find any examples):
<code>$date1 = "2013-11-05";
$date2 = "2013-11-19";
//both dates is in form yyyy.mm.dd
differsThreeMonths($date1,$date2) { ???? return $differs; }
differsThreeMonths("2013-11-05","2014-05-02");//true
differsThreeMonths("2014-01-01","2014-04-01");//true
differsThreeMonths("2014-01-01","2014-03-31");//false
differsThreeMonths("2013-12-01","2014-01-15");//false
etc
</code>
Thank you
Comment: This is a start: http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php
Comment: simplest way is to convert both dates into unix timestamps by using `strtotime` then calculate the number of seconds contained in 3 months  then substract the dates and compare the difference against the number of seconds from those 3 months.
Answer: <code>$datetime1 = new DateTime('2013-07-01 12:00:00');
$datetime2 = new DateTime('2013-11-11 12:00:00');
$interval = $datetime1->diff($datetime2);
if(($interval->m>=3) || ($interval->y > 0))
echo "at least 3 months";
else
echo "Not greater than 3 months";
</code>
Comment: Change `$interval->m > 3` to `$interval->m >= 3`, since exactly 3 month also count.
Answer: <code>$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
var_dump($interaval);
</code>
http://www.php.net/manual/en/datetime.diff.php
Answer: Try:
<code>function differsThreeMonths($date_str1, $date_str2) {
    if (strlen($date_str1) > 0 && strlen($date_str2) > 0) {
        $date1 = new DateTime($date_str1);
        $date2 = new DateTime($date_str2);
        $since_start = $date1->diff($date2);
        return (($since_start->y > 0) || ($since_start->m >= 3));
    } else {
        return -1; // ERROR CODE HERE
    }
}
</code>
Comment: @DanielLi: It's meant for both actually. One uses variables, the other uses constants but the faulty logic it's exactly the same.
Comment: @DanielLi: Yes they do, yet the output is "Not greater then 3 month". This is because you are only comparing months and not also years.
Comment: @DanielLi: As for your last edit, it's also not accurate. It's seconds and not milliseconds and 3 months is more often than not not 7776000 seconds - even a day is not always 86400 seconds.
Comment: I would use your prior logic and just add another condition, like this: `return (($diff->y > 0) || ($diff->m >= 3));`.
Comment: @DanielLi: No it isn't: http://ideone.com/yE6G9Q. Also, 1 hour = 3600 seconds, 1 day = 86400. My prior comment about a day not always being 86400 seconds was due to occasional DST changes and UTC corrections.


alcohol, stability, experience

Question: Last night I went to a local bar and had a few dart matches with my friends. It was an enjoyable night for sure.
The first two matches were 701 games, and my performance was just as usual with an average PPR around 50. However, after consuming more and more alcohol, I couldn't keep my hand steady. I just missed all the targets I aimed at, especially during the Cricket matches played afterwards. My MPR dropped from 1.8 to somewhere below 1.0. The phenomenon found on myself could be concluded as drink more, miss more.
I would like to know if this is a common thing among dart players. Since I have seen players still played very well after drinking quite a lot of beer, I wonder whether this is related to darting experiences.
By the way, is there any way to improve such drink more, miss more situation?
Answer: Your experienced in the bar of an initial improvement, then a decline, has also been studied in a controlled environment. Researchers T. Reilly and J. Scott summarized their study as follows:

Light (0.02% BAC) and moderate (0.05% BAC) does of alcohol were
  administered to 10 dart throwers while effects were monitored on tasks
  related to dart throwing, i.e., rotary pursuit and hand steadiness.
  Balance and accuracy of throwing improved with the 0.02% BAC, but
  performance was impaired with 0.05% BAC. The higher BAC levels were
  linked with deteriorations on rotary pursuit and hand steadiness.

So for optimal performance, you need to keep your alcohol level fairly low but non-zero.
The blood alcohol level depends on a lot of factors:, including:

The presence of food in your stomach
Number of drinks per hour.
Tolerance to alcohol, or learned tolerance
Weight
Gender

One solution would be to drink 1-2 beers (or whatever you need to get to about 0.02 % BAC), then switch to non-alcoholic drinks, and have another beer or two when you finish playing.
If you want to keep drinking, and keep playing darts well after the first couple of beers, you will need to eat something in the bar (crisps are traditional), consume alcohol regularly, and put on some weight. You may notice that drinking regularly and eating crisps are a quick and easy way to put on weight. This may answer the question posed, but also bring health risks, so I personally wouldn't recommend it.
Comment: Great answer with cool scientific evidence! Thanks for your information. FYI, I drank two glasses of Mojito in one and a half hour. Was it too much?

alcohol, stability, experience


IReport Tibco - Erro no processamento de XML: nenhum elemento encontrado

Question: Olá !!
É o seguinte estou com problemas na geração do relatório ,estou usando jsf,hibernate,mysql
segue meu bean.
@Named
@RequestScoped
public class RelatorioBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private List<Funcionario> listaFuncionariosRel;
    private Funcionario funcionarioSelecionadosPDF;

    @Inject
    private Funcionarios funcionarios;

    @Inject
    private EntityManager manager;//

    @Inject
    private FacesContext facesContext;//

    @Inject
    private HttpServletResponse response;//

    public Funcionarios getFuncionarios() {
        return funcionarios;
    }

    public void setFuncionarios(Funcionarios funcionarios) {
        this.funcionarios = funcionarios;
    }

    public List<Funcionario> getListaFuncionariosRel() {
        return listaFuncionariosRel;
    }

    public void setListaFuncionariosRel(List<Funcionario> listaFuncionariosRel) {
        this.listaFuncionariosRel = listaFuncionariosRel;
    }

    public Funcionario getFuncionarioSelecionadosPDF() {
        return funcionarioSelecionadosPDF;
    }

    public void setFuncionarioSelecionadosPDF(Funcionario funcionarioSelecionadosPDF) {
        this.funcionarioSelecionadosPDF = funcionarioSelecionadosPDF;
    }

    public void exporterPdf() {//não estou usando este..método
        try {

            FacesContext facesContext = FacesContext.getCurrentInstance();
            ExternalContext ec = facesContext.getExternalContext();
            HttpServletResponse response = (HttpServletResponse) ec.getResponse();

            //InputStream caminho = getClass().getResourceAsStream("/Ireport/func.jrxml");//acrescentei
            Map<String, Object> params = new HashMap<>();//.getCpf()

            params.put("cpf_Funcionario", funcionarioSelecionadosPDF.getCpf());

            /*response.reset();
            response.setContentType("application/pdf");//tbm
            response.setHeader("Content-disposition", "inline; filename=relatorio.pdf");*/
            ec.responseReset();
            ec.setResponseContentType("application/pdf");
            ec.setResponseHeader("Content-disposition", "inline; filename=relatorio.pdf");

            OutputStream saida = ec.getResponseOutputStream();

            GeradorDeRelatorios gerador = new GeradorDeRelatorios();
            gerador.geraPDF("/Ireport/func.jrxml", params, saida);

            JasperReport pathReport = JasperCompileManager.compileReport("/Ireport/func.jrxml");

            saida.close();
            facesContext.getResponseComplete();

        } catch (IOException ex) {
            FacesUtil.addErrorMessage("Erro 1: " + ex.getMessage());
        } catch (JRException ex) {
            FacesUtil.addErrorMessage("Erro 2: " + ex.getMessage());
        }
    }

    public void exportPdf2() {

        Map<String, Object> params = new HashMap<>();
        //params.put("cpf",this.listarDadosRel());
        params.put("cpf_Funcionario", this.funcionarioSelecionadosPDF);
        ExecutorReport execute = new ExecutorReport("/Ireport/func.jasper",
                this.response, params, "Funcionario.pdf");
        Session session = manager.unwrap(Session.class);
        session.doWork(execute);
        facesContext.responseComplete();

    }

}

Minha outra classe ExecutorReport
public class ExecutorReport implements Work {

    private String caminhoReport;
    private HttpServletResponse response;
    private Map<String,Object>params;
    private String nomeArquivo;

    public ExecutorReport(String caminhoReport, HttpServletResponse response, Map<String, Object> params, String nomeArquivo) {
        this.caminhoReport = caminhoReport;
        this.response = response;
        this.params = params;
        this.nomeArquivo = nomeArquivo;
    }

    @Override
    public void execute(Connection connection) throws SQLException {
        try{
        InputStream relatorioStream = this.getClass().getResourceAsStream(nomeArquivo);
        JasperPrint print = JasperFillManager.fillReport(relatorioStream,this.params,connection);

        JRExporter  exportador = new JRPdfExporter();

        exportador.setParameter(JRExporterParameter.OUTPUT_STREAM,response.getOutputStream());
        exportador.setParameter(JRExporterParameter.JASPER_PRINT,print);

        response.setContentType("application/pdf");
        exportador.exportReport();

    }catch(Exception e ){
        throw new SQLException("erro ao gerar "+this.caminhoReport);
    }

    }

}

mensagem do apache
Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type FacesContext with qualifiers @Default

Comment: está surgindo isso no log do apache...              `com.sun.faces.context.ExceptionHandlerImpl.log getOutputStream() has already been called for this response
 java.lang.IllegalStateException: getOutputStream() has already been called for this response`
Answer: Ele está entendendo que sua saída é xhtml, deveria ser PDF:
response.setContentType("application/pdf");
E também deveria haver um header para sua saída:
            response.setHeader(
                "Content-disposition",
                "inline;filename="teste.pdf");

Não tenho como testar sua implementação, mas segue um exemplo completo:
try {
        JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
        JasperReport jasperReport = JasperCompileManager
                .compileReport(jasperDesign);
        JasperPrint jasperPrint = JasperFillManager.fillReport(
                jasperReport, parameters, conection);
        // Gera saida em PDF em uma servlet
        HttpServletResponse response = (HttpServletResponse) context
                .getExternalContext().getResponse();
        response.setContentType("application/pdf");
        Calendar gc = GregorianCalendar.getInstance();
        response.setHeader(
                "Content-disposition",
                "inline;filename=" + report + gc.get(Calendar.YEAR) + ""
                        + gc.get(Calendar.MONTH) + ""
                        + gc.get(Calendar.DAY_OF_MONTH) + ""
                        + gc.get(Calendar.HOUR_OF_DAY) + ""
                        + gc.get(Calendar.MINUTE) + ""
                        + gc.get(Calendar.SECOND) + ".pdf");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Pragma", "No-cache");
        ServletOutputStream servletOutputStream = response
                .getOutputStream();

        JasperExportManager.exportReportToPdfStream(jasperPrint,
                servletOutputStream);

        servletOutputStream.flush();
        servletOutputStream.close();

    } catch (JRException ex) {
        throw new SystemException(ex);
    }
    context.responseComplete();

Comment: Norivan..Eu segui este mesmo exemplo... que você colocou e a aplicação agora ela nem sobe :/ mensagem do apache `Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type FacesContext with qualifiers @Default`  O que faço ??
Comment: aew quando eu tiro as importações `@Inject
private EntityManager manager ``@Inject
private FacesContext facesContext;``@Inject
private HttpServletResponse response;`    e quando chamo o método `exporterPdf()` aew a aplicação sobe ... e até lista ... mas não exporta para pdf exibe está mensagem ...  `getOutputStream() has already been called for this response`  no navegador
Comment: são estes problemas...um eu sigo o exemplo da algaworks que seria o void exportPdf2()  que a aplicação não sobe.. o outro até sobe mas não exporta...
Comment: o erro é este .... ` WELD-001408: Unsatisfied dependencies for type FacesContext with qualifiers `
Comment: consegui mudar as  dependencias do faceContext   -- o erro mudou agora exibe este ... `Caused by: javax.faces.el.EvaluationException: org.hibernate.exception.GenericJDBCException: error executing work` meu caminho do relatorio estou chamando certo.O que poderia ser ?
Comment: Parece que o SGBD fechou a conexão. Mostre todo o Stack
Answer: Aew pegou ...eu criei uma nova classe no pacote .util
public class UtilFaces {

public UtilFaces() {
}
public FacesContext getFacesContext() {
    return FacesContext.getCurrentInstance();
}
public ExternalContext getExternalContext() {
    return getFacesContext().getExternalContext();
}
public HttpServletRequest getRequest() {
    return (HttpServletRequest) getExternalContext().getRequest();
}
public HttpServletResponse getResponse() {
    return (HttpServletResponse) getExternalContext().getResponse();
}
public HttpSession getHttpSession(){
    return (HttpSession) getFacesContext().getExternalContext().getSession(false);
}
public ServletContext getServletContext(){
    return (ServletContext) getExternalContext().getContext();
}
public void msg(String destination,String msg){
    FacesMessage message = new FacesMessage(msg);
    getFacesContext().addMessage(destination, message);
}
public static void addErrorMessage(Exception ex, String defaultMsg) {
    String msg = ex.getLocalizedMessage();
    if (msg != null && msg.length() > 0) {
        addErrorMessage(msg);
    } else {
        addErrorMessage(defaultMsg);
    }
}
public static void addErrorMessages(List<String> messages) {
    for (String message : messages) {
        addErrorMessage(message);
    }
}
public static void addErrorMessage(String msg) {
    FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
    FacesContext.getCurrentInstance().addMessage(null, facesMsg);
}
public static void addSuccessMessage(String msg) {
    FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
    FacesContext.getCurrentInstance().addMessage("successInfo", facesMsg);
}
public static void addWarnMessage(String msg) {
    FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_WARN, msg, msg);
    FacesContext.getCurrentInstance().addMessage("warnInfo", facesMsg);
}
public static void addFatalMessage(String msg) {
    FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, msg, msg);
    FacesContext.getCurrentInstance().addMessage("fatalInfo", facesMsg);
}

}
e tbm atualizei o método que chama o relatório ...
aew a classe que fez pegar
public class ExecutorReport implements Work {

private String caminhoRelatorio;
private HttpServletResponse response;
private Map<String,Object>parametros;
private String nomeArquivoSaida;

private boolean relatorioGerado;

public ExecutorReport(String caminhoRelatorio, HttpServletResponse response, Map<String, Object> parametros, String nomeArquivoSaida) {
    this.caminhoRelatorio = caminhoRelatorio;
    this.response = response;
    this.parametros= parametros;
    this.nomeArquivoSaida = nomeArquivoSaida;

    this.parametros.put(JRParameter.REPORT_LOCALE, new Locale("pt", "BR"));
}

@Override
public void execute(Connection connection) throws SQLException {
    try{
    InputStream relatorioStream = this.getClass().getResourceAsStream(this.caminhoRelatorio);
    JasperPrint print = JasperFillManager.fillReport(relatorioStream,this.parametros,connection);
     this.relatorioGerado = print.getPages().size()>0;

      if(this.relatorioGerado){
          Exporter<ExporterInput,PdfReportConfiguration,PdfExporterConfiguration,
                  OutputStreamExporterOutput> exportador = new JRPdfExporter();
                  exportador.setExporterInput(new SimpleExporterInput(print));
                  exportador.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));

                  response.setContentType("application/pdf");
                  response.setHeader("Content-Disposition","attachment; filename=\""
                  +this.nomeArquivoSaida + "\"");
                  exportador.exportReport();

}
        } catch (Exception e) {
            throw new SQLException("Erro ao executar relatório " + this.caminhoRelatorio, e);
        }
    }
public boolean isRelatorioGerado() {
    return relatorioGerado;
}

}


What's the difference between managing certificates for a user account and for a computer account?

Question: We have some domain-joined computers that were unable to import a third party root cert as a trusted cert provider.  In trying to fix this, I noticed that when we go to use the certificate management snap-in, we get a prompt like in the screenclip below.

My question is, what's the difference between the user account and the computer account in the certificate management snap-in?
Comment: I believe if you import it with the computer account, the certificate will be added to everyone's account whereas if you use a user account it will only be added to that specific user.
Comment: @lbanz but after import the cert as trusted ca provider, I still see it as untrusted when I double click on the cer file
Answer: The difference is exactly what it says. With Windows, certificates get assigned to accounts.  So, if you want to apply a certificate to a specific computer, that's done by assigning the certificate to the computer account.  This is a slight difference that's mainly just semantic when compared to *nix systems, where a user-certificate would be stored in the user's directory some where, and a computer certificate would typically be found in a system directory somewhere.
Of course, as you noticed with your problem, the difference is that the computer account applies to the machine, and the user account applies to the user.  If you need your machine to be authenticated with public key crypto (like an SSL cert for https, as the most common example), the certificate needs to be associated with the machine, not the user.  If it's a user that you want to authenticate, rather than the whole machine, the certificate needs to be associated with the user.
Practically speaking, the difference you'll see in the certificate management snap-in is which "personal" certificate store you see and are able to manage - the one for the user account or the computer account... or for a service account, if you select that one.  As you can see in the screenclip below, on my company workstation, my user has a certificate for code signing purposes, and my computer has a certificate for authentication when using secured protocols (RDP, HTTPS, TLS, etc.) - and they're different certificate stores, which you can see from their different paths.
As a result, my user can sign the PowerShell scripts I create, but my machine cannot.  This is important, because the whole reason that I set up code signing certificates was because other coworkers were causing problems deploying broken copy-pasta scripts to our production servers, and I don't want them to get around that by simply logging on to my machine.  Similarly, my user cannot claim to be machine, because my user doesn't have my machine certificate.

Don't ask me why Microsoft didn't design their certificate management snap-in so that you could view the user's and the machine's personal certificate stores at the same time in the same window, but they didn't.  I would have done it differently, if they'd asked me, but instead, they paid someone else ungodly sums of money for something worse.
So because it makes a difference which "Personal" certificate store you're managing, and Microsoft paid someone other than me to design and create their certificate management snap-in, you have to select which account's certificates you want to manage when you add the snap-in.
Comment: You can just add a second (or more) instance of the Certificates snap-in in the same MMC console.  One for Computer, one for user.
Comment: The answer is good, but maybe the rant about the UI (and especially about the payment of UI designers) could have been omitted...